claude-mpm 3.9.11__py3-none-any.whl → 4.0.3__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 (419) hide show
  1. claude_mpm/VERSION +1 -1
  2. claude_mpm/__init__.py +2 -2
  3. claude_mpm/__main__.py +3 -2
  4. claude_mpm/agents/__init__.py +85 -79
  5. claude_mpm/agents/agent_loader.py +464 -1003
  6. claude_mpm/agents/agent_loader_integration.py +45 -45
  7. claude_mpm/agents/agents_metadata.py +29 -30
  8. claude_mpm/agents/async_agent_loader.py +156 -138
  9. claude_mpm/agents/base_agent.json +1 -1
  10. claude_mpm/agents/base_agent_loader.py +179 -151
  11. claude_mpm/agents/frontmatter_validator.py +229 -130
  12. claude_mpm/agents/schema/agent_schema.json +1 -1
  13. claude_mpm/agents/system_agent_config.py +213 -147
  14. claude_mpm/agents/templates/__init__.py +13 -13
  15. claude_mpm/agents/templates/code_analyzer.json +2 -2
  16. claude_mpm/agents/templates/data_engineer.json +1 -1
  17. claude_mpm/agents/templates/documentation.json +23 -11
  18. claude_mpm/agents/templates/engineer.json +22 -6
  19. claude_mpm/agents/templates/memory_manager.json +1 -1
  20. claude_mpm/agents/templates/ops.json +2 -2
  21. claude_mpm/agents/templates/project_organizer.json +1 -1
  22. claude_mpm/agents/templates/qa.json +1 -1
  23. claude_mpm/agents/templates/refactoring_engineer.json +222 -0
  24. claude_mpm/agents/templates/research.json +20 -14
  25. claude_mpm/agents/templates/security.json +1 -1
  26. claude_mpm/agents/templates/ticketing.json +1 -1
  27. claude_mpm/agents/templates/version_control.json +1 -1
  28. claude_mpm/agents/templates/web_qa.json +3 -1
  29. claude_mpm/agents/templates/web_ui.json +2 -2
  30. claude_mpm/cli/__init__.py +79 -51
  31. claude_mpm/cli/__main__.py +3 -2
  32. claude_mpm/cli/commands/__init__.py +20 -20
  33. claude_mpm/cli/commands/agents.py +279 -247
  34. claude_mpm/cli/commands/aggregate.py +138 -157
  35. claude_mpm/cli/commands/cleanup.py +147 -147
  36. claude_mpm/cli/commands/config.py +93 -76
  37. claude_mpm/cli/commands/info.py +17 -16
  38. claude_mpm/cli/commands/mcp.py +140 -905
  39. claude_mpm/cli/commands/mcp_command_router.py +139 -0
  40. claude_mpm/cli/commands/mcp_config_commands.py +20 -0
  41. claude_mpm/cli/commands/mcp_install_commands.py +20 -0
  42. claude_mpm/cli/commands/mcp_server_commands.py +175 -0
  43. claude_mpm/cli/commands/mcp_tool_commands.py +34 -0
  44. claude_mpm/cli/commands/memory.py +239 -203
  45. claude_mpm/cli/commands/monitor.py +203 -81
  46. claude_mpm/cli/commands/run.py +380 -429
  47. claude_mpm/cli/commands/run_config_checker.py +160 -0
  48. claude_mpm/cli/commands/socketio_monitor.py +235 -0
  49. claude_mpm/cli/commands/tickets.py +305 -197
  50. claude_mpm/cli/parser.py +24 -1156
  51. claude_mpm/cli/parsers/__init__.py +29 -0
  52. claude_mpm/cli/parsers/agents_parser.py +136 -0
  53. claude_mpm/cli/parsers/base_parser.py +331 -0
  54. claude_mpm/cli/parsers/config_parser.py +85 -0
  55. claude_mpm/cli/parsers/mcp_parser.py +152 -0
  56. claude_mpm/cli/parsers/memory_parser.py +138 -0
  57. claude_mpm/cli/parsers/monitor_parser.py +104 -0
  58. claude_mpm/cli/parsers/run_parser.py +147 -0
  59. claude_mpm/cli/parsers/tickets_parser.py +203 -0
  60. claude_mpm/cli/ticket_cli.py +7 -3
  61. claude_mpm/cli/utils.py +55 -37
  62. claude_mpm/cli_module/__init__.py +6 -6
  63. claude_mpm/cli_module/args.py +188 -140
  64. claude_mpm/cli_module/commands.py +79 -70
  65. claude_mpm/cli_module/migration_example.py +38 -60
  66. claude_mpm/config/__init__.py +32 -25
  67. claude_mpm/config/agent_config.py +151 -119
  68. claude_mpm/config/experimental_features.py +71 -73
  69. claude_mpm/config/paths.py +94 -208
  70. claude_mpm/config/socketio_config.py +84 -73
  71. claude_mpm/constants.py +35 -18
  72. claude_mpm/core/__init__.py +9 -6
  73. claude_mpm/core/agent_name_normalizer.py +68 -71
  74. claude_mpm/core/agent_registry.py +372 -521
  75. claude_mpm/core/agent_session_manager.py +74 -63
  76. claude_mpm/core/base_service.py +116 -87
  77. claude_mpm/core/cache.py +119 -153
  78. claude_mpm/core/claude_runner.py +425 -1120
  79. claude_mpm/core/config.py +263 -168
  80. claude_mpm/core/config_aliases.py +69 -61
  81. claude_mpm/core/config_constants.py +292 -0
  82. claude_mpm/core/constants.py +57 -99
  83. claude_mpm/core/container.py +211 -178
  84. claude_mpm/core/exceptions.py +233 -89
  85. claude_mpm/core/factories.py +92 -54
  86. claude_mpm/core/framework_loader.py +378 -220
  87. claude_mpm/core/hook_manager.py +198 -83
  88. claude_mpm/core/hook_performance_config.py +136 -0
  89. claude_mpm/core/injectable_service.py +61 -55
  90. claude_mpm/core/interactive_session.py +165 -155
  91. claude_mpm/core/interfaces.py +221 -195
  92. claude_mpm/core/lazy.py +96 -96
  93. claude_mpm/core/logger.py +133 -107
  94. claude_mpm/core/logging_config.py +185 -157
  95. claude_mpm/core/minimal_framework_loader.py +20 -15
  96. claude_mpm/core/mixins.py +30 -29
  97. claude_mpm/core/oneshot_session.py +215 -181
  98. claude_mpm/core/optimized_agent_loader.py +134 -138
  99. claude_mpm/core/optimized_startup.py +159 -157
  100. claude_mpm/core/pm_hook_interceptor.py +85 -72
  101. claude_mpm/core/service_registry.py +103 -101
  102. claude_mpm/core/session_manager.py +97 -87
  103. claude_mpm/core/socketio_pool.py +212 -158
  104. claude_mpm/core/tool_access_control.py +58 -51
  105. claude_mpm/core/types.py +46 -24
  106. claude_mpm/core/typing_utils.py +166 -82
  107. claude_mpm/core/unified_agent_registry.py +721 -0
  108. claude_mpm/core/unified_config.py +550 -0
  109. claude_mpm/core/unified_paths.py +549 -0
  110. claude_mpm/dashboard/index.html +1 -1
  111. claude_mpm/dashboard/open_dashboard.py +51 -17
  112. claude_mpm/dashboard/static/css/dashboard.css +27 -8
  113. claude_mpm/dashboard/static/dist/components/agent-inference.js +2 -0
  114. claude_mpm/dashboard/static/dist/components/event-processor.js +2 -0
  115. claude_mpm/dashboard/static/dist/components/event-viewer.js +2 -0
  116. claude_mpm/dashboard/static/dist/components/export-manager.js +2 -0
  117. claude_mpm/dashboard/static/dist/components/file-tool-tracker.js +2 -0
  118. claude_mpm/dashboard/static/dist/components/hud-library-loader.js +2 -0
  119. claude_mpm/dashboard/static/dist/components/hud-manager.js +2 -0
  120. claude_mpm/dashboard/static/dist/components/hud-visualizer.js +2 -0
  121. claude_mpm/dashboard/static/dist/components/module-viewer.js +2 -0
  122. claude_mpm/dashboard/static/dist/components/session-manager.js +2 -0
  123. claude_mpm/dashboard/static/dist/components/socket-manager.js +2 -0
  124. claude_mpm/dashboard/static/dist/components/ui-state-manager.js +2 -0
  125. claude_mpm/dashboard/static/dist/components/working-directory.js +2 -0
  126. claude_mpm/dashboard/static/dist/dashboard.js +2 -0
  127. claude_mpm/dashboard/static/dist/socket-client.js +2 -0
  128. claude_mpm/dashboard/static/js/components/agent-inference.js +80 -76
  129. claude_mpm/dashboard/static/js/components/event-processor.js +71 -67
  130. claude_mpm/dashboard/static/js/components/event-viewer.js +74 -70
  131. claude_mpm/dashboard/static/js/components/export-manager.js +31 -28
  132. claude_mpm/dashboard/static/js/components/file-tool-tracker.js +106 -92
  133. claude_mpm/dashboard/static/js/components/hud-library-loader.js +11 -11
  134. claude_mpm/dashboard/static/js/components/hud-manager.js +73 -73
  135. claude_mpm/dashboard/static/js/components/hud-visualizer.js +163 -163
  136. claude_mpm/dashboard/static/js/components/module-viewer.js +305 -233
  137. claude_mpm/dashboard/static/js/components/session-manager.js +32 -29
  138. claude_mpm/dashboard/static/js/components/socket-manager.js +27 -20
  139. claude_mpm/dashboard/static/js/components/ui-state-manager.js +21 -18
  140. claude_mpm/dashboard/static/js/components/working-directory.js +74 -71
  141. claude_mpm/dashboard/static/js/dashboard.js +178 -453
  142. claude_mpm/dashboard/static/js/extension-error-handler.js +164 -0
  143. claude_mpm/dashboard/static/js/socket-client.js +120 -54
  144. claude_mpm/dashboard/templates/index.html +40 -50
  145. claude_mpm/experimental/cli_enhancements.py +60 -58
  146. claude_mpm/generators/__init__.py +1 -1
  147. claude_mpm/generators/agent_profile_generator.py +75 -65
  148. claude_mpm/hooks/__init__.py +1 -1
  149. claude_mpm/hooks/base_hook.py +33 -28
  150. claude_mpm/hooks/claude_hooks/__init__.py +1 -1
  151. claude_mpm/hooks/claude_hooks/connection_pool.py +120 -0
  152. claude_mpm/hooks/claude_hooks/event_handlers.py +743 -0
  153. claude_mpm/hooks/claude_hooks/hook_handler.py +415 -1331
  154. claude_mpm/hooks/claude_hooks/hook_wrapper.sh +4 -4
  155. claude_mpm/hooks/claude_hooks/memory_integration.py +221 -0
  156. claude_mpm/hooks/claude_hooks/response_tracking.py +348 -0
  157. claude_mpm/hooks/claude_hooks/tool_analysis.py +230 -0
  158. claude_mpm/hooks/memory_integration_hook.py +140 -100
  159. claude_mpm/hooks/tool_call_interceptor.py +89 -76
  160. claude_mpm/hooks/validation_hooks.py +57 -49
  161. claude_mpm/init.py +145 -121
  162. claude_mpm/models/__init__.py +9 -9
  163. claude_mpm/models/agent_definition.py +33 -23
  164. claude_mpm/models/agent_session.py +228 -200
  165. claude_mpm/scripts/__init__.py +1 -1
  166. claude_mpm/scripts/socketio_daemon.py +192 -75
  167. claude_mpm/scripts/socketio_server_manager.py +328 -0
  168. claude_mpm/scripts/start_activity_logging.py +25 -22
  169. claude_mpm/services/__init__.py +68 -43
  170. claude_mpm/services/agent_capabilities_service.py +271 -0
  171. claude_mpm/services/agents/__init__.py +23 -32
  172. claude_mpm/services/agents/deployment/__init__.py +3 -3
  173. claude_mpm/services/agents/deployment/agent_config_provider.py +310 -0
  174. claude_mpm/services/agents/deployment/agent_configuration_manager.py +359 -0
  175. claude_mpm/services/agents/deployment/agent_definition_factory.py +84 -0
  176. claude_mpm/services/agents/deployment/agent_deployment.py +415 -2113
  177. claude_mpm/services/agents/deployment/agent_discovery_service.py +387 -0
  178. claude_mpm/services/agents/deployment/agent_environment_manager.py +293 -0
  179. claude_mpm/services/agents/deployment/agent_filesystem_manager.py +387 -0
  180. claude_mpm/services/agents/deployment/agent_format_converter.py +453 -0
  181. claude_mpm/services/agents/deployment/agent_frontmatter_validator.py +161 -0
  182. claude_mpm/services/agents/deployment/agent_lifecycle_manager.py +345 -495
  183. claude_mpm/services/agents/deployment/agent_metrics_collector.py +279 -0
  184. claude_mpm/services/agents/deployment/agent_restore_handler.py +88 -0
  185. claude_mpm/services/agents/deployment/agent_template_builder.py +406 -0
  186. claude_mpm/services/agents/deployment/agent_validator.py +352 -0
  187. claude_mpm/services/agents/deployment/agent_version_manager.py +313 -0
  188. claude_mpm/services/agents/deployment/agent_versioning.py +6 -9
  189. claude_mpm/services/agents/deployment/agents_directory_resolver.py +79 -0
  190. claude_mpm/services/agents/deployment/async_agent_deployment.py +298 -234
  191. claude_mpm/services/agents/deployment/config/__init__.py +13 -0
  192. claude_mpm/services/agents/deployment/config/deployment_config.py +182 -0
  193. claude_mpm/services/agents/deployment/config/deployment_config_manager.py +200 -0
  194. claude_mpm/services/agents/deployment/deployment_config_loader.py +54 -0
  195. claude_mpm/services/agents/deployment/deployment_type_detector.py +124 -0
  196. claude_mpm/services/agents/deployment/facade/__init__.py +18 -0
  197. claude_mpm/services/agents/deployment/facade/async_deployment_executor.py +159 -0
  198. claude_mpm/services/agents/deployment/facade/deployment_executor.py +73 -0
  199. claude_mpm/services/agents/deployment/facade/deployment_facade.py +270 -0
  200. claude_mpm/services/agents/deployment/facade/sync_deployment_executor.py +178 -0
  201. claude_mpm/services/agents/deployment/interface_adapter.py +227 -0
  202. claude_mpm/services/agents/deployment/lifecycle_health_checker.py +85 -0
  203. claude_mpm/services/agents/deployment/lifecycle_performance_tracker.py +100 -0
  204. claude_mpm/services/agents/deployment/pipeline/__init__.py +32 -0
  205. claude_mpm/services/agents/deployment/pipeline/pipeline_builder.py +158 -0
  206. claude_mpm/services/agents/deployment/pipeline/pipeline_context.py +159 -0
  207. claude_mpm/services/agents/deployment/pipeline/pipeline_executor.py +169 -0
  208. claude_mpm/services/agents/deployment/pipeline/steps/__init__.py +19 -0
  209. claude_mpm/services/agents/deployment/pipeline/steps/agent_processing_step.py +195 -0
  210. claude_mpm/services/agents/deployment/pipeline/steps/base_step.py +119 -0
  211. claude_mpm/services/agents/deployment/pipeline/steps/configuration_step.py +79 -0
  212. claude_mpm/services/agents/deployment/pipeline/steps/target_directory_step.py +90 -0
  213. claude_mpm/services/agents/deployment/pipeline/steps/validation_step.py +100 -0
  214. claude_mpm/services/agents/deployment/processors/__init__.py +15 -0
  215. claude_mpm/services/agents/deployment/processors/agent_deployment_context.py +98 -0
  216. claude_mpm/services/agents/deployment/processors/agent_deployment_result.py +235 -0
  217. claude_mpm/services/agents/deployment/processors/agent_processor.py +258 -0
  218. claude_mpm/services/agents/deployment/refactored_agent_deployment_service.py +318 -0
  219. claude_mpm/services/agents/deployment/results/__init__.py +13 -0
  220. claude_mpm/services/agents/deployment/results/deployment_metrics.py +200 -0
  221. claude_mpm/services/agents/deployment/results/deployment_result_builder.py +249 -0
  222. claude_mpm/services/agents/deployment/strategies/__init__.py +25 -0
  223. claude_mpm/services/agents/deployment/strategies/base_strategy.py +119 -0
  224. claude_mpm/services/agents/deployment/strategies/project_strategy.py +150 -0
  225. claude_mpm/services/agents/deployment/strategies/strategy_selector.py +117 -0
  226. claude_mpm/services/agents/deployment/strategies/system_strategy.py +116 -0
  227. claude_mpm/services/agents/deployment/strategies/user_strategy.py +137 -0
  228. claude_mpm/services/agents/deployment/system_instructions_deployer.py +108 -0
  229. claude_mpm/services/agents/deployment/validation/__init__.py +19 -0
  230. claude_mpm/services/agents/deployment/validation/agent_validator.py +323 -0
  231. claude_mpm/services/agents/deployment/validation/deployment_validator.py +238 -0
  232. claude_mpm/services/agents/deployment/validation/template_validator.py +299 -0
  233. claude_mpm/services/agents/deployment/validation/validation_result.py +226 -0
  234. claude_mpm/services/agents/loading/__init__.py +2 -2
  235. claude_mpm/services/agents/loading/agent_profile_loader.py +259 -229
  236. claude_mpm/services/agents/loading/base_agent_manager.py +90 -81
  237. claude_mpm/services/agents/loading/framework_agent_loader.py +154 -129
  238. claude_mpm/services/agents/management/__init__.py +2 -2
  239. claude_mpm/services/agents/management/agent_capabilities_generator.py +72 -58
  240. claude_mpm/services/agents/management/agent_management_service.py +209 -156
  241. claude_mpm/services/agents/memory/__init__.py +9 -6
  242. claude_mpm/services/agents/memory/agent_memory_manager.py +218 -1152
  243. claude_mpm/services/agents/memory/agent_persistence_service.py +20 -16
  244. claude_mpm/services/agents/memory/analyzer.py +430 -0
  245. claude_mpm/services/agents/memory/content_manager.py +376 -0
  246. claude_mpm/services/agents/memory/template_generator.py +468 -0
  247. claude_mpm/services/agents/registry/__init__.py +7 -10
  248. claude_mpm/services/agents/registry/deployed_agent_discovery.py +122 -97
  249. claude_mpm/services/agents/registry/modification_tracker.py +351 -285
  250. claude_mpm/services/async_session_logger.py +187 -153
  251. claude_mpm/services/claude_session_logger.py +87 -72
  252. claude_mpm/services/command_handler_service.py +217 -0
  253. claude_mpm/services/communication/__init__.py +3 -2
  254. claude_mpm/services/core/__init__.py +50 -97
  255. claude_mpm/services/core/base.py +60 -53
  256. claude_mpm/services/core/interfaces/__init__.py +188 -0
  257. claude_mpm/services/core/interfaces/agent.py +351 -0
  258. claude_mpm/services/core/interfaces/communication.py +343 -0
  259. claude_mpm/services/core/interfaces/infrastructure.py +413 -0
  260. claude_mpm/services/core/interfaces/service.py +434 -0
  261. claude_mpm/services/core/interfaces.py +19 -944
  262. claude_mpm/services/event_aggregator.py +208 -170
  263. claude_mpm/services/exceptions.py +387 -308
  264. claude_mpm/services/framework_claude_md_generator/__init__.py +75 -79
  265. claude_mpm/services/framework_claude_md_generator/content_assembler.py +69 -60
  266. claude_mpm/services/framework_claude_md_generator/content_validator.py +65 -61
  267. claude_mpm/services/framework_claude_md_generator/deployment_manager.py +68 -49
  268. claude_mpm/services/framework_claude_md_generator/section_generators/__init__.py +34 -34
  269. claude_mpm/services/framework_claude_md_generator/section_generators/agents.py +25 -22
  270. claude_mpm/services/framework_claude_md_generator/section_generators/claude_pm_init.py +10 -10
  271. claude_mpm/services/framework_claude_md_generator/section_generators/core_responsibilities.py +4 -3
  272. claude_mpm/services/framework_claude_md_generator/section_generators/delegation_constraints.py +4 -3
  273. claude_mpm/services/framework_claude_md_generator/section_generators/environment_config.py +4 -3
  274. claude_mpm/services/framework_claude_md_generator/section_generators/footer.py +6 -5
  275. claude_mpm/services/framework_claude_md_generator/section_generators/header.py +8 -7
  276. claude_mpm/services/framework_claude_md_generator/section_generators/orchestration_principles.py +4 -3
  277. claude_mpm/services/framework_claude_md_generator/section_generators/role_designation.py +6 -5
  278. claude_mpm/services/framework_claude_md_generator/section_generators/subprocess_validation.py +9 -8
  279. claude_mpm/services/framework_claude_md_generator/section_generators/todo_task_tools.py +4 -3
  280. claude_mpm/services/framework_claude_md_generator/section_generators/troubleshooting.py +5 -4
  281. claude_mpm/services/framework_claude_md_generator/section_manager.py +28 -27
  282. claude_mpm/services/framework_claude_md_generator/version_manager.py +30 -28
  283. claude_mpm/services/hook_service.py +106 -114
  284. claude_mpm/services/infrastructure/__init__.py +7 -5
  285. claude_mpm/services/infrastructure/context_preservation.py +233 -199
  286. claude_mpm/services/infrastructure/daemon_manager.py +279 -0
  287. claude_mpm/services/infrastructure/logging.py +83 -76
  288. claude_mpm/services/infrastructure/monitoring.py +547 -404
  289. claude_mpm/services/mcp_gateway/__init__.py +30 -13
  290. claude_mpm/services/mcp_gateway/config/__init__.py +2 -2
  291. claude_mpm/services/mcp_gateway/config/config_loader.py +61 -56
  292. claude_mpm/services/mcp_gateway/config/config_schema.py +50 -41
  293. claude_mpm/services/mcp_gateway/config/configuration.py +82 -75
  294. claude_mpm/services/mcp_gateway/core/__init__.py +13 -20
  295. claude_mpm/services/mcp_gateway/core/base.py +80 -67
  296. claude_mpm/services/mcp_gateway/core/exceptions.py +60 -46
  297. claude_mpm/services/mcp_gateway/core/interfaces.py +87 -84
  298. claude_mpm/services/mcp_gateway/main.py +287 -137
  299. claude_mpm/services/mcp_gateway/registry/__init__.py +1 -1
  300. claude_mpm/services/mcp_gateway/registry/service_registry.py +97 -94
  301. claude_mpm/services/mcp_gateway/registry/tool_registry.py +135 -126
  302. claude_mpm/services/mcp_gateway/server/__init__.py +2 -2
  303. claude_mpm/services/mcp_gateway/server/mcp_gateway.py +105 -110
  304. claude_mpm/services/mcp_gateway/server/stdio_handler.py +105 -107
  305. claude_mpm/services/mcp_gateway/server/stdio_server.py +691 -0
  306. claude_mpm/services/mcp_gateway/tools/__init__.py +4 -2
  307. claude_mpm/services/mcp_gateway/tools/base_adapter.py +109 -119
  308. claude_mpm/services/mcp_gateway/tools/document_summarizer.py +283 -215
  309. claude_mpm/services/mcp_gateway/tools/hello_world.py +122 -120
  310. claude_mpm/services/mcp_gateway/tools/ticket_tools.py +652 -0
  311. claude_mpm/services/mcp_gateway/tools/unified_ticket_tool.py +606 -0
  312. claude_mpm/services/memory/__init__.py +2 -2
  313. claude_mpm/services/memory/builder.py +451 -362
  314. claude_mpm/services/memory/cache/__init__.py +2 -2
  315. claude_mpm/services/memory/cache/shared_prompt_cache.py +232 -194
  316. claude_mpm/services/memory/cache/simple_cache.py +107 -93
  317. claude_mpm/services/memory/indexed_memory.py +195 -193
  318. claude_mpm/services/memory/optimizer.py +267 -234
  319. claude_mpm/services/memory/router.py +571 -263
  320. claude_mpm/services/memory_hook_service.py +237 -0
  321. claude_mpm/services/port_manager.py +223 -0
  322. claude_mpm/services/project/__init__.py +3 -3
  323. claude_mpm/services/project/analyzer.py +451 -305
  324. claude_mpm/services/project/registry.py +262 -240
  325. claude_mpm/services/recovery_manager.py +287 -231
  326. claude_mpm/services/response_tracker.py +87 -67
  327. claude_mpm/services/runner_configuration_service.py +587 -0
  328. claude_mpm/services/session_management_service.py +304 -0
  329. claude_mpm/services/socketio/__init__.py +4 -4
  330. claude_mpm/services/socketio/client_proxy.py +174 -0
  331. claude_mpm/services/socketio/handlers/__init__.py +3 -3
  332. claude_mpm/services/socketio/handlers/base.py +44 -30
  333. claude_mpm/services/socketio/handlers/connection.py +145 -65
  334. claude_mpm/services/socketio/handlers/file.py +123 -108
  335. claude_mpm/services/socketio/handlers/git.py +607 -373
  336. claude_mpm/services/socketio/handlers/hook.py +170 -0
  337. claude_mpm/services/socketio/handlers/memory.py +4 -4
  338. claude_mpm/services/socketio/handlers/project.py +4 -4
  339. claude_mpm/services/socketio/handlers/registry.py +53 -38
  340. claude_mpm/services/socketio/server/__init__.py +18 -0
  341. claude_mpm/services/socketio/server/broadcaster.py +252 -0
  342. claude_mpm/services/socketio/server/core.py +399 -0
  343. claude_mpm/services/socketio/server/main.py +323 -0
  344. claude_mpm/services/socketio_client_manager.py +160 -133
  345. claude_mpm/services/socketio_server.py +36 -1885
  346. claude_mpm/services/subprocess_launcher_service.py +316 -0
  347. claude_mpm/services/system_instructions_service.py +258 -0
  348. claude_mpm/services/ticket_manager.py +19 -533
  349. claude_mpm/services/utility_service.py +285 -0
  350. claude_mpm/services/version_control/__init__.py +18 -21
  351. claude_mpm/services/version_control/branch_strategy.py +20 -10
  352. claude_mpm/services/version_control/conflict_resolution.py +37 -13
  353. claude_mpm/services/version_control/git_operations.py +52 -21
  354. claude_mpm/services/version_control/semantic_versioning.py +92 -53
  355. claude_mpm/services/version_control/version_parser.py +145 -125
  356. claude_mpm/services/version_service.py +270 -0
  357. claude_mpm/storage/__init__.py +2 -2
  358. claude_mpm/storage/state_storage.py +177 -181
  359. claude_mpm/ticket_wrapper.py +2 -2
  360. claude_mpm/utils/__init__.py +2 -2
  361. claude_mpm/utils/agent_dependency_loader.py +453 -243
  362. claude_mpm/utils/config_manager.py +157 -118
  363. claude_mpm/utils/console.py +1 -1
  364. claude_mpm/utils/dependency_cache.py +102 -107
  365. claude_mpm/utils/dependency_manager.py +52 -47
  366. claude_mpm/utils/dependency_strategies.py +131 -96
  367. claude_mpm/utils/environment_context.py +110 -102
  368. claude_mpm/utils/error_handler.py +75 -55
  369. claude_mpm/utils/file_utils.py +80 -67
  370. claude_mpm/utils/framework_detection.py +12 -11
  371. claude_mpm/utils/import_migration_example.py +12 -60
  372. claude_mpm/utils/imports.py +48 -45
  373. claude_mpm/utils/path_operations.py +100 -93
  374. claude_mpm/utils/robust_installer.py +172 -164
  375. claude_mpm/utils/session_logging.py +30 -23
  376. claude_mpm/utils/subprocess_utils.py +99 -61
  377. claude_mpm/validation/__init__.py +1 -1
  378. claude_mpm/validation/agent_validator.py +151 -111
  379. claude_mpm/validation/frontmatter_validator.py +92 -71
  380. {claude_mpm-3.9.11.dist-info → claude_mpm-4.0.3.dist-info}/METADATA +27 -1
  381. claude_mpm-4.0.3.dist-info/RECORD +402 -0
  382. {claude_mpm-3.9.11.dist-info → claude_mpm-4.0.3.dist-info}/entry_points.txt +1 -0
  383. {claude_mpm-3.9.11.dist-info → claude_mpm-4.0.3.dist-info}/licenses/LICENSE +1 -1
  384. claude_mpm/cli/commands/run_guarded.py +0 -511
  385. claude_mpm/config/memory_guardian_config.py +0 -325
  386. claude_mpm/config/memory_guardian_yaml.py +0 -335
  387. claude_mpm/core/config_paths.py +0 -150
  388. claude_mpm/core/memory_aware_runner.py +0 -353
  389. claude_mpm/dashboard/static/js/dashboard-original.js +0 -4134
  390. claude_mpm/deployment_paths.py +0 -261
  391. claude_mpm/hooks/claude_hooks/hook_handler_fixed.py +0 -454
  392. claude_mpm/models/state_models.py +0 -433
  393. claude_mpm/services/agent/__init__.py +0 -24
  394. claude_mpm/services/agent/deployment.py +0 -2548
  395. claude_mpm/services/agent/management.py +0 -598
  396. claude_mpm/services/agent/registry.py +0 -813
  397. claude_mpm/services/agents/registry/agent_registry.py +0 -813
  398. claude_mpm/services/communication/socketio.py +0 -1935
  399. claude_mpm/services/communication/websocket.py +0 -479
  400. claude_mpm/services/framework_claude_md_generator.py +0 -624
  401. claude_mpm/services/health_monitor.py +0 -893
  402. claude_mpm/services/infrastructure/graceful_degradation.py +0 -616
  403. claude_mpm/services/infrastructure/health_monitor.py +0 -775
  404. claude_mpm/services/infrastructure/memory_dashboard.py +0 -479
  405. claude_mpm/services/infrastructure/memory_guardian.py +0 -944
  406. claude_mpm/services/infrastructure/restart_protection.py +0 -642
  407. claude_mpm/services/infrastructure/state_manager.py +0 -774
  408. claude_mpm/services/mcp_gateway/manager.py +0 -334
  409. claude_mpm/services/optimized_hook_service.py +0 -542
  410. claude_mpm/services/project_analyzer.py +0 -864
  411. claude_mpm/services/project_registry.py +0 -608
  412. claude_mpm/services/standalone_socketio_server.py +0 -1300
  413. claude_mpm/services/ticket_manager_di.py +0 -318
  414. claude_mpm/services/ticketing_service_original.py +0 -510
  415. claude_mpm/utils/paths.py +0 -395
  416. claude_mpm/utils/platform_memory.py +0 -524
  417. claude_mpm-3.9.11.dist-info/RECORD +0 -306
  418. {claude_mpm-3.9.11.dist-info → claude_mpm-4.0.3.dist-info}/WHEEL +0 -0
  419. {claude_mpm-3.9.11.dist-info → claude_mpm-4.0.3.dist-info}/top_level.txt +0 -0
@@ -1,3 +1,5 @@
1
+ from pathlib import Path
2
+
1
3
  """
2
4
  Memory command implementation for claude-mpm.
3
5
 
@@ -12,102 +14,103 @@ with other command modules like agents.py.
12
14
  import json
13
15
  import os
14
16
  from datetime import datetime
15
- from pathlib import Path
16
17
 
17
18
  import click
18
19
 
19
- from ...core.logger import get_logger
20
20
  from ...core.config import Config
21
+ from ...core.logger import get_logger
21
22
  from ...services.agents.memory import AgentMemoryManager
22
23
 
23
24
 
24
25
  def manage_memory(args):
25
26
  """
26
27
  Manage agent memory files.
27
-
28
+
28
29
  WHY: Agents need persistent memory to maintain learnings across sessions.
29
30
  This command provides a unified interface for memory-related operations.
30
-
31
+
31
32
  DESIGN DECISION: When no subcommand is provided, we show memory status
32
33
  as the default action, giving users a quick overview of the memory system.
33
-
34
+
34
35
  Args:
35
36
  args: Parsed command line arguments with memory_command attribute
36
37
  """
37
38
  logger = get_logger("cli")
38
-
39
+
39
40
  try:
40
41
  # Load configuration for memory manager
41
42
  config = Config()
42
43
  # Use CLAUDE_MPM_USER_PWD if available (when called via shell script),
43
44
  # otherwise use current working directory
44
- user_pwd = os.environ.get('CLAUDE_MPM_USER_PWD', os.getcwd())
45
+ user_pwd = os.environ.get("CLAUDE_MPM_USER_PWD", os.getcwd())
45
46
  current_dir = Path(user_pwd)
46
47
  memory_manager = AgentMemoryManager(config, current_dir)
47
-
48
+
48
49
  if not args.memory_command:
49
50
  # No subcommand - show status
50
51
  _show_status(memory_manager)
51
52
  return
52
-
53
+
53
54
  if args.memory_command == "status":
54
55
  _show_status(memory_manager)
55
-
56
+
56
57
  elif args.memory_command == "view":
57
58
  _show_memories(args, memory_manager)
58
-
59
+
59
60
  elif args.memory_command == "add":
60
61
  _add_learning(args, memory_manager)
61
-
62
+
62
63
  elif args.memory_command == "clean":
63
64
  _clean_memory(args, memory_manager)
64
-
65
+
65
66
  elif args.memory_command == "optimize":
66
67
  _optimize_memory(args, memory_manager)
67
-
68
+
68
69
  elif args.memory_command == "build":
69
70
  _build_memory(args, memory_manager)
70
-
71
+
71
72
  elif args.memory_command == "cross-ref":
72
73
  _cross_reference_memory(args, memory_manager)
73
-
74
+
74
75
  elif args.memory_command == "route":
75
76
  _route_memory_command(args, memory_manager)
76
-
77
+
77
78
  elif args.memory_command == "show":
78
79
  _show_memories(args, memory_manager)
79
-
80
+
80
81
  elif args.memory_command == "init":
81
82
  _init_memory(args, memory_manager)
82
-
83
+
83
84
  else:
84
85
  logger.error(f"Unknown memory command: {args.memory_command}")
85
86
  print(f"Unknown memory command: {args.memory_command}")
86
- print("Available commands: init, status, view, add, clean, optimize, build, cross-ref, route, show")
87
+ print(
88
+ "Available commands: init, status, view, add, clean, optimize, build, cross-ref, route, show"
89
+ )
87
90
  return 1
88
-
91
+
89
92
  except Exception as e:
90
93
  logger.error(f"Error managing memory: {e}")
91
94
  print(f"❌ Error: {e}")
92
95
  return 1
93
-
96
+
94
97
  return 0
95
98
 
96
99
 
97
100
  def _init_memory(args, memory_manager):
98
101
  """
99
102
  Initialize project-specific memories via agent delegation.
100
-
103
+
101
104
  WHY: When starting with a new project, agents need project-specific knowledge
102
105
  beyond what automatic analysis provides. This command triggers an agent task
103
106
  to comprehensively scan the project and create custom memories.
104
-
107
+
105
108
  Args:
106
109
  args: Command line arguments (unused but kept for consistency)
107
110
  memory_manager: AgentMemoryManager instance
108
111
  """
109
112
  logger = get_logger("cli")
110
-
113
+
111
114
  print("🚀 Initializing project-specific memories...")
112
115
  print("=" * 80)
113
116
  print()
@@ -147,9 +150,15 @@ def _init_memory(args, memory_manager):
147
150
  print(" • Domain-specific terminology and concepts")
148
151
  print()
149
152
  print("Example commands to use:")
150
- print(' claude-mpm memory add engineer pattern "Use dependency injection with @inject"')
151
- print(' claude-mpm memory add qa pattern "Test files follow test_<module>_<feature>.py"')
152
- print(' claude-mpm memory add research context "Project uses microservices architecture"')
153
+ print(
154
+ ' claude-mpm memory add engineer pattern "Use dependency injection with @inject"'
155
+ )
156
+ print(
157
+ ' claude-mpm memory add qa pattern "Test files follow test_<module>_<feature>.py"'
158
+ )
159
+ print(
160
+ ' claude-mpm memory add research context "Project uses microservices architecture"'
161
+ )
153
162
  print()
154
163
  print("Begin by examining the project structure and key files.")
155
164
  print()
@@ -157,46 +166,50 @@ def _init_memory(args, memory_manager):
157
166
  print()
158
167
  print("📝 Note: Copy the task above to execute the memory initialization process.")
159
168
  print(" Use 'claude-mpm memory add' commands to add discovered insights.")
160
-
169
+
161
170
 
162
171
  def _show_status(memory_manager):
163
172
  """
164
173
  Show comprehensive memory system status.
165
-
174
+
166
175
  WHY: Users need to see memory system health, file sizes, optimization
167
176
  opportunities, and agent-specific statistics to understand the system state.
168
-
177
+
169
178
  Args:
170
179
  memory_manager: AgentMemoryManager instance
171
180
  """
172
181
  print("Agent Memory System Status")
173
182
  print("-" * 80)
174
-
183
+
175
184
  try:
176
185
  # Get comprehensive status from memory manager
177
186
  status = memory_manager.get_memory_status()
178
-
187
+
179
188
  if not status.get("success", True):
180
189
  print(f"❌ Error getting status: {status.get('error', 'Unknown error')}")
181
190
  return
182
-
191
+
183
192
  # Show system overview
184
193
  system_health = status.get("system_health", "unknown")
185
194
  health_emoji = {
186
195
  "healthy": "✅",
187
196
  "needs_optimization": "⚠️",
188
197
  "high_usage": "📊",
189
- "no_memory_dir": "📁"
198
+ "no_memory_dir": "📁",
190
199
  }.get(system_health, "❓")
191
-
200
+
192
201
  print(f"🧠 Memory System Health: {health_emoji} {system_health}")
193
202
  print(f"📁 Memory Directory: {status.get('memory_directory', 'Unknown')}")
194
- print(f"🔧 System Enabled: {'Yes' if status.get('system_enabled', True) else 'No'}")
195
- print(f"📚 Auto Learning: {'Yes' if status.get('auto_learning', True) else 'No'}")
203
+ print(
204
+ f"🔧 System Enabled: {'Yes' if status.get('system_enabled', True) else 'No'}"
205
+ )
206
+ print(
207
+ f"📚 Auto Learning: {'Yes' if status.get('auto_learning', True) else 'No'}"
208
+ )
196
209
  print(f"📊 Total Agents: {status.get('total_agents', 0)}")
197
210
  print(f"💾 Total Size: {status.get('total_size_kb', 0):.1f} KB")
198
211
  print()
199
-
212
+
200
213
  # Show optimization opportunities
201
214
  opportunities = status.get("optimization_opportunities", [])
202
215
  if opportunities:
@@ -206,7 +219,7 @@ def _show_status(memory_manager):
206
219
  if len(opportunities) > 5:
207
220
  print(f" ... and {len(opportunities) - 5} more")
208
221
  print()
209
-
222
+
210
223
  # Show per-agent details
211
224
  agents = status.get("agents", {})
212
225
  if agents:
@@ -215,7 +228,7 @@ def _show_status(memory_manager):
215
228
  if "error" in agent_info:
216
229
  print(f" ❌ {agent_id}: Error - {agent_info['error']}")
217
230
  continue
218
-
231
+
219
232
  size_kb = agent_info.get("size_kb", 0)
220
233
  size_limit = agent_info.get("size_limit_kb", 8)
221
234
  utilization = agent_info.get("size_utilization", 0)
@@ -223,15 +236,16 @@ def _show_status(memory_manager):
223
236
  items = agent_info.get("items", 0)
224
237
  last_modified = agent_info.get("last_modified", "Unknown")
225
238
  auto_learning = agent_info.get("auto_learning", True)
226
-
239
+
227
240
  # Format last modified time
228
241
  try:
229
242
  from datetime import datetime
230
- dt = datetime.fromisoformat(last_modified.replace('Z', '+00:00'))
231
- last_modified_str = dt.strftime('%Y-%m-%d %H:%M:%S')
243
+
244
+ dt = datetime.fromisoformat(last_modified.replace("Z", "+00:00"))
245
+ last_modified_str = dt.strftime("%Y-%m-%d %H:%M:%S")
232
246
  except:
233
247
  last_modified_str = last_modified
234
-
248
+
235
249
  # Status indicator based on usage
236
250
  if utilization > 90:
237
251
  status_emoji = "🔴" # High usage
@@ -239,15 +253,17 @@ def _show_status(memory_manager):
239
253
  status_emoji = "🟡" # Medium usage
240
254
  else:
241
255
  status_emoji = "🟢" # Low usage
242
-
256
+
243
257
  print(f" {status_emoji} {agent_id}")
244
- print(f" Size: {size_kb:.1f} KB / {size_limit} KB ({utilization:.1f}%)")
258
+ print(
259
+ f" Size: {size_kb:.1f} KB / {size_limit} KB ({utilization:.1f}%)"
260
+ )
245
261
  print(f" Content: {sections} sections, {items} items")
246
262
  print(f" Auto-learning: {'On' if auto_learning else 'Off'}")
247
263
  print(f" Last modified: {last_modified_str}")
248
264
  else:
249
265
  print("📭 No agent memories found")
250
-
266
+
251
267
  except Exception as e:
252
268
  print(f"❌ Error showing status: {e}")
253
269
  # Fallback to basic status display
@@ -257,59 +273,59 @@ def _show_status(memory_manager):
257
273
  def _show_basic_status(memory_manager):
258
274
  """Fallback basic status display if comprehensive status fails."""
259
275
  print("\n--- Basic Status (Fallback) ---")
260
-
276
+
261
277
  memory_dir = memory_manager.memories_dir
262
278
  if not memory_dir.exists():
263
279
  print("📁 Memory directory not found - no agent memories stored yet")
264
280
  print(f" Expected location: {memory_dir}")
265
281
  return
266
-
282
+
267
283
  memory_files = list(memory_dir.glob("*_agent.md"))
268
-
284
+
269
285
  if not memory_files:
270
286
  print("📭 No memory files found")
271
287
  print(f" Memory directory: {memory_dir}")
272
288
  return
273
-
289
+
274
290
  print(f"📁 Memory directory: {memory_dir}")
275
291
  print(f"📊 Total memory files: {len(memory_files)}")
276
-
292
+
277
293
  total_size = 0
278
294
  for file_path in sorted(memory_files):
279
295
  stat = file_path.stat()
280
296
  size_kb = stat.st_size / 1024
281
297
  total_size += stat.st_size
282
-
283
- agent_id = file_path.stem.replace('_agent', '')
298
+
299
+ agent_id = file_path.stem.replace("_agent", "")
284
300
  print(f" {agent_id}: {size_kb:.1f} KB")
285
-
301
+
286
302
  print(f"💾 Total size: {total_size / 1024:.1f} KB")
287
303
 
288
304
 
289
305
  def _view_memory(args, memory_manager):
290
306
  """
291
307
  View agent memory file contents.
292
-
308
+
293
309
  WHY: Users need to inspect what learnings an agent has accumulated
294
310
  to understand its behavior and debug issues.
295
-
311
+
296
312
  Args:
297
313
  args: Command arguments with agent_id
298
314
  memory_manager: AgentMemoryManager instance
299
315
  """
300
316
  agent_id = args.agent_id
301
-
317
+
302
318
  try:
303
319
  memory_content = memory_manager.load_agent_memory(agent_id)
304
-
320
+
305
321
  if not memory_content:
306
322
  print(f"📭 No memory found for agent: {agent_id}")
307
323
  return
308
-
324
+
309
325
  print(f"🧠 Memory for agent: {agent_id}")
310
326
  print("-" * 80)
311
327
  print(memory_content)
312
-
328
+
313
329
  except FileNotFoundError:
314
330
  print(f"📭 No memory file found for agent: {agent_id}")
315
331
  except Exception as e:
@@ -319,10 +335,10 @@ def _view_memory(args, memory_manager):
319
335
  def _add_learning(args, memory_manager):
320
336
  """
321
337
  Manually add learning to agent memory.
322
-
338
+
323
339
  WHY: Allows manual injection of learnings for testing or correction
324
340
  purposes, useful for debugging and development.
325
-
341
+
326
342
  Args:
327
343
  args: Command arguments with agent_id, learning_type, and content
328
344
  memory_manager: AgentMemoryManager instance
@@ -330,28 +346,28 @@ def _add_learning(args, memory_manager):
330
346
  agent_id = args.agent_id
331
347
  section = args.learning_type # Map learning_type to section name
332
348
  content = args.content
333
-
349
+
334
350
  # Map learning types to appropriate sections
335
351
  section_map = {
336
352
  "pattern": "Project Architecture",
337
353
  "error": "Common Mistakes to Avoid",
338
354
  "optimization": "Implementation Guidelines",
339
355
  "preference": "Implementation Guidelines",
340
- "context": "Current Technical Context"
356
+ "context": "Current Technical Context",
341
357
  }
342
-
358
+
343
359
  section_name = section_map.get(section, "Current Technical Context")
344
-
360
+
345
361
  try:
346
362
  success = memory_manager.update_agent_memory(agent_id, section_name, content)
347
-
363
+
348
364
  if success:
349
365
  print(f"✅ Added {section} to {agent_id} memory in section: {section_name}")
350
366
  print(f" Content: {content[:100]}{'...' if len(content) > 100 else ''}")
351
367
  else:
352
368
  print(f"❌ Failed to add learning to {agent_id} memory")
353
369
  print(" Memory file may be at size limit or section may be full")
354
-
370
+
355
371
  except Exception as e:
356
372
  print(f"❌ Error adding learning: {e}")
357
373
 
@@ -359,31 +375,31 @@ def _add_learning(args, memory_manager):
359
375
  def _clean_memory(args, memory_manager):
360
376
  """
361
377
  Clean up old/unused memory files.
362
-
378
+
363
379
  WHY: Memory files can accumulate over time. This provides a way to
364
380
  clean up old or unused files to save disk space.
365
-
381
+
366
382
  DESIGN DECISION: For Phase 1, this is a stub implementation.
367
383
  Full cleanup logic will be implemented based on usage patterns.
368
-
384
+
369
385
  Args:
370
386
  args: Command arguments
371
387
  memory_manager: AgentMemoryManager instance
372
388
  """
373
389
  print("🧹 Memory cleanup")
374
390
  print("-" * 80)
375
-
391
+
376
392
  # For Phase 1, just show what would be cleaned
377
393
  memory_dir = memory_manager.memories_dir
378
394
  if not memory_dir.exists():
379
395
  print("📁 No memory directory found - nothing to clean")
380
396
  return
381
-
397
+
382
398
  memory_files = list(memory_dir.glob("*_agent.md"))
383
399
  if not memory_files:
384
400
  print("📭 No memory files found - nothing to clean")
385
401
  return
386
-
402
+
387
403
  print(f"📊 Found {len(memory_files)} memory files")
388
404
  print()
389
405
  print("⚠️ Cleanup not yet implemented in Phase 1")
@@ -396,20 +412,20 @@ def _clean_memory(args, memory_manager):
396
412
  def _optimize_memory(args, memory_manager):
397
413
  """
398
414
  Optimize memory files by removing duplicates and consolidating similar items.
399
-
415
+
400
416
  WHY: Memory files can become cluttered over time with duplicate or redundant
401
417
  information. This command provides automated cleanup while preserving
402
418
  important learnings.
403
-
419
+
404
420
  Args:
405
421
  args: Command arguments with optional agent_id
406
422
  memory_manager: AgentMemoryManager instance
407
423
  """
408
424
  print("🔧 Memory Optimization")
409
425
  print("-" * 80)
410
-
411
- agent_id = getattr(args, 'agent_id', None)
412
-
426
+
427
+ agent_id = getattr(args, "agent_id", None)
428
+
413
429
  try:
414
430
  if agent_id:
415
431
  print(f"📊 Optimizing memory for agent: {agent_id}")
@@ -417,7 +433,7 @@ def _optimize_memory(args, memory_manager):
417
433
  else:
418
434
  print("📊 Optimizing all agent memories...")
419
435
  result = memory_manager.optimize_memory()
420
-
436
+
421
437
  if result.get("success"):
422
438
  if agent_id:
423
439
  # Single agent results
@@ -427,7 +443,7 @@ def _optimize_memory(args, memory_manager):
427
443
  _display_bulk_optimization_results(result)
428
444
  else:
429
445
  print(f"❌ Optimization failed: {result.get('error', 'Unknown error')}")
430
-
446
+
431
447
  except Exception as e:
432
448
  print(f"❌ Error during optimization: {e}")
433
449
 
@@ -435,52 +451,54 @@ def _optimize_memory(args, memory_manager):
435
451
  def _build_memory(args, memory_manager):
436
452
  """
437
453
  Build agent memories from project documentation.
438
-
454
+
439
455
  WHY: Project documentation contains valuable patterns and guidelines that
440
456
  agents should be aware of. This command automatically extracts and assigns
441
457
  relevant information to appropriate agents.
442
-
458
+
443
459
  Args:
444
460
  args: Command arguments with optional force_rebuild flag
445
461
  memory_manager: AgentMemoryManager instance
446
462
  """
447
463
  print("📚 Memory Building from Documentation")
448
464
  print("-" * 80)
449
-
450
- force_rebuild = getattr(args, 'force_rebuild', False)
451
-
465
+
466
+ force_rebuild = getattr(args, "force_rebuild", False)
467
+
452
468
  try:
453
469
  print("🔍 Analyzing project documentation...")
454
470
  result = memory_manager.build_memories_from_docs(force_rebuild)
455
-
471
+
456
472
  if result.get("success"):
457
473
  print(f"✅ Successfully processed documentation")
458
474
  print(f" Files processed: {result.get('files_processed', 0)}")
459
475
  print(f" Memories created: {result.get('memories_created', 0)}")
460
476
  print(f" Memories updated: {result.get('memories_updated', 0)}")
461
477
  print(f" Agents affected: {result.get('total_agents_affected', 0)}")
462
-
463
- if result.get('agents_affected'):
478
+
479
+ if result.get("agents_affected"):
464
480
  print(f" Affected agents: {', '.join(result['agents_affected'])}")
465
-
481
+
466
482
  # Show file-specific results
467
- files_results = result.get('files', {})
483
+ files_results = result.get("files", {})
468
484
  if files_results:
469
485
  print("\n📄 File processing details:")
470
486
  for file_path, file_result in files_results.items():
471
- if file_result.get('success'):
472
- extracted = file_result.get('items_extracted', 0)
473
- created = file_result.get('memories_created', 0)
474
- print(f" {file_path}: {extracted} items extracted, {created} memories created")
475
-
476
- if result.get('errors'):
487
+ if file_result.get("success"):
488
+ extracted = file_result.get("items_extracted", 0)
489
+ created = file_result.get("memories_created", 0)
490
+ print(
491
+ f" {file_path}: {extracted} items extracted, {created} memories created"
492
+ )
493
+
494
+ if result.get("errors"):
477
495
  print("\n⚠️ Errors encountered:")
478
- for error in result['errors']:
496
+ for error in result["errors"]:
479
497
  print(f" {error}")
480
-
498
+
481
499
  else:
482
500
  print(f"❌ Build failed: {result.get('error', 'Unknown error')}")
483
-
501
+
484
502
  except Exception as e:
485
503
  print(f"❌ Error building memories: {e}")
486
504
 
@@ -488,60 +506,62 @@ def _build_memory(args, memory_manager):
488
506
  def _cross_reference_memory(args, memory_manager):
489
507
  """
490
508
  Find cross-references and common patterns across agent memories.
491
-
509
+
492
510
  WHY: Different agents may have learned similar information or there may be
493
511
  knowledge gaps that can be identified through cross-referencing.
494
-
512
+
495
513
  Args:
496
514
  args: Command arguments with optional query
497
515
  memory_manager: AgentMemoryManager instance
498
516
  """
499
517
  print("🔗 Memory Cross-Reference Analysis")
500
518
  print("-" * 80)
501
-
502
- query = getattr(args, 'query', None)
503
-
519
+
520
+ query = getattr(args, "query", None)
521
+
504
522
  try:
505
523
  if query:
506
524
  print(f"🔍 Searching for: '{query}'")
507
525
  else:
508
526
  print("🔍 Analyzing all agent memories for patterns...")
509
-
527
+
510
528
  result = memory_manager.cross_reference_memories(query)
511
-
529
+
512
530
  if result.get("success") is False:
513
531
  print(f"❌ Analysis failed: {result.get('error', 'Unknown error')}")
514
532
  return
515
-
533
+
516
534
  # Display common patterns
517
535
  common_patterns = result.get("common_patterns", [])
518
536
  if common_patterns:
519
537
  print(f"\n🔄 Common patterns found ({len(common_patterns)}):")
520
538
  for pattern in common_patterns[:10]: # Show top 10
521
- agents = ', '.join(pattern['agents'])
539
+ agents = ", ".join(pattern["agents"])
522
540
  print(f" • {pattern['pattern']}")
523
541
  print(f" Found in: {agents} ({pattern['count']} instances)")
524
542
  else:
525
543
  print("\n🔄 No common patterns found")
526
-
544
+
527
545
  # Display query matches if query was provided
528
546
  if query and result.get("query_matches"):
529
547
  print(f"\n🎯 Query matches for '{query}':")
530
548
  for match in result["query_matches"]:
531
549
  print(f" 📋 {match['agent']}:")
532
- for line in match['matches'][:3]: # Show first 3 matches
550
+ for line in match["matches"][:3]: # Show first 3 matches
533
551
  print(f" • {line}")
534
-
552
+
535
553
  # Display agent correlations
536
554
  correlations = result.get("agent_correlations", {})
537
555
  if correlations:
538
556
  print(f"\n🤝 Agent knowledge correlations:")
539
- sorted_correlations = sorted(correlations.items(), key=lambda x: x[1], reverse=True)
557
+ sorted_correlations = sorted(
558
+ correlations.items(), key=lambda x: x[1], reverse=True
559
+ )
540
560
  for agents, count in sorted_correlations[:5]: # Show top 5
541
561
  print(f" {agents}: {count} common items")
542
562
  else:
543
563
  print("\n🤝 No significant correlations found")
544
-
564
+
545
565
  except Exception as e:
546
566
  print(f"❌ Error during cross-reference analysis: {e}")
547
567
 
@@ -549,22 +569,22 @@ def _cross_reference_memory(args, memory_manager):
549
569
  def _show_memories(args, memory_manager):
550
570
  """
551
571
  Show agent memories in a user-friendly format with cross-references and patterns.
552
-
572
+
553
573
  WHY: Users need to see agent memories in a readable format to understand
554
574
  what agents have learned and identify common patterns across agents.
555
-
575
+
556
576
  DESIGN DECISION: Added --raw flag to output structured JSON data for
557
577
  programmatic processing, enabling external tools and scripts to access
558
578
  all agent memories in a structured format.
559
-
579
+
560
580
  Args:
561
581
  args: Command arguments with optional agent_id, format, and raw flag
562
582
  memory_manager: AgentMemoryManager instance
563
583
  """
564
- agent_id = getattr(args, 'agent_id', None)
565
- format_type = getattr(args, 'format', 'detailed')
566
- raw_output = getattr(args, 'raw', False)
567
-
584
+ agent_id = getattr(args, "agent_id", None)
585
+ format_type = getattr(args, "format", "detailed")
586
+ raw_output = getattr(args, "raw", False)
587
+
568
588
  try:
569
589
  if raw_output:
570
590
  # Output structured JSON data
@@ -578,19 +598,19 @@ def _show_memories(args, memory_manager):
578
598
  # Normal user-friendly display
579
599
  print("🧠 Agent Memories Display")
580
600
  print("-" * 80)
581
-
601
+
582
602
  if agent_id:
583
603
  _show_single_agent_memory(agent_id, format_type, memory_manager)
584
604
  else:
585
605
  _show_all_agent_memories(format_type, memory_manager)
586
-
606
+
587
607
  except Exception as e:
588
608
  if raw_output:
589
609
  # Output error in JSON format for consistency
590
610
  error_output = {
591
611
  "success": False,
592
612
  "error": str(e),
593
- "timestamp": datetime.now().isoformat()
613
+ "timestamp": datetime.now().isoformat(),
594
614
  }
595
615
  print(json.dumps(error_output, indent=2))
596
616
  else:
@@ -600,20 +620,20 @@ def _show_memories(args, memory_manager):
600
620
  def _show_single_agent_memory(agent_id, format_type, memory_manager):
601
621
  """Show memory for a single agent in the specified format."""
602
622
  memory_content = memory_manager.load_agent_memory(agent_id)
603
-
623
+
604
624
  if not memory_content:
605
625
  print(f"📭 No memory found for agent: {agent_id}")
606
626
  return
607
-
627
+
608
628
  print(f"🤖 Agent: {agent_id}")
609
629
  print("-" * 40)
610
-
611
- if format_type == 'full':
630
+
631
+ if format_type == "full":
612
632
  print(memory_content)
613
633
  else:
614
634
  # Parse and display memory sections
615
635
  sections = _parse_memory_content(memory_content)
616
-
636
+
617
637
  for section_name, items in sections.items():
618
638
  if items:
619
639
  print(f"\n📚 {section_name} ({len(items)} items):")
@@ -630,44 +650,44 @@ def _show_all_agent_memories(format_type, memory_manager):
630
650
  if not memory_dir.exists():
631
651
  print("📁 No memory directory found")
632
652
  return
633
-
653
+
634
654
  memory_files = list(memory_dir.glob("*_agent.md"))
635
655
  if not memory_files:
636
656
  print("📭 No agent memories found")
637
657
  return
638
-
658
+
639
659
  print(f"📊 Found memories for {len(memory_files)} agents")
640
660
  print()
641
-
661
+
642
662
  agent_memories = {}
643
663
  total_items = 0
644
-
664
+
645
665
  # Load all agent memories
646
666
  for file_path in sorted(memory_files):
647
- agent_id = file_path.stem.replace('_agent', '')
667
+ agent_id = file_path.stem.replace("_agent", "")
648
668
  try:
649
669
  memory_content = memory_manager.load_agent_memory(agent_id)
650
670
  if memory_content:
651
671
  sections = _parse_memory_content(memory_content)
652
672
  agent_memories[agent_id] = sections
653
-
673
+
654
674
  # Count items
655
675
  item_count = sum(len(items) for items in sections.values())
656
676
  total_items += item_count
657
-
658
- if format_type == 'summary':
677
+
678
+ if format_type == "summary":
659
679
  print(f"🤖 {agent_id}")
660
680
  print(f" 📚 {len(sections)} sections, {item_count} total items")
661
-
681
+
662
682
  # Show section summary
663
683
  for section_name, items in sections.items():
664
684
  if items:
665
685
  print(f" • {section_name}: {len(items)} items")
666
686
  print()
667
- elif format_type == 'detailed':
687
+ elif format_type == "detailed":
668
688
  print(f"🤖 {agent_id}")
669
689
  print(f" 📚 {len(sections)} sections, {item_count} total items")
670
-
690
+
671
691
  for section_name, items in sections.items():
672
692
  if items:
673
693
  print(f"\n 📖 {section_name}:")
@@ -678,9 +698,9 @@ def _show_all_agent_memories(format_type, memory_manager):
678
698
  print()
679
699
  except Exception as e:
680
700
  print(f"❌ Error loading memory for {agent_id}: {e}")
681
-
701
+
682
702
  print(f"📊 Total: {total_items} memory items across {len(agent_memories)} agents")
683
-
703
+
684
704
  # Show cross-references if we have multiple agents
685
705
  if len(agent_memories) > 1:
686
706
  print("\n🔗 Cross-References and Common Patterns:")
@@ -692,27 +712,27 @@ def _parse_memory_content(content):
692
712
  sections = {}
693
713
  current_section = None
694
714
  current_items = []
695
-
696
- for line in content.split('\n'):
715
+
716
+ for line in content.split("\n"):
697
717
  line = line.strip()
698
-
699
- if line.startswith('## ') and not line.startswith('## Memory Usage'):
718
+
719
+ if line.startswith("## ") and not line.startswith("## Memory Usage"):
700
720
  # New section
701
721
  if current_section and current_items:
702
722
  sections[current_section] = current_items.copy()
703
-
723
+
704
724
  current_section = line[3:].strip()
705
725
  current_items = []
706
- elif line.startswith('- ') and current_section:
726
+ elif line.startswith("- ") and current_section:
707
727
  # Item in current section
708
728
  item = line[2:].strip()
709
729
  if item and len(item) > 5: # Filter out very short items
710
730
  current_items.append(item)
711
-
731
+
712
732
  # Add final section
713
733
  if current_section and current_items:
714
734
  sections[current_section] = current_items
715
-
735
+
716
736
  return sections
717
737
 
718
738
 
@@ -720,11 +740,11 @@ def _find_common_patterns(agent_memories):
720
740
  """Find common patterns across agent memories."""
721
741
  pattern_count = {}
722
742
  agent_patterns = {}
723
-
743
+
724
744
  # Collect all patterns and which agents have them
725
745
  for agent_id, sections in agent_memories.items():
726
746
  agent_patterns[agent_id] = set()
727
-
747
+
728
748
  for section_name, items in sections.items():
729
749
  for item in items:
730
750
  # Normalize item for comparison (lowercase, basic cleanup)
@@ -732,90 +752,104 @@ def _find_common_patterns(agent_memories):
732
752
  if len(normalized) > 10: # Skip very short items
733
753
  pattern_count[normalized] = pattern_count.get(normalized, 0) + 1
734
754
  agent_patterns[agent_id].add(normalized)
735
-
755
+
736
756
  # Find patterns that appear in multiple agents
737
- common_patterns = [(pattern, count) for pattern, count in pattern_count.items() if count > 1]
757
+ common_patterns = [
758
+ (pattern, count) for pattern, count in pattern_count.items() if count > 1
759
+ ]
738
760
  common_patterns.sort(key=lambda x: x[1], reverse=True)
739
-
761
+
740
762
  if common_patterns:
741
763
  print("\n🔄 Most Common Patterns:")
742
764
  for pattern, count in common_patterns[:5]:
743
765
  # Find which agents have this pattern
744
- agents_with_pattern = [agent for agent, patterns in agent_patterns.items()
745
- if pattern in patterns]
766
+ agents_with_pattern = [
767
+ agent
768
+ for agent, patterns in agent_patterns.items()
769
+ if pattern in patterns
770
+ ]
746
771
  print(f" • {pattern[:80]}{'...' if len(pattern) > 80 else ''}")
747
772
  print(f" Found in: {', '.join(agents_with_pattern)} ({count} agents)")
748
773
  print()
749
774
  else:
750
775
  print(" No common patterns found across agents")
751
-
776
+
752
777
  # Show agent similarities
753
778
  print("\n🤝 Agent Knowledge Similarity:")
754
779
  agents = list(agent_memories.keys())
755
780
  for i, agent1 in enumerate(agents):
756
- for agent2 in agents[i+1:]:
781
+ for agent2 in agents[i + 1 :]:
757
782
  common_items = len(agent_patterns[agent1] & agent_patterns[agent2])
758
783
  if common_items > 0:
759
784
  total_items = len(agent_patterns[agent1] | agent_patterns[agent2])
760
- similarity = (common_items / total_items) * 100 if total_items > 0 else 0
761
- print(f" {agent1} {agent2}: {common_items} common items ({similarity:.1f}% similarity)")
785
+ similarity = (
786
+ (common_items / total_items) * 100 if total_items > 0 else 0
787
+ )
788
+ print(
789
+ f" {agent1} ↔ {agent2}: {common_items} common items ({similarity:.1f}% similarity)"
790
+ )
762
791
 
763
792
 
764
793
  def _route_memory_command(args, memory_manager):
765
794
  """
766
795
  Test memory command routing logic.
767
-
796
+
768
797
  WHY: Users and developers need to understand how memory commands are routed
769
798
  to appropriate agents for debugging and customization purposes.
770
-
799
+
771
800
  Args:
772
801
  args: Command arguments with content to route
773
802
  memory_manager: AgentMemoryManager instance
774
803
  """
775
804
  print("🎯 Memory Command Routing Test")
776
805
  print("-" * 80)
777
-
778
- content = getattr(args, 'content', None)
806
+
807
+ content = getattr(args, "content", None)
779
808
  if not content:
780
809
  print("❌ No content provided for routing analysis")
781
810
  print(" Usage: memory route --content 'your content here'")
782
811
  return
783
-
812
+
784
813
  try:
785
- print(f"📝 Analyzing content: '{content[:100]}{'...' if len(content) > 100 else ''}'")
786
-
814
+ print(
815
+ f"📝 Analyzing content: '{content[:100]}{'...' if len(content) > 100 else ''}'"
816
+ )
817
+
787
818
  result = memory_manager.route_memory_command(content)
788
-
819
+
789
820
  if result.get("success") is False:
790
821
  print(f"❌ Routing failed: {result.get('error', 'Unknown error')}")
791
822
  return
792
-
823
+
793
824
  target_agent = result.get("target_agent", "unknown")
794
825
  section = result.get("section", "unknown")
795
826
  confidence = result.get("confidence", 0.0)
796
827
  reasoning = result.get("reasoning", "No reasoning provided")
797
-
828
+
798
829
  print(f"\n🎯 Routing Decision:")
799
830
  print(f" Target Agent: {target_agent}")
800
831
  print(f" Section: {section}")
801
832
  print(f" Confidence: {confidence:.2f}")
802
833
  print(f" Reasoning: {reasoning}")
803
-
834
+
804
835
  # Show agent scores if available
805
836
  agent_scores = result.get("agent_scores", {})
806
837
  if agent_scores:
807
838
  print(f"\n📊 Agent Relevance Scores:")
808
839
  sorted_scores = sorted(
809
- [(agent, data['score']) for agent, data in agent_scores.items()],
810
- key=lambda x: x[1], reverse=True
840
+ [(agent, data["score"]) for agent, data in agent_scores.items()],
841
+ key=lambda x: x[1],
842
+ reverse=True,
811
843
  )
812
844
  for agent, score in sorted_scores[:5]: # Show top 5
813
845
  print(f" {agent}: {score:.3f}")
814
846
  # Show matched keywords if available
815
- if agent in agent_scores and agent_scores[agent].get('matched_keywords'):
816
- keywords = ', '.join(agent_scores[agent]['matched_keywords'][:3])
847
+ if agent in agent_scores and agent_scores[agent].get(
848
+ "matched_keywords"
849
+ ):
850
+ keywords = ", ".join(agent_scores[agent]["matched_keywords"][:3])
817
851
  print(f" Keywords: {keywords}")
818
-
852
+
819
853
  except Exception as e:
820
854
  print(f"❌ Error routing memory command: {e}")
821
855
 
@@ -827,23 +861,23 @@ def _display_single_optimization_result(result):
827
861
  optimized_size = result.get("optimized_size", 0)
828
862
  size_reduction = result.get("size_reduction", 0)
829
863
  size_reduction_percent = result.get("size_reduction_percent", 0)
830
-
864
+
831
865
  print(f"✅ Optimization completed for {agent_id}")
832
866
  print(f" Original size: {original_size:,} bytes")
833
867
  print(f" Optimized size: {optimized_size:,} bytes")
834
868
  print(f" Size reduction: {size_reduction:,} bytes ({size_reduction_percent}%)")
835
-
869
+
836
870
  duplicates = result.get("duplicates_removed", 0)
837
871
  consolidated = result.get("items_consolidated", 0)
838
872
  reordered = result.get("items_reordered", 0)
839
-
873
+
840
874
  if duplicates > 0:
841
875
  print(f" Duplicates removed: {duplicates}")
842
876
  if consolidated > 0:
843
877
  print(f" Items consolidated: {consolidated}")
844
878
  if reordered > 0:
845
879
  print(f" Sections reordered: {reordered}")
846
-
880
+
847
881
  backup_path = result.get("backup_created")
848
882
  if backup_path:
849
883
  print(f" Backup created: {backup_path}")
@@ -852,16 +886,18 @@ def _display_single_optimization_result(result):
852
886
  def _display_bulk_optimization_results(result):
853
887
  """Display optimization results for all agents."""
854
888
  summary = result.get("summary", {})
855
-
889
+
856
890
  print(f"✅ Bulk optimization completed")
857
891
  print(f" Agents processed: {summary.get('agents_processed', 0)}")
858
892
  print(f" Agents optimized: {summary.get('agents_optimized', 0)}")
859
893
  print(f" Total size before: {summary.get('total_size_before', 0):,} bytes")
860
894
  print(f" Total size after: {summary.get('total_size_after', 0):,} bytes")
861
- print(f" Total reduction: {summary.get('total_size_reduction', 0):,} bytes ({summary.get('total_size_reduction_percent', 0)}%)")
895
+ print(
896
+ f" Total reduction: {summary.get('total_size_reduction', 0):,} bytes ({summary.get('total_size_reduction_percent', 0)}%)"
897
+ )
862
898
  print(f" Total duplicates removed: {summary.get('total_duplicates_removed', 0)}")
863
899
  print(f" Total items consolidated: {summary.get('total_items_consolidated', 0)}")
864
-
900
+
865
901
  # Show per-agent summary
866
902
  agents_results = result.get("agents", {})
867
903
  if agents_results:
@@ -871,13 +907,13 @@ def _display_bulk_optimization_results(result):
871
907
  reduction = agent_result.get("size_reduction_percent", 0)
872
908
  duplicates = agent_result.get("duplicates_removed", 0)
873
909
  consolidated = agent_result.get("items_consolidated", 0)
874
-
910
+
875
911
  status_parts = []
876
912
  if duplicates > 0:
877
913
  status_parts.append(f"{duplicates} dupes")
878
914
  if consolidated > 0:
879
915
  status_parts.append(f"{consolidated} consolidated")
880
-
916
+
881
917
  status = f" ({', '.join(status_parts)})" if status_parts else ""
882
918
  print(f" {agent_id}: {reduction}% reduction{status}")
883
919
  else:
@@ -888,10 +924,10 @@ def _display_bulk_optimization_results(result):
888
924
  def _output_all_memories_raw(memory_manager):
889
925
  """
890
926
  Output all agent memories in raw JSON format.
891
-
927
+
892
928
  WHY: Provides programmatic access to all agent memories for external tools,
893
929
  scripts, or APIs that need to process or analyze the complete memory state.
894
-
930
+
895
931
  Args:
896
932
  memory_manager: AgentMemoryManager instance
897
933
  """
@@ -902,7 +938,7 @@ def _output_all_memories_raw(memory_manager):
902
938
  error_output = {
903
939
  "success": False,
904
940
  "error": f"Failed to retrieve all memories: {str(e)}",
905
- "timestamp": datetime.now().isoformat()
941
+ "timestamp": datetime.now().isoformat(),
906
942
  }
907
943
  print(json.dumps(error_output, indent=2))
908
944
 
@@ -910,10 +946,10 @@ def _output_all_memories_raw(memory_manager):
910
946
  def _output_single_agent_raw(agent_id, memory_manager):
911
947
  """
912
948
  Output single agent memory in raw JSON format.
913
-
949
+
914
950
  WHY: Provides programmatic access to a specific agent's memory for
915
951
  targeted analysis or processing by external tools.
916
-
952
+
917
953
  Args:
918
954
  agent_id: ID of the agent to retrieve memory for
919
955
  memory_manager: AgentMemoryManager instance
@@ -921,40 +957,40 @@ def _output_single_agent_raw(agent_id, memory_manager):
921
957
  try:
922
958
  # Get all memories and extract the specific agent
923
959
  all_memories = memory_manager.get_all_memories_raw()
924
-
960
+
925
961
  if not all_memories.get("success", False):
926
962
  error_output = {
927
963
  "success": False,
928
964
  "error": all_memories.get("error", "Failed to retrieve memories"),
929
- "timestamp": datetime.now().isoformat()
965
+ "timestamp": datetime.now().isoformat(),
930
966
  }
931
967
  print(json.dumps(error_output, indent=2))
932
968
  return
933
-
969
+
934
970
  agents = all_memories.get("agents", {})
935
971
  if agent_id not in agents:
936
972
  error_output = {
937
973
  "success": False,
938
974
  "error": f"No memory found for agent: {agent_id}",
939
975
  "available_agents": list(agents.keys()),
940
- "timestamp": datetime.now().isoformat()
976
+ "timestamp": datetime.now().isoformat(),
941
977
  }
942
978
  print(json.dumps(error_output, indent=2))
943
979
  return
944
-
980
+
945
981
  # Return single agent data with metadata
946
982
  single_agent_output = {
947
983
  "success": True,
948
984
  "timestamp": all_memories["timestamp"],
949
- "agent": agents[agent_id]
985
+ "agent": agents[agent_id],
950
986
  }
951
-
987
+
952
988
  print(json.dumps(single_agent_output, indent=2, ensure_ascii=False))
953
-
989
+
954
990
  except Exception as e:
955
991
  error_output = {
956
992
  "success": False,
957
993
  "error": f"Failed to retrieve memory for agent {agent_id}: {str(e)}",
958
- "timestamp": datetime.now().isoformat()
994
+ "timestamp": datetime.now().isoformat(),
959
995
  }
960
- print(json.dumps(error_output, indent=2))
996
+ print(json.dumps(error_output, indent=2))