claude-mpm 4.14.6__py3-none-any.whl → 4.21.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.

Potentially problematic release.


This version of claude-mpm might be problematic. Click here for more details.

Files changed (353) hide show
  1. claude_mpm/VERSION +1 -1
  2. claude_mpm/agents/BASE_ENGINEER.md +286 -0
  3. claude_mpm/agents/BASE_PM.md +272 -23
  4. claude_mpm/agents/OUTPUT_STYLE.md +48 -3
  5. claude_mpm/agents/PM_INSTRUCTIONS.md +49 -0
  6. claude_mpm/agents/agent_loader.py +17 -5
  7. claude_mpm/agents/frontmatter_validator.py +284 -253
  8. claude_mpm/agents/templates/agentic-coder-optimizer.json +9 -2
  9. claude_mpm/agents/templates/api_qa.json +7 -1
  10. claude_mpm/agents/templates/clerk-ops.json +8 -1
  11. claude_mpm/agents/templates/code_analyzer.json +4 -1
  12. claude_mpm/agents/templates/dart_engineer.json +11 -1
  13. claude_mpm/agents/templates/data_engineer.json +11 -1
  14. claude_mpm/agents/templates/documentation.json +6 -1
  15. claude_mpm/agents/templates/engineer.json +18 -1
  16. claude_mpm/agents/templates/gcp_ops_agent.json +8 -1
  17. claude_mpm/agents/templates/golang_engineer.json +11 -1
  18. claude_mpm/agents/templates/java_engineer.json +12 -2
  19. claude_mpm/agents/templates/local_ops_agent.json +216 -37
  20. claude_mpm/agents/templates/nextjs_engineer.json +11 -1
  21. claude_mpm/agents/templates/ops.json +8 -1
  22. claude_mpm/agents/templates/php-engineer.json +20 -4
  23. claude_mpm/agents/templates/project_organizer.json +10 -3
  24. claude_mpm/agents/templates/prompt-engineer.json +5 -1
  25. claude_mpm/agents/templates/python_engineer.json +19 -4
  26. claude_mpm/agents/templates/qa.json +7 -1
  27. claude_mpm/agents/templates/react_engineer.json +11 -1
  28. claude_mpm/agents/templates/refactoring_engineer.json +8 -1
  29. claude_mpm/agents/templates/research.json +4 -1
  30. claude_mpm/agents/templates/ruby-engineer.json +11 -1
  31. claude_mpm/agents/templates/rust_engineer.json +23 -8
  32. claude_mpm/agents/templates/security.json +6 -1
  33. claude_mpm/agents/templates/svelte-engineer.json +225 -0
  34. claude_mpm/agents/templates/ticketing.json +6 -1
  35. claude_mpm/agents/templates/typescript_engineer.json +11 -1
  36. claude_mpm/agents/templates/vercel_ops_agent.json +8 -1
  37. claude_mpm/agents/templates/version_control.json +8 -1
  38. claude_mpm/agents/templates/web_qa.json +7 -1
  39. claude_mpm/agents/templates/web_ui.json +11 -1
  40. claude_mpm/cli/__init__.py +34 -740
  41. claude_mpm/cli/commands/__init__.py +2 -0
  42. claude_mpm/cli/commands/agent_manager.py +25 -12
  43. claude_mpm/cli/commands/agent_state_manager.py +186 -0
  44. claude_mpm/cli/commands/agents.py +204 -148
  45. claude_mpm/cli/commands/aggregate.py +7 -3
  46. claude_mpm/cli/commands/analyze.py +9 -4
  47. claude_mpm/cli/commands/analyze_code.py +7 -2
  48. claude_mpm/cli/commands/auto_configure.py +7 -9
  49. claude_mpm/cli/commands/config.py +47 -13
  50. claude_mpm/cli/commands/configure.py +294 -1788
  51. claude_mpm/cli/commands/configure_agent_display.py +261 -0
  52. claude_mpm/cli/commands/configure_behavior_manager.py +204 -0
  53. claude_mpm/cli/commands/configure_hook_manager.py +225 -0
  54. claude_mpm/cli/commands/configure_models.py +18 -0
  55. claude_mpm/cli/commands/configure_navigation.py +167 -0
  56. claude_mpm/cli/commands/configure_paths.py +104 -0
  57. claude_mpm/cli/commands/configure_persistence.py +254 -0
  58. claude_mpm/cli/commands/configure_startup_manager.py +646 -0
  59. claude_mpm/cli/commands/configure_template_editor.py +497 -0
  60. claude_mpm/cli/commands/configure_validators.py +73 -0
  61. claude_mpm/cli/commands/local_deploy.py +3 -2
  62. claude_mpm/cli/commands/memory.py +54 -20
  63. claude_mpm/cli/commands/mpm_init/__init__.py +73 -0
  64. claude_mpm/cli/commands/mpm_init/core.py +525 -0
  65. claude_mpm/cli/commands/mpm_init/display.py +341 -0
  66. claude_mpm/cli/commands/mpm_init/git_activity.py +427 -0
  67. claude_mpm/cli/commands/mpm_init/modes.py +397 -0
  68. claude_mpm/cli/commands/mpm_init/prompts.py +442 -0
  69. claude_mpm/cli/commands/mpm_init_cli.py +396 -0
  70. claude_mpm/cli/commands/mpm_init_handler.py +75 -4
  71. claude_mpm/cli/commands/skills.py +488 -0
  72. claude_mpm/cli/executor.py +204 -0
  73. claude_mpm/cli/helpers.py +105 -0
  74. claude_mpm/cli/interactive/__init__.py +3 -0
  75. claude_mpm/cli/interactive/skills_wizard.py +491 -0
  76. claude_mpm/cli/parsers/base_parser.py +7 -0
  77. claude_mpm/cli/parsers/mpm_init_parser.py +42 -0
  78. claude_mpm/cli/parsers/skills_parser.py +137 -0
  79. claude_mpm/cli/shared/output_formatters.py +28 -19
  80. claude_mpm/cli/startup.py +538 -0
  81. claude_mpm/commands/mpm-auto-configure.md +52 -0
  82. claude_mpm/commands/mpm-help.md +3 -0
  83. claude_mpm/commands/mpm-init.md +112 -6
  84. claude_mpm/commands/mpm-version.md +113 -0
  85. claude_mpm/commands/mpm.md +1 -0
  86. claude_mpm/config/agent_config.py +2 -2
  87. claude_mpm/constants.py +12 -0
  88. claude_mpm/core/base_service.py +13 -12
  89. claude_mpm/core/config.py +42 -0
  90. claude_mpm/core/enums.py +452 -0
  91. claude_mpm/core/factories.py +1 -1
  92. claude_mpm/core/instruction_reinforcement_hook.py +2 -1
  93. claude_mpm/core/interactive_session.py +6 -3
  94. claude_mpm/core/interfaces.py +56 -1
  95. claude_mpm/core/logging_config.py +6 -2
  96. claude_mpm/core/oneshot_session.py +8 -4
  97. claude_mpm/core/optimized_agent_loader.py +3 -3
  98. claude_mpm/core/output_style_manager.py +12 -192
  99. claude_mpm/core/service_registry.py +5 -1
  100. claude_mpm/core/types.py +2 -9
  101. claude_mpm/core/typing_utils.py +7 -6
  102. claude_mpm/dashboard/static/js/dashboard.js +0 -14
  103. claude_mpm/dashboard/templates/index.html +3 -41
  104. claude_mpm/hooks/__init__.py +8 -0
  105. claude_mpm/hooks/claude_hooks/response_tracking.py +35 -1
  106. claude_mpm/hooks/instruction_reinforcement.py +7 -2
  107. claude_mpm/hooks/session_resume_hook.py +121 -0
  108. claude_mpm/models/resume_log.py +340 -0
  109. claude_mpm/services/agents/auto_config_manager.py +10 -11
  110. claude_mpm/services/agents/deployment/agent_configuration_manager.py +1 -1
  111. claude_mpm/services/agents/deployment/agent_record_service.py +1 -1
  112. claude_mpm/services/agents/deployment/agent_validator.py +17 -1
  113. claude_mpm/services/agents/deployment/async_agent_deployment.py +1 -1
  114. claude_mpm/services/agents/deployment/interface_adapter.py +3 -2
  115. claude_mpm/services/agents/deployment/local_template_deployment.py +1 -1
  116. claude_mpm/services/agents/deployment/pipeline/steps/agent_processing_step.py +7 -6
  117. claude_mpm/services/agents/deployment/pipeline/steps/base_step.py +7 -16
  118. claude_mpm/services/agents/deployment/pipeline/steps/configuration_step.py +4 -3
  119. claude_mpm/services/agents/deployment/pipeline/steps/target_directory_step.py +5 -3
  120. claude_mpm/services/agents/deployment/pipeline/steps/validation_step.py +6 -5
  121. claude_mpm/services/agents/deployment/refactored_agent_deployment_service.py +9 -6
  122. claude_mpm/services/agents/deployment/validation/__init__.py +3 -1
  123. claude_mpm/services/agents/deployment/validation/validation_result.py +1 -9
  124. claude_mpm/services/agents/local_template_manager.py +1 -1
  125. claude_mpm/services/agents/memory/agent_memory_manager.py +5 -2
  126. claude_mpm/services/agents/recommender.py +47 -0
  127. claude_mpm/services/agents/registry/modification_tracker.py +5 -2
  128. claude_mpm/services/cli/resume_service.py +617 -0
  129. claude_mpm/services/cli/session_manager.py +87 -0
  130. claude_mpm/services/cli/session_pause_manager.py +504 -0
  131. claude_mpm/services/cli/session_resume_helper.py +372 -0
  132. claude_mpm/services/command_handler_service.py +11 -5
  133. claude_mpm/services/core/interfaces/process.py +6 -6
  134. claude_mpm/services/core/interfaces.py +56 -1
  135. claude_mpm/services/core/models/__init__.py +0 -2
  136. claude_mpm/services/core/models/agent_config.py +15 -28
  137. claude_mpm/services/core/models/health.py +1 -28
  138. claude_mpm/services/core/models/process.py +22 -41
  139. claude_mpm/services/core/path_resolver.py +1 -1
  140. claude_mpm/services/diagnostics/__init__.py +2 -2
  141. claude_mpm/services/diagnostics/checks/agent_check.py +25 -24
  142. claude_mpm/services/diagnostics/checks/claude_code_check.py +24 -23
  143. claude_mpm/services/diagnostics/checks/common_issues_check.py +25 -24
  144. claude_mpm/services/diagnostics/checks/configuration_check.py +24 -23
  145. claude_mpm/services/diagnostics/checks/filesystem_check.py +18 -17
  146. claude_mpm/services/diagnostics/checks/installation_check.py +30 -29
  147. claude_mpm/services/diagnostics/checks/instructions_check.py +20 -19
  148. claude_mpm/services/diagnostics/checks/mcp_check.py +50 -36
  149. claude_mpm/services/diagnostics/checks/mcp_services_check.py +36 -31
  150. claude_mpm/services/diagnostics/checks/monitor_check.py +23 -22
  151. claude_mpm/services/diagnostics/checks/startup_log_check.py +9 -8
  152. claude_mpm/services/diagnostics/diagnostic_runner.py +6 -5
  153. claude_mpm/services/diagnostics/doctor_reporter.py +28 -25
  154. claude_mpm/services/diagnostics/models.py +37 -21
  155. claude_mpm/services/infrastructure/monitoring/__init__.py +1 -1
  156. claude_mpm/services/infrastructure/monitoring/aggregator.py +12 -12
  157. claude_mpm/services/infrastructure/monitoring/base.py +5 -13
  158. claude_mpm/services/infrastructure/monitoring/network.py +7 -6
  159. claude_mpm/services/infrastructure/monitoring/process.py +13 -12
  160. claude_mpm/services/infrastructure/monitoring/resources.py +7 -6
  161. claude_mpm/services/infrastructure/monitoring/service.py +16 -15
  162. claude_mpm/services/infrastructure/resume_log_generator.py +439 -0
  163. claude_mpm/services/local_ops/__init__.py +5 -3
  164. claude_mpm/services/local_ops/crash_detector.py +1 -1
  165. claude_mpm/services/local_ops/health_checks/http_check.py +2 -1
  166. claude_mpm/services/local_ops/health_checks/process_check.py +2 -1
  167. claude_mpm/services/local_ops/health_checks/resource_check.py +2 -1
  168. claude_mpm/services/local_ops/health_manager.py +1 -1
  169. claude_mpm/services/local_ops/process_manager.py +12 -12
  170. claude_mpm/services/local_ops/restart_manager.py +1 -1
  171. claude_mpm/services/local_ops/state_manager.py +6 -5
  172. claude_mpm/services/local_ops/unified_manager.py +2 -2
  173. claude_mpm/services/mcp_config_manager.py +7 -126
  174. claude_mpm/services/mcp_gateway/auto_configure.py +31 -25
  175. claude_mpm/services/mcp_gateway/core/__init__.py +1 -2
  176. claude_mpm/services/mcp_gateway/core/base.py +18 -31
  177. claude_mpm/services/mcp_gateway/core/process_pool.py +19 -10
  178. claude_mpm/services/mcp_gateway/tools/external_mcp_services.py +97 -45
  179. claude_mpm/services/mcp_gateway/tools/health_check_tool.py +30 -28
  180. claude_mpm/services/memory_hook_service.py +4 -1
  181. claude_mpm/services/monitor/daemon_manager.py +3 -2
  182. claude_mpm/services/monitor/handlers/dashboard.py +2 -1
  183. claude_mpm/services/monitor/handlers/hooks.py +2 -1
  184. claude_mpm/services/monitor/management/lifecycle.py +3 -2
  185. claude_mpm/services/monitor/server.py +2 -1
  186. claude_mpm/services/session_management_service.py +3 -2
  187. claude_mpm/services/session_manager.py +205 -1
  188. claude_mpm/services/shared/async_service_base.py +16 -27
  189. claude_mpm/services/shared/lifecycle_service_base.py +1 -14
  190. claude_mpm/services/socketio/handlers/__init__.py +5 -2
  191. claude_mpm/services/socketio/handlers/hook.py +13 -2
  192. claude_mpm/services/socketio/handlers/registry.py +4 -2
  193. claude_mpm/services/socketio/server/main.py +10 -8
  194. claude_mpm/services/subprocess_launcher_service.py +14 -5
  195. claude_mpm/services/unified/analyzer_strategies/code_analyzer.py +8 -7
  196. claude_mpm/services/unified/analyzer_strategies/dependency_analyzer.py +6 -5
  197. claude_mpm/services/unified/analyzer_strategies/performance_analyzer.py +8 -7
  198. claude_mpm/services/unified/analyzer_strategies/security_analyzer.py +7 -6
  199. claude_mpm/services/unified/analyzer_strategies/structure_analyzer.py +5 -4
  200. claude_mpm/services/unified/config_strategies/validation_strategy.py +13 -9
  201. claude_mpm/services/unified/deployment_strategies/cloud_strategies.py +10 -3
  202. claude_mpm/services/unified/deployment_strategies/local.py +6 -5
  203. claude_mpm/services/unified/deployment_strategies/utils.py +6 -5
  204. claude_mpm/services/unified/deployment_strategies/vercel.py +7 -6
  205. claude_mpm/services/unified/interfaces.py +3 -1
  206. claude_mpm/services/unified/unified_analyzer.py +14 -10
  207. claude_mpm/services/unified/unified_config.py +2 -1
  208. claude_mpm/services/unified/unified_deployment.py +9 -4
  209. claude_mpm/services/version_service.py +104 -1
  210. claude_mpm/skills/__init__.py +42 -0
  211. claude_mpm/skills/agent_skills_injector.py +324 -0
  212. claude_mpm/skills/bundled/LICENSE_ATTRIBUTIONS.md +79 -0
  213. claude_mpm/skills/bundled/__init__.py +6 -0
  214. claude_mpm/skills/bundled/api-documentation.md +393 -0
  215. claude_mpm/skills/bundled/async-testing.md +571 -0
  216. claude_mpm/skills/bundled/code-review.md +143 -0
  217. claude_mpm/skills/bundled/collaboration/brainstorming/SKILL.md +79 -0
  218. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/SKILL.md +178 -0
  219. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/agent-prompts.md +577 -0
  220. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/coordination-patterns.md +467 -0
  221. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/examples.md +537 -0
  222. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/troubleshooting.md +730 -0
  223. claude_mpm/skills/bundled/collaboration/requesting-code-review/SKILL.md +112 -0
  224. claude_mpm/skills/bundled/collaboration/requesting-code-review/references/code-reviewer-template.md +146 -0
  225. claude_mpm/skills/bundled/collaboration/requesting-code-review/references/review-examples.md +412 -0
  226. claude_mpm/skills/bundled/collaboration/writing-plans/SKILL.md +81 -0
  227. claude_mpm/skills/bundled/collaboration/writing-plans/references/best-practices.md +362 -0
  228. claude_mpm/skills/bundled/collaboration/writing-plans/references/plan-structure-templates.md +312 -0
  229. claude_mpm/skills/bundled/database-migration.md +199 -0
  230. claude_mpm/skills/bundled/debugging/root-cause-tracing/SKILL.md +152 -0
  231. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/advanced-techniques.md +668 -0
  232. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/examples.md +587 -0
  233. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/integration.md +438 -0
  234. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/tracing-techniques.md +391 -0
  235. claude_mpm/skills/bundled/debugging/systematic-debugging/CREATION-LOG.md +119 -0
  236. claude_mpm/skills/bundled/debugging/systematic-debugging/SKILL.md +148 -0
  237. claude_mpm/skills/bundled/debugging/systematic-debugging/references/anti-patterns.md +483 -0
  238. claude_mpm/skills/bundled/debugging/systematic-debugging/references/examples.md +452 -0
  239. claude_mpm/skills/bundled/debugging/systematic-debugging/references/troubleshooting.md +449 -0
  240. claude_mpm/skills/bundled/debugging/systematic-debugging/references/workflow.md +411 -0
  241. claude_mpm/skills/bundled/debugging/systematic-debugging/test-academic.md +14 -0
  242. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-1.md +58 -0
  243. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-2.md +68 -0
  244. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-3.md +69 -0
  245. claude_mpm/skills/bundled/debugging/verification-before-completion/SKILL.md +131 -0
  246. claude_mpm/skills/bundled/debugging/verification-before-completion/references/gate-function.md +325 -0
  247. claude_mpm/skills/bundled/debugging/verification-before-completion/references/integration-and-workflows.md +490 -0
  248. claude_mpm/skills/bundled/debugging/verification-before-completion/references/red-flags-and-failures.md +425 -0
  249. claude_mpm/skills/bundled/debugging/verification-before-completion/references/verification-patterns.md +499 -0
  250. claude_mpm/skills/bundled/docker-containerization.md +194 -0
  251. claude_mpm/skills/bundled/express-local-dev.md +1429 -0
  252. claude_mpm/skills/bundled/fastapi-local-dev.md +1199 -0
  253. claude_mpm/skills/bundled/git-workflow.md +414 -0
  254. claude_mpm/skills/bundled/imagemagick.md +204 -0
  255. claude_mpm/skills/bundled/json-data-handling.md +223 -0
  256. claude_mpm/skills/bundled/main/artifacts-builder/SKILL.md +86 -0
  257. claude_mpm/skills/bundled/main/internal-comms/SKILL.md +43 -0
  258. claude_mpm/skills/bundled/main/internal-comms/examples/3p-updates.md +47 -0
  259. claude_mpm/skills/bundled/main/internal-comms/examples/company-newsletter.md +65 -0
  260. claude_mpm/skills/bundled/main/internal-comms/examples/faq-answers.md +30 -0
  261. claude_mpm/skills/bundled/main/internal-comms/examples/general-comms.md +16 -0
  262. claude_mpm/skills/bundled/main/mcp-builder/SKILL.md +160 -0
  263. claude_mpm/skills/bundled/main/mcp-builder/reference/design_principles.md +412 -0
  264. claude_mpm/skills/bundled/main/mcp-builder/reference/evaluation.md +602 -0
  265. claude_mpm/skills/bundled/main/mcp-builder/reference/mcp_best_practices.md +915 -0
  266. claude_mpm/skills/bundled/main/mcp-builder/reference/node_mcp_server.md +916 -0
  267. claude_mpm/skills/bundled/main/mcp-builder/reference/python_mcp_server.md +752 -0
  268. claude_mpm/skills/bundled/main/mcp-builder/reference/workflow.md +1237 -0
  269. claude_mpm/skills/bundled/main/mcp-builder/scripts/connections.py +157 -0
  270. claude_mpm/skills/bundled/main/mcp-builder/scripts/evaluation.py +425 -0
  271. claude_mpm/skills/bundled/main/skill-creator/SKILL.md +189 -0
  272. claude_mpm/skills/bundled/main/skill-creator/references/best-practices.md +500 -0
  273. claude_mpm/skills/bundled/main/skill-creator/references/creation-workflow.md +464 -0
  274. claude_mpm/skills/bundled/main/skill-creator/references/examples.md +619 -0
  275. claude_mpm/skills/bundled/main/skill-creator/references/progressive-disclosure.md +437 -0
  276. claude_mpm/skills/bundled/main/skill-creator/references/skill-structure.md +231 -0
  277. claude_mpm/skills/bundled/main/skill-creator/scripts/init_skill.py +303 -0
  278. claude_mpm/skills/bundled/main/skill-creator/scripts/package_skill.py +113 -0
  279. claude_mpm/skills/bundled/main/skill-creator/scripts/quick_validate.py +72 -0
  280. claude_mpm/skills/bundled/nextjs-local-dev.md +807 -0
  281. claude_mpm/skills/bundled/pdf.md +141 -0
  282. claude_mpm/skills/bundled/performance-profiling.md +567 -0
  283. claude_mpm/skills/bundled/php/espocrm-development/SKILL.md +170 -0
  284. claude_mpm/skills/bundled/php/espocrm-development/references/architecture.md +602 -0
  285. claude_mpm/skills/bundled/php/espocrm-development/references/common-tasks.md +821 -0
  286. claude_mpm/skills/bundled/php/espocrm-development/references/development-workflow.md +742 -0
  287. claude_mpm/skills/bundled/php/espocrm-development/references/frontend-customization.md +726 -0
  288. claude_mpm/skills/bundled/php/espocrm-development/references/hooks-and-services.md +764 -0
  289. claude_mpm/skills/bundled/php/espocrm-development/references/testing-debugging.md +831 -0
  290. claude_mpm/skills/bundled/refactoring-patterns.md +180 -0
  291. claude_mpm/skills/bundled/rust/desktop-applications/SKILL.md +226 -0
  292. claude_mpm/skills/bundled/rust/desktop-applications/references/architecture-patterns.md +901 -0
  293. claude_mpm/skills/bundled/rust/desktop-applications/references/native-gui-frameworks.md +901 -0
  294. claude_mpm/skills/bundled/rust/desktop-applications/references/platform-integration.md +775 -0
  295. claude_mpm/skills/bundled/rust/desktop-applications/references/state-management.md +937 -0
  296. claude_mpm/skills/bundled/rust/desktop-applications/references/tauri-framework.md +770 -0
  297. claude_mpm/skills/bundled/rust/desktop-applications/references/testing-deployment.md +961 -0
  298. claude_mpm/skills/bundled/security-scanning.md +327 -0
  299. claude_mpm/skills/bundled/systematic-debugging.md +473 -0
  300. claude_mpm/skills/bundled/test-driven-development.md +378 -0
  301. claude_mpm/skills/bundled/testing/condition-based-waiting/SKILL.md +119 -0
  302. claude_mpm/skills/bundled/testing/condition-based-waiting/references/patterns-and-implementation.md +253 -0
  303. claude_mpm/skills/bundled/testing/test-driven-development/SKILL.md +145 -0
  304. claude_mpm/skills/bundled/testing/test-driven-development/references/anti-patterns.md +543 -0
  305. claude_mpm/skills/bundled/testing/test-driven-development/references/examples.md +741 -0
  306. claude_mpm/skills/bundled/testing/test-driven-development/references/integration.md +470 -0
  307. claude_mpm/skills/bundled/testing/test-driven-development/references/philosophy.md +458 -0
  308. claude_mpm/skills/bundled/testing/test-driven-development/references/workflow.md +639 -0
  309. claude_mpm/skills/bundled/testing/testing-anti-patterns/SKILL.md +140 -0
  310. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/completeness-anti-patterns.md +572 -0
  311. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/core-anti-patterns.md +411 -0
  312. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/detection-guide.md +569 -0
  313. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/tdd-connection.md +695 -0
  314. claude_mpm/skills/bundled/testing/webapp-testing/SKILL.md +184 -0
  315. claude_mpm/skills/bundled/testing/webapp-testing/decision-tree.md +459 -0
  316. claude_mpm/skills/bundled/testing/webapp-testing/examples/console_logging.py +35 -0
  317. claude_mpm/skills/bundled/testing/webapp-testing/examples/element_discovery.py +44 -0
  318. claude_mpm/skills/bundled/testing/webapp-testing/examples/static_html_automation.py +34 -0
  319. claude_mpm/skills/bundled/testing/webapp-testing/playwright-patterns.md +479 -0
  320. claude_mpm/skills/bundled/testing/webapp-testing/reconnaissance-pattern.md +687 -0
  321. claude_mpm/skills/bundled/testing/webapp-testing/scripts/with_server.py +129 -0
  322. claude_mpm/skills/bundled/testing/webapp-testing/server-management.md +758 -0
  323. claude_mpm/skills/bundled/testing/webapp-testing/troubleshooting.md +868 -0
  324. claude_mpm/skills/bundled/vite-local-dev.md +1061 -0
  325. claude_mpm/skills/bundled/web-performance-optimization.md +2305 -0
  326. claude_mpm/skills/bundled/xlsx.md +157 -0
  327. claude_mpm/skills/registry.py +286 -0
  328. claude_mpm/skills/skill_manager.py +310 -0
  329. claude_mpm/skills/skills_registry.py +348 -0
  330. claude_mpm/skills/skills_service.py +739 -0
  331. claude_mpm/tools/code_tree_analyzer.py +177 -141
  332. claude_mpm/tools/code_tree_events.py +4 -2
  333. claude_mpm/utils/agent_dependency_loader.py +2 -2
  334. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/METADATA +211 -33
  335. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/RECORD +339 -199
  336. claude_mpm/agents/INSTRUCTIONS_OLD_DEPRECATED.md +0 -602
  337. claude_mpm/cli/commands/mpm_init.py +0 -1994
  338. claude_mpm/dashboard/static/css/code-tree.css +0 -1639
  339. claude_mpm/dashboard/static/js/components/code-tree/tree-breadcrumb.js +0 -353
  340. claude_mpm/dashboard/static/js/components/code-tree/tree-constants.js +0 -235
  341. claude_mpm/dashboard/static/js/components/code-tree/tree-search.js +0 -409
  342. claude_mpm/dashboard/static/js/components/code-tree/tree-utils.js +0 -435
  343. claude_mpm/dashboard/static/js/components/code-tree.js +0 -5869
  344. claude_mpm/dashboard/static/js/components/code-viewer.js +0 -1386
  345. claude_mpm/hooks/claude_hooks/hook_handler_eventbus.py +0 -425
  346. claude_mpm/hooks/claude_hooks/hook_handler_original.py +0 -1041
  347. claude_mpm/hooks/claude_hooks/hook_handler_refactored.py +0 -347
  348. claude_mpm/services/agents/deployment/agent_lifecycle_manager_refactored.py +0 -575
  349. claude_mpm/services/project/analyzer_refactored.py +0 -450
  350. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/WHEEL +0 -0
  351. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/entry_points.txt +0 -0
  352. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/licenses/LICENSE +0 -0
  353. {claude_mpm-4.14.6.dist-info → claude_mpm-4.21.0.dist-info}/top_level.txt +0 -0
@@ -1,1994 +0,0 @@
1
- """
2
- MPM-Init Command - Initialize projects for optimal Claude Code and Claude MPM success.
3
-
4
- This command delegates to the Agentic Coder Optimizer agent to establish clear,
5
- single-path project standards for documentation, tooling, and workflows.
6
-
7
- Enhanced with AST inspection capabilities for generating comprehensive developer
8
- documentation with code structure analysis.
9
- """
10
-
11
- import contextlib
12
- import subprocess
13
- import sys
14
- from pathlib import Path
15
- from typing import Any, Dict, List, Optional
16
-
17
- import click
18
- from rich.console import Console
19
- from rich.panel import Panel
20
- from rich.progress import Progress, SpinnerColumn, TextColumn
21
- from rich.prompt import Prompt
22
-
23
- from claude_mpm.core.logging_utils import get_logger
24
-
25
- # Import new services
26
- from claude_mpm.services.project.archive_manager import ArchiveManager
27
- from claude_mpm.services.project.documentation_manager import DocumentationManager
28
- from claude_mpm.services.project.enhanced_analyzer import EnhancedProjectAnalyzer
29
- from claude_mpm.services.project.project_organizer import ProjectOrganizer
30
- from claude_mpm.utils.display_helper import DisplayHelper
31
-
32
- logger = get_logger(__name__)
33
- console = Console()
34
-
35
-
36
- class MPMInitCommand:
37
- """Initialize projects for optimal Claude Code and Claude MPM usage."""
38
-
39
- def __init__(self, project_path: Optional[Path] = None):
40
- """Initialize the MPM-Init command."""
41
- self.project_path = project_path or Path.cwd()
42
- self.claude_mpm_script = self._find_claude_mpm_script()
43
-
44
- # Initialize service components
45
- self.doc_manager = DocumentationManager(self.project_path)
46
- self.organizer = ProjectOrganizer(self.project_path)
47
- self.archive_manager = ArchiveManager(self.project_path)
48
- self.analyzer = EnhancedProjectAnalyzer(self.project_path)
49
- self.display = DisplayHelper(console)
50
-
51
- def initialize_project(
52
- self,
53
- project_type: Optional[str] = None,
54
- framework: Optional[str] = None,
55
- force: bool = False,
56
- verbose: bool = False,
57
- ast_analysis: bool = True,
58
- update_mode: bool = False,
59
- review_only: bool = False,
60
- organize_files: bool = False,
61
- preserve_custom: bool = True,
62
- skip_archive: bool = False,
63
- dry_run: bool = False,
64
- quick_update: bool = False,
65
- catchup: bool = False,
66
- non_interactive: bool = False,
67
- days: int = 30,
68
- export: Optional[str] = None,
69
- ) -> Dict:
70
- """
71
- Initialize project with Agentic Coder Optimizer standards.
72
-
73
- Args:
74
- project_type: Type of project (web, api, cli, library, etc.)
75
- framework: Specific framework if applicable
76
- force: Force initialization even if project already configured
77
- verbose: Show detailed output
78
- ast_analysis: Enable AST analysis for enhanced documentation
79
- update_mode: Update existing CLAUDE.md instead of recreating
80
- review_only: Review project state without making changes
81
- organize_files: Organize misplaced files into proper directories
82
- preserve_custom: Preserve custom sections when updating
83
- skip_archive: Skip archiving existing files
84
- dry_run: Show what would be done without making changes
85
- quick_update: Perform lightweight update based on recent git activity
86
- catchup: Show recent commit history from all branches for PM context
87
- non_interactive: Non-interactive mode - display report only without prompting
88
- days: Number of days for git history analysis (7, 14, 30, 60, or 90)
89
- export: Export report to file (path or "auto" for default location)
90
-
91
- Returns:
92
- Dict containing initialization results
93
- """
94
- try:
95
- # Determine initialization mode
96
- claude_md = self.project_path / "CLAUDE.md"
97
- has_existing = claude_md.exists()
98
-
99
- if review_only:
100
- return self._run_review_mode()
101
-
102
- if catchup:
103
- data = self._catchup()
104
- self._display_catchup(data)
105
- return {"status": "success", "mode": "catchup", "catchup_data": data}
106
-
107
- if quick_update:
108
- return self._run_quick_update_mode(
109
- days=days,
110
- non_interactive=non_interactive,
111
- export=export,
112
- )
113
-
114
- if has_existing and not force and not update_mode:
115
- # Auto-select update mode if organize_files or dry_run is specified
116
- if organize_files or dry_run:
117
- update_mode = True
118
- console.print(
119
- "[cyan]Auto-selecting update mode for organization tasks.[/cyan]\n"
120
- )
121
- else:
122
- # Offer update mode
123
- console.print(
124
- "[yellow]⚠️ Project already has CLAUDE.md file.[/yellow]\n"
125
- )
126
-
127
- # Show current documentation analysis
128
- doc_analysis = self.doc_manager.analyze_existing_content()
129
- self._display_documentation_status(doc_analysis)
130
-
131
- # Ask user what to do
132
- action = self._prompt_update_action()
133
-
134
- if action == "update":
135
- update_mode = True
136
- elif action == "recreate":
137
- force = True
138
- elif action == "review":
139
- return self._run_review_mode()
140
- else:
141
- return {
142
- "status": "cancelled",
143
- "message": "Initialization cancelled",
144
- }
145
-
146
- # Handle dry-run mode
147
- if dry_run:
148
- return self._run_dry_run_mode(organize_files, has_existing)
149
-
150
- # Run pre-initialization checks
151
- if not review_only:
152
- pre_check_result = self._run_pre_initialization_checks(
153
- organize_files, skip_archive, has_existing
154
- )
155
- if pre_check_result.get("status") == "error":
156
- return pre_check_result
157
-
158
- # Build the delegation prompt
159
- if update_mode:
160
- prompt = self._build_update_prompt(
161
- project_type, framework, ast_analysis, preserve_custom
162
- )
163
- else:
164
- prompt = self._build_initialization_prompt(
165
- project_type, framework, ast_analysis
166
- )
167
-
168
- # Show appropriate plan based on mode
169
- if update_mode:
170
- self._show_update_plan(ast_analysis, preserve_custom)
171
- else:
172
- self._show_initialization_plan(ast_analysis)
173
-
174
- # Execute via claude-mpm run command
175
- with Progress(
176
- SpinnerColumn(),
177
- TextColumn("[progress.description]{task.description}"),
178
- console=console,
179
- ) as progress:
180
- task_desc = (
181
- "[cyan]Updating documentation..."
182
- if update_mode
183
- else "[cyan]Delegating to Agentic Coder Optimizer..."
184
- )
185
- task = progress.add_task(task_desc, total=None)
186
-
187
- # Run the initialization through subprocess
188
- result = self._run_initialization(prompt, verbose, update_mode)
189
-
190
- complete_desc = (
191
- "[green]✓ Update complete"
192
- if update_mode
193
- else "[green]✓ Initialization complete"
194
- )
195
- progress.update(task, description=complete_desc)
196
-
197
- # Post-processing for update mode
198
- if update_mode and result.get("status") == "success":
199
- self._handle_update_post_processing()
200
-
201
- return result
202
-
203
- except Exception as e:
204
- logger.error(f"Failed to initialize project: {e}")
205
- console.print(f"[red]❌ Error: {e}[/red]")
206
- return {"status": "error", "message": str(e)}
207
-
208
- def _find_claude_mpm_script(self) -> Path:
209
- """Find the claude-mpm script location."""
210
- # Try to find claude-mpm in the project scripts directory first
211
- project_root = Path(__file__).parent.parent.parent.parent.parent
212
- script_path = project_root / "scripts" / "claude-mpm"
213
- if script_path.exists():
214
- return script_path
215
- # Otherwise assume it's in PATH
216
- return Path("claude-mpm")
217
-
218
- def _build_initialization_prompt(
219
- self,
220
- project_type: Optional[str] = None,
221
- framework: Optional[str] = None,
222
- ast_analysis: bool = True,
223
- ) -> str:
224
- """Build the initialization prompt for the agent."""
225
- base_prompt = f"""Please delegate this task to the Agentic Coder Optimizer agent:
226
-
227
- Initialize this project for optimal use with Claude Code and Claude MPM.
228
-
229
- Project Path: {self.project_path}
230
- """
231
-
232
- if project_type:
233
- base_prompt += f"Project Type: {project_type}\n"
234
-
235
- if framework:
236
- base_prompt += f"Framework: {framework}\n"
237
-
238
- base_prompt += """
239
- Please perform the following initialization tasks:
240
-
241
- 1. **Analyze Current State**:
242
- - Scan project structure and existing configurations
243
- - Identify project type, language, and frameworks
244
- - Check for existing documentation and tooling
245
-
246
- 2. **Create/Update CLAUDE.md**:
247
- - Project overview and purpose
248
- - Architecture and key components
249
- - Development guidelines
250
- - ONE clear way to: build, test, deploy, lint, format
251
- - Links to all relevant documentation
252
- - Common tasks and workflows
253
-
254
- 3. **Establish Single-Path Standards**:
255
- - ONE command for each operation (build, test, lint, etc.)
256
- - Clear documentation of THE way to do things
257
- - Remove ambiguity in workflows
258
-
259
- 4. **Configure Development Tools**:
260
- - Set up or verify linting configuration
261
- - Configure code formatting standards
262
- - Establish testing framework
263
- - Add pre-commit hooks if needed
264
-
265
- 5. **Create Project Structure Documentation**:
266
- - Document folder organization
267
- - Explain where different file types belong
268
- - Provide examples of proper file placement
269
-
270
- 6. **Set Up GitHub Integration** (if applicable):
271
- - Create/update .github/workflows
272
- - Add issue and PR templates
273
- - Configure branch protection rules documentation
274
-
275
- 7. **Initialize Memory System**:
276
- - Create .claude-mpm/memories/ directory
277
- - Add initial memory files for key project knowledge
278
- - Document memory usage patterns
279
-
280
- 8. **Generate Quick Start Guide**:
281
- - Step-by-step setup instructions
282
- - Common commands reference
283
- - Troubleshooting guide
284
- """
285
-
286
- if ast_analysis:
287
- base_prompt += """
288
- 9. **Perform AST Analysis** (using Code Analyzer agent if needed):
289
- - Parse code files to extract structure (classes, functions, methods)
290
- - Generate comprehensive API documentation
291
- - Create code architecture diagrams
292
- - Document function signatures and dependencies
293
- - Extract docstrings and inline comments
294
- - Map code relationships and inheritance hierarchies
295
- - Generate developer documentation with:
296
- * Module overview and purpose
297
- * Class hierarchies and relationships
298
- * Function/method documentation
299
- * Type annotations and parameter descriptions
300
- * Code complexity metrics
301
- * Dependency graphs
302
- - Create DEVELOPER.md with technical architecture details
303
- - Add CODE_STRUCTURE.md with AST-derived insights
304
- """
305
-
306
- base_prompt += """
307
-
308
- 10. **Holistic CLAUDE.md Organization** (CRITICAL - Do this LAST):
309
- After completing all initialization tasks, take a holistic look at the CLAUDE.md file and:
310
-
311
- a) **Reorganize Content by Priority**:
312
- - CRITICAL instructions (security, data handling, core business rules) at the TOP
313
- - Project overview and purpose
314
- - Key architectural decisions and constraints
315
- - Development guidelines and standards
316
- - Common tasks and workflows
317
- - Links to additional documentation
318
- - Nice-to-have or optional information at the BOTTOM
319
-
320
- b) **Rank Instructions by Importance**:
321
- - Use clear markers:
322
- * 🔴 CRITICAL: Security, data handling, breaking changes, core business rules
323
- * 🟡 IMPORTANT: Key workflows, architecture decisions, performance requirements
324
- * 🟢 STANDARD: Common operations, coding standards, best practices
325
- * ⚪ OPTIONAL: Nice-to-have features, experimental code, future considerations
326
- - Group related instructions together
327
- - Ensure no contradictory instructions exist
328
- - Remove redundant or outdated information
329
- - Add a "Priority Index" at the top listing all CRITICAL and IMPORTANT items
330
-
331
- c) **Optimize for AI Agent Understanding**:
332
- - Use consistent formatting and structure
333
- - Provide clear examples for complex instructions
334
- - Include "WHY" explanations for critical rules
335
- - Add quick reference sections for common operations
336
- - Ensure instructions are actionable and unambiguous
337
-
338
- d) **Validate Completeness**:
339
- - Ensure ALL critical project knowledge is captured
340
- - Verify single-path principle (ONE way to do each task)
341
- - Check that all referenced documentation exists
342
- - Confirm all tools and dependencies are documented
343
- - Test that a new AI agent could understand the project from CLAUDE.md alone
344
-
345
- e) **Add Meta-Instructions Section**:
346
- - Include a section about how to maintain CLAUDE.md
347
- - Document when and how to update instructions
348
- - Provide guidelines for instruction priority levels
349
- - Add a changelog or last-updated timestamp
350
-
351
- f) **Follow This CLAUDE.md Template Structure**:
352
- ```markdown
353
- # Project Name - CLAUDE.md
354
-
355
- ## 🎯 Priority Index
356
- ### 🔴 CRITICAL Instructions
357
- - [List all critical items with links to their sections]
358
-
359
- ### 🟡 IMPORTANT Instructions
360
- - [List all important items with links to their sections]
361
-
362
- ## 📋 Project Overview
363
- [Brief description and purpose]
364
-
365
- ## 🔴 CRITICAL: Security & Data Handling
366
- [Critical security rules and data handling requirements]
367
-
368
- ## 🔴 CRITICAL: Core Business Rules
369
- [Non-negotiable business logic and constraints]
370
-
371
- ## 🟡 IMPORTANT: Architecture & Design
372
- [Key architectural decisions and patterns]
373
-
374
- ## 🟡 IMPORTANT: Development Workflow
375
- ### ONE Way to Build
376
- ### ONE Way to Test
377
- ### ONE Way to Deploy
378
-
379
- ## 🟢 STANDARD: Coding Guidelines
380
- [Standard practices and conventions]
381
-
382
- ## 🟢 STANDARD: Common Tasks
383
- [How to perform routine operations]
384
-
385
- ## 📚 Documentation Links
386
- [Links to additional resources]
387
-
388
- ## ⚪ OPTIONAL: Future Enhancements
389
- [Nice-to-have features and ideas]
390
-
391
- ## 📝 Meta: Maintaining This Document
392
- - Last Updated: [timestamp]
393
- - Update Frequency: [when to update]
394
- - Priority Guidelines: [how to assign priorities]
395
- ```
396
-
397
- Please ensure all documentation is clear, concise, and optimized for AI agents to understand and follow.
398
- Focus on establishing ONE clear way to do ANYTHING in the project.
399
- The final CLAUDE.md should be a comprehensive, well-organized guide that any AI agent can follow to work effectively on this project.
400
- """
401
-
402
- return base_prompt
403
-
404
- def _build_claude_mpm_command(self, verbose: bool) -> List[str]:
405
- """Build the claude-mpm run command with appropriate arguments."""
406
- cmd = [str(self.claude_mpm_script)]
407
-
408
- # Add top-level flags that go before 'run' subcommand
409
- cmd.append("--no-check-dependencies")
410
-
411
- # Now add the run subcommand
412
- cmd.append("run")
413
-
414
- # Add non-interactive mode
415
- # We'll pass the prompt via stdin instead of -i flag
416
- cmd.append("--non-interactive")
417
-
418
- # Add verbose flag if requested (run subcommand argument)
419
- if verbose:
420
- cmd.append("--verbose")
421
-
422
- return cmd
423
-
424
- def _display_documentation_status(self, analysis: Dict) -> None:
425
- """Display current documentation status."""
426
- self.display.display_documentation_status(analysis)
427
-
428
- def _prompt_update_action(self) -> str:
429
- """Prompt user for update action."""
430
- console.print("\n[bold]How would you like to proceed?[/bold]\n")
431
-
432
- choices = {
433
- "1": ("update", "Update existing CLAUDE.md (preserves custom content)"),
434
- "2": ("recreate", "Recreate CLAUDE.md from scratch"),
435
- "3": ("review", "Review project state without changes"),
436
- "4": ("cancel", "Cancel operation"),
437
- }
438
-
439
- for key, (_, desc) in choices.items():
440
- console.print(f" [{key}] {desc}")
441
-
442
- choice = Prompt.ask(
443
- "\nSelect option", choices=list(choices.keys()), default="1"
444
- )
445
- return choices[choice][0]
446
-
447
- def _run_review_mode(self) -> Dict:
448
- """Run review mode to analyze project without changes."""
449
- console.print("\n[bold cyan]🔍 Project Review Mode[/bold cyan]\n")
450
-
451
- with Progress(
452
- SpinnerColumn(),
453
- TextColumn("[progress.description]{task.description}"),
454
- console=console,
455
- ) as progress:
456
- # Analyze project structure
457
- task = progress.add_task("[cyan]Analyzing project structure...", total=None)
458
- structure_report = self.organizer.verify_structure()
459
- progress.update(task, description="[green]✓ Structure analysis complete")
460
-
461
- # Analyze documentation
462
- task = progress.add_task("[cyan]Analyzing documentation...", total=None)
463
- doc_analysis = self.doc_manager.analyze_existing_content()
464
- progress.update(
465
- task, description="[green]✓ Documentation analysis complete"
466
- )
467
-
468
- # Analyze git history
469
- if self.analyzer.is_git_repo:
470
- task = progress.add_task("[cyan]Analyzing git history...", total=None)
471
- git_analysis = self.analyzer.analyze_git_history()
472
- progress.update(task, description="[green]✓ Git analysis complete")
473
- else:
474
- git_analysis = None
475
-
476
- # Detect project state
477
- task = progress.add_task("[cyan]Detecting project state...", total=None)
478
- project_state = self.analyzer.detect_project_state()
479
- progress.update(task, description="[green]✓ State detection complete")
480
-
481
- # Display comprehensive report
482
- self._display_review_report(
483
- structure_report, doc_analysis, git_analysis, project_state
484
- )
485
-
486
- return {
487
- "status": "success",
488
- "mode": "review",
489
- "structure_report": structure_report,
490
- "documentation_analysis": doc_analysis,
491
- "git_analysis": git_analysis,
492
- "project_state": project_state,
493
- }
494
-
495
- def _display_review_report(
496
- self, structure: Dict, docs: Dict, git: Optional[Dict], state: Dict
497
- ) -> None:
498
- """Display comprehensive review report."""
499
- self.display.display_header("PROJECT REVIEW REPORT")
500
-
501
- # Project State
502
- state_data = {"Phase": state.get("phase", "unknown")}
503
- if state.get("indicators"):
504
- state_data["Indicators"] = state["indicators"][:5]
505
- self.display.display_report_section("📊 Project State", state_data)
506
-
507
- # Structure Report
508
- structure_data = {
509
- "Existing directories": len(structure.get("exists", [])),
510
- "Missing directories": len(structure.get("missing", [])),
511
- }
512
- if structure.get("issues"):
513
- structure_data["Issues found"] = len(structure["issues"])
514
- structure_data["Issues"] = structure["issues"][:3]
515
- self.display.display_report_section("📁 Project Structure", structure_data)
516
-
517
- # Documentation Report
518
- self.display.display_section_title("📚 Documentation Status")
519
- if docs.get("exists"):
520
- console.print(f" CLAUDE.md: Found ({docs.get('size', 0):,} chars)")
521
- console.print(f" Sections: {len(docs.get('sections', []))}")
522
- console.print(
523
- f" Priority markers: {'Yes' if docs.get('has_priority_markers') else 'No'}"
524
- )
525
- else:
526
- console.print(" CLAUDE.md: Not found")
527
-
528
- # Git Analysis
529
- if git and git.get("git_available"):
530
- git_metrics = {
531
- "Commits": len(git.get("recent_commits", [])),
532
- "Authors": git.get("authors", {}).get("total_authors", 0),
533
- "Changed files": git.get("changed_files", {}).get("total_files", 0),
534
- }
535
-
536
- if git.get("branch_info"):
537
- branch_info = git["branch_info"]
538
- git_metrics["Current branch"] = branch_info.get(
539
- "current_branch", "unknown"
540
- )
541
-
542
- self.display.display_metrics_section(
543
- "📈 Recent Activity (30 days)", git_metrics
544
- )
545
-
546
- if git.get("branch_info", {}).get("has_uncommitted_changes"):
547
- self.display.display_metric_row(
548
- "⚠️ Uncommitted changes",
549
- f"{git['branch_info'].get('uncommitted_files', 0)} files",
550
- warning=True,
551
- )
552
-
553
- # Recommendations
554
- if state.get("recommendations"):
555
- self.display.display_recommendations(state["recommendations"])
556
-
557
- self.display.display_separator()
558
-
559
- def _run_quick_update_mode(
560
- self,
561
- days: int = 30,
562
- non_interactive: bool = False,
563
- export: Optional[str] = None,
564
- ) -> Dict:
565
- """Run quick update mode - lightweight update based on recent git activity."""
566
- console.print("\n[bold cyan]⚡ Quick Update Mode[/bold cyan]\n")
567
- console.print(
568
- f"[dim]Analyzing recent git activity ({days} days) for lightweight documentation update...[/dim]\n"
569
- )
570
-
571
- if not self.analyzer.is_git_repo:
572
- console.print(
573
- "[yellow]⚠️ Not a git repository. Quick update requires git.[/yellow]"
574
- )
575
- console.print(
576
- "[dim]Tip: Use `/mpm-init --review` for non-git projects.[/dim]\n"
577
- )
578
- return {
579
- "status": "error",
580
- "message": "Quick update requires a git repository",
581
- }
582
-
583
- claude_md = self.project_path / "CLAUDE.md"
584
- if not claude_md.exists():
585
- console.print(
586
- "[yellow]⚠️ CLAUDE.md not found. Quick update requires existing documentation.[/yellow]"
587
- )
588
- console.print(
589
- "[dim]Tip: Use `/mpm-init` to create initial documentation.[/dim]\n"
590
- )
591
- return {
592
- "status": "error",
593
- "message": "Quick update requires existing CLAUDE.md",
594
- }
595
-
596
- with Progress(
597
- SpinnerColumn(),
598
- TextColumn("[progress.description]{task.description}"),
599
- console=console,
600
- ) as progress:
601
- # Analyze git history
602
- task = progress.add_task(
603
- f"[cyan]Analyzing git history ({days} days)...", total=None
604
- )
605
- git_analysis = self.analyzer.analyze_git_history(days_back=days)
606
- progress.update(task, description="[green]✓ Git analysis complete")
607
-
608
- # Analyze current documentation
609
- task = progress.add_task(
610
- "[cyan]Checking documentation status...", total=None
611
- )
612
- doc_analysis = self.doc_manager.analyze_existing_content()
613
- progress.update(task, description="[green]✓ Documentation analyzed")
614
-
615
- # Generate activity report
616
- activity_report = self._generate_activity_report(
617
- git_analysis, doc_analysis, days
618
- )
619
-
620
- # Display the report
621
- self._display_activity_report(activity_report)
622
-
623
- # Export report if requested
624
- if export:
625
- export_path = self._export_activity_report(activity_report, export)
626
- console.print(f"\n[green]✅ Report exported to: {export_path}[/green]")
627
-
628
- # Handle non-interactive mode
629
- if non_interactive:
630
- console.print(
631
- "\n[cyan]ℹ️ Non-interactive mode: Report displayed, no changes made.[/cyan]"
632
- )
633
- return {
634
- "status": "success",
635
- "mode": "quick_update",
636
- "activity_report": activity_report,
637
- "changes_made": False,
638
- "non_interactive": True,
639
- }
640
-
641
- # Offer to append activity notes to CLAUDE.md
642
- console.print("\n[bold]Update Options:[/bold]")
643
- console.print(" [1] Append activity summary to CLAUDE.md")
644
- console.print(" [2] Display report only (no changes)")
645
- console.print(" [3] Cancel")
646
-
647
- from rich.prompt import Prompt
648
-
649
- choice = Prompt.ask("\nSelect option", choices=["1", "2", "3"], default="2")
650
-
651
- if choice == "1":
652
- # Append activity notes
653
- self._append_activity_notes(claude_md, activity_report)
654
- console.print("\n[green]✅ Activity notes appended to CLAUDE.md[/green]")
655
-
656
- # Archive the update
657
- self.archive_manager.auto_archive_before_update(
658
- claude_md, update_reason="Quick update - recent activity summary"
659
- )
660
-
661
- return {
662
- "status": "success",
663
- "mode": "quick_update",
664
- "activity_report": activity_report,
665
- "changes_made": True,
666
- }
667
- if choice == "2":
668
- console.print("\n[cyan]Report generated - no changes made[/cyan]")
669
- return {
670
- "status": "success",
671
- "mode": "quick_update",
672
- "activity_report": activity_report,
673
- "changes_made": False,
674
- }
675
- console.print("\n[yellow]Quick update cancelled[/yellow]")
676
- return {"status": "cancelled", "message": "Quick update cancelled"}
677
-
678
- def _catchup(self) -> Dict[str, Any]:
679
- """Get recent commit history for PM context.
680
-
681
- Returns:
682
- Dict containing commit history and contributor stats
683
- """
684
- from collections import Counter
685
- from datetime import datetime
686
- from subprocess import run
687
-
688
- try:
689
- # Get last 25 commits from all branches with author info
690
- result = run(
691
- ["git", "log", "--all", "--format=%h|%an|%ai|%s", "-25"],
692
- capture_output=True,
693
- text=True,
694
- check=True,
695
- cwd=str(self.project_path),
696
- )
697
-
698
- commits = []
699
- authors = []
700
-
701
- for line in result.stdout.strip().split("\n"):
702
- if not line:
703
- continue
704
-
705
- parts = line.split("|", 3)
706
- if len(parts) == 4:
707
- hash_val, author, date_str, message = parts
708
-
709
- # Parse date
710
- try:
711
- dt = datetime.fromisoformat(date_str.replace(" ", "T", 1))
712
- date_display = dt.strftime("%Y-%m-%d %H:%M")
713
- except Exception:
714
- date_display = date_str[:16]
715
-
716
- commits.append(
717
- {
718
- "hash": hash_val,
719
- "author": author,
720
- "date": date_display,
721
- "message": message,
722
- }
723
- )
724
- authors.append(author)
725
-
726
- # Calculate contributor stats
727
- author_counts = Counter(authors)
728
-
729
- return {
730
- "commits": commits,
731
- "total_commits": len(commits),
732
- "contributors": dict(author_counts),
733
- "contributor_count": len(author_counts),
734
- }
735
-
736
- except Exception as e:
737
- console.print(f"[yellow]Could not retrieve commit history: {e}[/yellow]")
738
- return {
739
- "commits": [],
740
- "total_commits": 0,
741
- "contributors": {},
742
- "contributor_count": 0,
743
- "error": str(e),
744
- }
745
-
746
- def _display_catchup(self, data: Dict[str, Any]) -> None:
747
- """Display catchup information to console.
748
-
749
- Args:
750
- data: Commit history data from _catchup()
751
- """
752
- from rich.panel import Panel
753
- from rich.table import Table
754
-
755
- if data.get("error"):
756
- console.print(
757
- Panel(
758
- "[yellow]Not a git repository or no commits found[/yellow]",
759
- title="⚠️ Catchup Status",
760
- border_style="yellow",
761
- )
762
- )
763
- return
764
-
765
- # Display contributor summary
766
- if data["contributors"]:
767
- console.print("\n[bold cyan]👥 Active Contributors[/bold cyan]")
768
- for author, count in sorted(
769
- data["contributors"].items(), key=lambda x: x[1], reverse=True
770
- ):
771
- console.print(
772
- f" • [green]{author}[/green]: {count} commit{'s' if count != 1 else ''}"
773
- )
774
-
775
- # Display commit history table
776
- if data["commits"]:
777
- console.print(
778
- f"\n[bold cyan]📝 Last {data['total_commits']} Commits[/bold cyan]"
779
- )
780
-
781
- table = Table(
782
- show_header=True, header_style="bold magenta", border_style="dim"
783
- )
784
- table.add_column("#", style="dim", width=3)
785
- table.add_column("Hash", style="yellow", width=8)
786
- table.add_column("Author", style="green", width=20)
787
- table.add_column("Date", style="cyan", width=16)
788
- table.add_column("Message", style="white")
789
-
790
- for idx, commit in enumerate(data["commits"], 1):
791
- # Truncate message if too long
792
- msg = commit["message"]
793
- if len(msg) > 80:
794
- msg = msg[:77] + "..."
795
-
796
- # Truncate author if too long
797
- author = commit["author"]
798
- if len(author) > 18:
799
- author = author[:18] + "..."
800
-
801
- table.add_row(str(idx), commit["hash"], author, commit["date"], msg)
802
-
803
- console.print(table)
804
-
805
- # Display PM recommendations
806
- console.print("\n[bold cyan]💡 PM Recommendations[/bold cyan]")
807
- console.print(
808
- f" • Total activity: {data['total_commits']} commits from {data['contributor_count']} contributor{'s' if data['contributor_count'] != 1 else ''}"
809
- )
810
- console.print(" • Review commit messages for recent project context")
811
- console.print(" • Identify development patterns and focus areas")
812
- console.print(" • Use this context to inform current work priorities\n")
813
-
814
- def _generate_activity_report(
815
- self, git_analysis: Dict, doc_analysis: Dict, days: int = 30
816
- ) -> Dict:
817
- """Generate activity report from git analysis and documentation status."""
818
- from datetime import datetime, timezone
819
-
820
- report = {
821
- "period": f"Last {days} days",
822
- "generated_at": datetime.now(timezone.utc).isoformat(),
823
- "summary": {},
824
- "recommendations": [],
825
- }
826
-
827
- # Git activity summary
828
- if git_analysis.get("git_available"):
829
- recent_commits = git_analysis.get("recent_commits", [])
830
- changed_files = git_analysis.get("changed_files", {})
831
- authors = git_analysis.get("authors", {})
832
- branch_info = git_analysis.get("branch_info", {})
833
-
834
- report["summary"] = {
835
- "total_commits": len(recent_commits),
836
- "total_authors": authors.get("total_authors", 0),
837
- "files_changed": changed_files.get("total_files", 0),
838
- "current_branch": branch_info.get("current_branch", "unknown"),
839
- "has_uncommitted": branch_info.get("has_uncommitted_changes", False),
840
- "uncommitted_count": branch_info.get("uncommitted_files", 0),
841
- }
842
-
843
- # Recent commits (last 10)
844
- report["recent_commits"] = recent_commits[:10]
845
-
846
- # Most changed files
847
- most_changed = changed_files.get("most_changed", {})
848
- report["hot_files"] = list(most_changed.items())[:10]
849
-
850
- # Active branches
851
- branches = branch_info.get("branches", [])
852
- report["active_branches"] = [
853
- b for b in branches if not b.startswith("remotes/")
854
- ][:5]
855
-
856
- # Generate recommendations
857
- if len(recent_commits) > 20:
858
- report["recommendations"].append(
859
- "High activity detected - consider updating architecture docs"
860
- )
861
-
862
- if changed_files.get("total_files", 0) > 50:
863
- report["recommendations"].append(
864
- "Many files changed - review CLAUDE.md for accuracy"
865
- )
866
-
867
- if branch_info.get("has_uncommitted_changes"):
868
- report["recommendations"].append(
869
- "Uncommitted changes detected - commit before updating docs"
870
- )
871
-
872
- # Check for documentation changes
873
- doc_changes = git_analysis.get("documentation_changes", {})
874
- if not doc_changes.get("has_recent_doc_changes"):
875
- report["recommendations"].append(
876
- "No recent doc updates - CLAUDE.md may be outdated"
877
- )
878
-
879
- # Documentation freshness
880
- if doc_analysis.get("exists"):
881
- report["doc_status"] = {
882
- "size": doc_analysis.get("size", 0),
883
- "lines": doc_analysis.get("lines", 0),
884
- "has_priority_index": doc_analysis.get("has_priority_index", False),
885
- "has_priority_markers": doc_analysis.get("has_priority_markers", False),
886
- "last_modified": doc_analysis.get("last_modified", "unknown"),
887
- }
888
-
889
- if not doc_analysis.get("has_priority_markers"):
890
- report["recommendations"].append(
891
- "Add priority markers (🔴🟡🟢⚪) to CLAUDE.md"
892
- )
893
-
894
- return report
895
-
896
- def _export_activity_report(self, report: Dict, export_path: str) -> Path:
897
- """Export activity report to a markdown file."""
898
- from datetime import datetime, timezone
899
- from pathlib import Path
900
-
901
- # Determine export path
902
- if export_path == "auto":
903
- # Generate default path with timestamp
904
- timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
905
- reports_dir = self.project_path / "docs" / "reports"
906
- reports_dir.mkdir(parents=True, exist_ok=True)
907
- file_path = reports_dir / f"activity-report-{timestamp}.md"
908
- else:
909
- # Use provided path
910
- file_path = Path(export_path)
911
- if not file_path.is_absolute():
912
- file_path = self.project_path / file_path
913
- # Create parent directory if needed
914
- file_path.parent.mkdir(parents=True, exist_ok=True)
915
-
916
- # Generate markdown content
917
- summary = report.get("summary", {})
918
- timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
919
-
920
- content = f"""# Activity Report
921
-
922
- **Generated**: {timestamp}
923
- **Analysis Period**: {report.get('period', 'Last 30 days')}
924
-
925
- ## Summary
926
-
927
- - **Total Commits**: {summary.get('total_commits', 0)}
928
- - **Active Contributors**: {summary.get('total_authors', 0)}
929
- - **Files Modified**: {summary.get('files_changed', 0)}
930
- - **Current Branch**: {summary.get('current_branch', 'unknown')}
931
- """
932
-
933
- if summary.get("has_uncommitted"):
934
- content += f"- **⚠️ Uncommitted Changes**: {summary.get('uncommitted_count', 0)} files\n"
935
-
936
- # Recent commits
937
- recent_commits = report.get("recent_commits", [])
938
- if recent_commits:
939
- content += "\n## Recent Commits\n\n"
940
- for commit in recent_commits[:10]:
941
- content += (
942
- f"- `{commit['hash']}` {commit['message']} - {commit['author']}\n"
943
- )
944
-
945
- # Hot files
946
- hot_files = report.get("hot_files", [])
947
- if hot_files:
948
- content += "\n## Most Changed Files\n\n"
949
- for hot_file_path, changes in hot_files[:10]:
950
- content += f"- `{hot_file_path}`: {changes} changes\n"
951
-
952
- # Active branches
953
- branches = report.get("active_branches", [])
954
- if branches:
955
- content += "\n## Active Branches\n\n"
956
- for branch in branches:
957
- marker = "→" if branch == summary.get("current_branch") else " "
958
- content += f"{marker} {branch}\n"
959
-
960
- # Documentation status
961
- doc_status = report.get("doc_status", {})
962
- if doc_status:
963
- content += "\n## CLAUDE.md Status\n\n"
964
- content += f"- **Size**: {doc_status.get('size', 0):,} characters\n"
965
- content += f"- **Lines**: {doc_status.get('lines', 0)}\n"
966
- content += f"- **Priority Markers**: {'✓' if doc_status.get('has_priority_markers') else '✗'}\n"
967
- content += (
968
- f"- **Last Modified**: {doc_status.get('last_modified', 'unknown')}\n"
969
- )
970
-
971
- # Recommendations
972
- recommendations = report.get("recommendations", [])
973
- if recommendations:
974
- content += "\n## Recommendations\n\n"
975
- for rec in recommendations:
976
- content += f"- {rec}\n"
977
-
978
- content += (
979
- "\n---\n\n*Generated by Claude MPM `/mpm-init --quick-update --export`*\n"
980
- )
981
-
982
- # Write to file
983
- file_path.write_text(content, encoding="utf-8")
984
-
985
- return file_path
986
-
987
- def _display_activity_report(self, report: Dict) -> None:
988
- """Display the activity report in a formatted manner."""
989
- self.display.display_header("RECENT ACTIVITY SUMMARY")
990
-
991
- summary = report.get("summary", {})
992
- period = report.get("period", "Last 30 days")
993
-
994
- # Summary statistics
995
- self.display.display_activity_summary(summary, period)
996
-
997
- # Recent commits
998
- recent_commits = report.get("recent_commits", [])
999
- if recent_commits:
1000
- self.display.display_commit_list(recent_commits)
1001
-
1002
- # Hot files
1003
- hot_files = report.get("hot_files", [])
1004
- if hot_files:
1005
- self.display.display_file_change_list(hot_files)
1006
-
1007
- # Active branches
1008
- branches = report.get("active_branches", [])
1009
- current_branch = summary.get("current_branch", "unknown")
1010
- if branches:
1011
- self.display.display_branch_list(branches, current_branch)
1012
-
1013
- # Documentation status
1014
- doc_status = report.get("doc_status", {})
1015
- if doc_status:
1016
- doc_metrics = {
1017
- "Size": f"{doc_status.get('size', 0):,} characters",
1018
- "Lines": doc_status.get("lines", 0),
1019
- "Priority markers": (
1020
- "✓" if doc_status.get("has_priority_markers") else "✗"
1021
- ),
1022
- "Last modified": doc_status.get("last_modified", "unknown"),
1023
- }
1024
- self.display.display_metrics_section("📚 CLAUDE.md Status", doc_metrics)
1025
-
1026
- # Recommendations
1027
- recommendations = report.get("recommendations", [])
1028
- if recommendations:
1029
- self.display.display_recommendations(recommendations)
1030
-
1031
- self.display.display_separator()
1032
-
1033
- def _append_activity_notes(self, claude_md_path: Path, report: Dict) -> None:
1034
- """Append activity notes to CLAUDE.md."""
1035
- from datetime import datetime, timezone
1036
-
1037
- # Generate activity summary section
1038
- summary = report.get("summary", {})
1039
- timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
1040
-
1041
- activity_section = f"""
1042
-
1043
- ---
1044
-
1045
- ## 📈 Recent Activity Summary
1046
-
1047
- **Last Updated**: {timestamp}
1048
- **Analysis Period**: {report.get('period', 'Last 30 days')}
1049
-
1050
- ### Activity Metrics
1051
- - **Commits**: {summary.get('total_commits', 0)}
1052
- - **Contributors**: {summary.get('total_authors', 0)}
1053
- - **Files Changed**: {summary.get('files_changed', 0)}
1054
- - **Current Branch**: {summary.get('current_branch', 'unknown')}
1055
- """
1056
-
1057
- if summary.get("has_uncommitted"):
1058
- activity_section += f"- **⚠️ Uncommitted Changes**: {summary.get('uncommitted_count', 0)} files\n"
1059
-
1060
- # Add recent commits
1061
- recent_commits = report.get("recent_commits", [])
1062
- if recent_commits:
1063
- activity_section += "\n### Recent Commits\n"
1064
- for commit in recent_commits[:5]:
1065
- activity_section += f"- `{commit['hash']}` {commit['message'][:60]} ({commit['author']})\n"
1066
-
1067
- # Add hot files
1068
- hot_files = report.get("hot_files", [])
1069
- if hot_files:
1070
- activity_section += "\n### Most Active Files\n"
1071
- for file_path, changes in hot_files[:5]:
1072
- activity_section += f"- `{file_path}`: {changes} changes\n"
1073
-
1074
- # Add recommendations
1075
- recommendations = report.get("recommendations", [])
1076
- if recommendations:
1077
- activity_section += "\n### 💡 Recommendations\n"
1078
- for rec in recommendations:
1079
- activity_section += f"- {rec}\n"
1080
-
1081
- activity_section += "\n---\n"
1082
-
1083
- # Append to file
1084
- with open(claude_md_path, "a", encoding="utf-8") as f:
1085
- f.write(activity_section)
1086
-
1087
- def _run_dry_run_mode(self, organize_files: bool, has_existing: bool) -> Dict:
1088
- """Run dry-run mode to show what would be done without making changes."""
1089
- console.print("\n[bold cyan]🔍 Dry Run Mode - Preview Changes[/bold cyan]\n")
1090
-
1091
- actions_planned = []
1092
-
1093
- # Check what organization would do
1094
- if organize_files:
1095
- console.print("[bold]📁 File Organization Analysis:[/bold]")
1096
-
1097
- # Get structure validation without making changes
1098
- validation = self.organizer.validate_structure()
1099
- if validation.get("issues"):
1100
- console.print(" [yellow]Files that would be organized:[/yellow]")
1101
- for issue in validation["issues"][:10]:
1102
- actions_planned.append(
1103
- f"Organize: {issue.get('description', 'Unknown')}"
1104
- )
1105
- console.print(f" • {issue.get('description', 'Unknown')}")
1106
- else:
1107
- console.print(" ✅ Project structure is already well-organized")
1108
-
1109
- # Check what documentation updates would occur
1110
- if has_existing:
1111
- console.print("\n[bold]📚 Documentation Updates:[/bold]")
1112
- doc_analysis = self.doc_manager.analyze_existing_content()
1113
-
1114
- if not doc_analysis.get("has_priority_markers"):
1115
- actions_planned.append("Add priority markers (🔴🟡🟢⚪)")
1116
- console.print(" • Add priority markers (🔴🟡🟢⚪)")
1117
-
1118
- if doc_analysis.get("outdated_patterns"):
1119
- actions_planned.append("Update outdated patterns")
1120
- console.print(" • Update outdated patterns")
1121
-
1122
- if not doc_analysis.get("has_priority_index"):
1123
- actions_planned.append("Add priority index section")
1124
- console.print(" • Add priority index section")
1125
-
1126
- # Archive would be created
1127
- actions_planned.append("Archive current CLAUDE.md to docs/_archive/")
1128
- console.print(" • Archive current CLAUDE.md to docs/_archive/")
1129
- else:
1130
- console.print("\n[bold]📚 Documentation Creation:[/bold]")
1131
- actions_planned.append("Create new CLAUDE.md with priority structure")
1132
- console.print(" • Create new CLAUDE.md with priority structure")
1133
-
1134
- # General improvements
1135
- console.print("\n[bold]🔧 General Improvements:[/bold]")
1136
- actions_planned.extend(
1137
- [
1138
- "Update/create .gitignore if needed",
1139
- "Verify project structure compliance",
1140
- "Add memory system initialization",
1141
- "Set up single-path workflows",
1142
- ]
1143
- )
1144
- for action in actions_planned[-4:]:
1145
- console.print(f" • {action}")
1146
-
1147
- console.print(
1148
- f"\n[bold cyan]Summary: {len(actions_planned)} actions would be performed[/bold cyan]"
1149
- )
1150
- console.print("\n[dim]Run without --dry-run to execute these changes.[/dim]\n")
1151
-
1152
- return {
1153
- "status": "success",
1154
- "mode": "dry_run",
1155
- "actions_planned": actions_planned,
1156
- "message": "Dry run completed - no changes made",
1157
- }
1158
-
1159
- def _run_pre_initialization_checks(
1160
- self, organize_files: bool, skip_archive: bool, has_existing: bool
1161
- ) -> Dict:
1162
- """Run pre-initialization checks and preparations."""
1163
- checks_passed = []
1164
- warnings = []
1165
-
1166
- # Run comprehensive project readiness check
1167
- ready, actions = self.organizer.ensure_project_ready(
1168
- auto_organize=organize_files,
1169
- safe_mode=True, # Only perform safe operations by default
1170
- )
1171
-
1172
- if actions:
1173
- checks_passed.extend(actions)
1174
-
1175
- # Get structure validation report
1176
- validation = self.organizer.validate_structure()
1177
- if validation["warnings"]:
1178
- warnings.extend(validation["warnings"])
1179
- if validation["errors"]:
1180
- warnings.extend(validation["errors"])
1181
-
1182
- # Show structure grade
1183
- if validation.get("grade"):
1184
- checks_passed.append(f"Structure validation: {validation['grade']}")
1185
-
1186
- # Archive existing documentation if needed
1187
- if has_existing and not skip_archive:
1188
- if self.archive_manager.auto_archive_before_update(
1189
- self.project_path / "CLAUDE.md", update_reason="Before mpm-init update"
1190
- ):
1191
- checks_passed.append("Archived existing CLAUDE.md")
1192
-
1193
- # Check for issues in validation report
1194
- if validation.get("issues"):
1195
- for issue in validation["issues"]:
1196
- warnings.append(issue["description"])
1197
-
1198
- if warnings:
1199
- console.print("\n[yellow]⚠️ Project issues detected:[/yellow]")
1200
- for warning in warnings[:5]:
1201
- console.print(f" • {warning}")
1202
- console.print()
1203
-
1204
- if checks_passed:
1205
- console.print("[green]✅ Pre-initialization checks:[/green]")
1206
- for check in checks_passed:
1207
- console.print(f" • {check}")
1208
- console.print()
1209
-
1210
- return {
1211
- "status": "success",
1212
- "checks_passed": checks_passed,
1213
- "warnings": warnings,
1214
- }
1215
-
1216
- def _show_update_plan(self, ast_analysis: bool, preserve_custom: bool) -> None:
1217
- """Show update mode plan."""
1218
- console.print(
1219
- Panel(
1220
- "[bold cyan]🔄 Claude MPM Documentation Update[/bold cyan]\n\n"
1221
- "This will update your existing CLAUDE.md with:\n"
1222
- "• Smart merging of new and existing content\n"
1223
- + ("• Preservation of custom sections\n" if preserve_custom else "")
1224
- + "• Priority-based reorganization (🔴🟡🟢⚪)\n"
1225
- "• Updated single-path workflows\n"
1226
- "• Refreshed tool configurations\n"
1227
- + (
1228
- "• AST analysis for enhanced documentation\n"
1229
- if ast_analysis
1230
- else ""
1231
- )
1232
- + "• Automatic archival of previous version\n"
1233
- + "• Holistic review and optimization\n"
1234
- + "\n[dim]Previous version will be archived in docs/_archive/[/dim]",
1235
- title="Update Mode",
1236
- border_style="blue",
1237
- )
1238
- )
1239
-
1240
- def _show_initialization_plan(self, ast_analysis: bool) -> None:
1241
- """Show standard initialization plan."""
1242
- console.print(
1243
- Panel(
1244
- "[bold cyan]🤖👥 Claude MPM Project Initialization[/bold cyan]\n\n"
1245
- "This will set up your project with:\n"
1246
- "• Clear CLAUDE.md documentation for AI agents\n"
1247
- "• Single-path workflows (ONE way to do ANYTHING)\n"
1248
- "• Optimized project structure\n"
1249
- "• Tool configurations (linting, formatting, testing)\n"
1250
- "• GitHub workflows and CI/CD setup\n"
1251
- "• Memory system initialization\n"
1252
- + (
1253
- "• AST analysis for comprehensive code documentation\n"
1254
- if ast_analysis
1255
- else ""
1256
- )
1257
- + "• Holistic CLAUDE.md organization with ranked instructions\n"
1258
- + "• Priority-based content structure (🔴🟡🟢⚪)\n"
1259
- + "\n[dim]Powered by Agentic Coder Optimizer Agent[/dim]",
1260
- title="MPM-Init",
1261
- border_style="cyan",
1262
- )
1263
- )
1264
-
1265
- def _build_update_prompt(
1266
- self,
1267
- project_type: Optional[str],
1268
- framework: Optional[str],
1269
- ast_analysis: bool,
1270
- preserve_custom: bool,
1271
- ) -> str:
1272
- """Build prompt for update mode."""
1273
- # Get existing content analysis
1274
- doc_analysis = self.doc_manager.analyze_existing_content()
1275
-
1276
- prompt = f"""Please delegate this task to the Agentic Coder Optimizer agent:
1277
-
1278
- UPDATE existing CLAUDE.md documentation for this project.
1279
-
1280
- Project Path: {self.project_path}
1281
- Update Mode: Smart merge with existing content
1282
- """
1283
- if project_type:
1284
- prompt += f"Project Type: {project_type}\n"
1285
- if framework:
1286
- prompt += f"Framework: {framework}\n"
1287
-
1288
- prompt += f"""
1289
- Existing Documentation Analysis:
1290
- - Current CLAUDE.md: {doc_analysis.get('size', 0):,} characters, {doc_analysis.get('lines', 0)} lines
1291
- - Has Priority Index: {'Yes' if doc_analysis.get('has_priority_index') else 'No'}
1292
- - Custom Sections: {len(doc_analysis.get('custom_sections', []))} found
1293
- """
1294
- if preserve_custom and doc_analysis.get("custom_sections"):
1295
- prompt += f"- Preserve Custom Sections: {', '.join(doc_analysis['custom_sections'][:5])}\n"
1296
-
1297
- prompt += """
1298
- Please perform the following UPDATE tasks:
1299
-
1300
- 1. **Review Existing Content**:
1301
- - Analyze current CLAUDE.md structure and content
1302
- - Identify outdated or missing information
1303
- - Preserve valuable custom sections and project-specific knowledge
1304
-
1305
- 2. **Smart Content Merge**:
1306
- - Update project overview if needed
1307
- - Refresh architecture documentation
1308
- - Update development workflows to ensure single-path principle
1309
- - Merge new standard sections while preserving custom content
1310
- - Remove duplicate or contradictory information
1311
-
1312
- 3. **Update Priority Organization**:
1313
- - Reorganize content with priority markers (🔴🟡🟢⚪)
1314
- - Ensure critical instructions are at the top
1315
- - Update priority index with all important items
1316
- - Validate instruction clarity and completeness
1317
-
1318
- 4. **Refresh Technical Content**:
1319
- - Update build/test/deploy commands
1320
- - Verify tool configurations are current
1321
- - Update dependency information
1322
- - Refresh API documentation if applicable
1323
- """
1324
- if ast_analysis:
1325
- prompt += """
1326
- 5. **Update Code Documentation** (using Code Analyzer agent):
1327
- - Re-analyze code structure for changes
1328
- - Update API documentation
1329
- - Refresh architecture diagrams
1330
- - Update function/class documentation
1331
- """
1332
- prompt += """
1333
- 6. **Final Optimization**:
1334
- - Ensure single-path principle throughout
1335
- - Validate all links and references
1336
- - Add/update timestamp in meta section
1337
- - Verify AI agent readability
1338
-
1339
- IMPORTANT: This is an UPDATE operation. Intelligently merge new content with existing,
1340
- preserving valuable project-specific information while refreshing standard sections.
1341
- """
1342
- return prompt
1343
-
1344
- def _handle_update_post_processing(self) -> None:
1345
- """Handle post-processing after successful update."""
1346
- # Generate update report
1347
- if self.doc_manager.has_existing_documentation():
1348
- latest_archive = self.archive_manager.get_latest_archive("CLAUDE.md")
1349
- if latest_archive:
1350
- comparison = self.archive_manager.compare_with_archive(
1351
- self.project_path / "CLAUDE.md", latest_archive.name
1352
- )
1353
-
1354
- if not comparison.get("identical"):
1355
- console.print("\n[bold cyan]📊 Update Summary[/bold cyan]")
1356
- console.print(
1357
- f" Lines changed: {comparison.get('lines_added', 0):+d}"
1358
- )
1359
- console.print(
1360
- f" Size change: {comparison.get('size_change', 0):+,} characters"
1361
- )
1362
- console.print(f" Previous version: {latest_archive.name}")
1363
-
1364
- def _run_initialization(
1365
- self,
1366
- prompt: str,
1367
- verbose: bool,
1368
- update_mode: bool = False,
1369
- ) -> Dict:
1370
- """Run the initialization through subprocess calling claude-mpm."""
1371
- import tempfile
1372
-
1373
- try:
1374
- # Write prompt to temporary file
1375
- with tempfile.NamedTemporaryFile(
1376
- mode="w", suffix=".txt", delete=False
1377
- ) as tmp_file:
1378
- tmp_file.write(prompt)
1379
- prompt_file = tmp_file.name
1380
-
1381
- try:
1382
- # Build the command
1383
- cmd = self._build_claude_mpm_command(verbose)
1384
- # Add the input file flag
1385
- cmd.extend(["-i", prompt_file])
1386
-
1387
- # Log the command if verbose
1388
- if verbose:
1389
- console.print(f"[dim]Running: {' '.join(cmd)}[/dim]")
1390
- console.print(f"[dim]Prompt file: {prompt_file}[/dim]")
1391
-
1392
- # Execute the command
1393
- result = subprocess.run(
1394
- cmd,
1395
- capture_output=True,
1396
- text=True,
1397
- cwd=str(self.project_path),
1398
- check=False,
1399
- )
1400
- finally:
1401
- # Clean up temporary file
1402
-
1403
- with contextlib.suppress(Exception):
1404
- Path(prompt_file).unlink()
1405
-
1406
- # Display output if verbose
1407
- if verbose and result.stdout:
1408
- console.print(result.stdout)
1409
- if verbose and result.stderr:
1410
- console.print(f"[yellow]{result.stderr}[/yellow]")
1411
-
1412
- # Check result - be more lenient with return codes
1413
- if result.returncode == 0 or (self.project_path / "CLAUDE.md").exists():
1414
- response = {
1415
- "status": "success",
1416
- "message": "Project initialized successfully",
1417
- "files_created": [],
1418
- "files_updated": [],
1419
- "next_steps": [],
1420
- }
1421
-
1422
- # Check if CLAUDE.md was created
1423
- claude_md = self.project_path / "CLAUDE.md"
1424
- if claude_md.exists():
1425
- response["files_created"].append("CLAUDE.md")
1426
-
1427
- # Check for other common files
1428
- for file_name in ["CODE.md", "DEVELOPER.md", "STRUCTURE.md", "OPS.md"]:
1429
- file_path = self.project_path / file_name
1430
- if file_path.exists():
1431
- response["files_created"].append(file_name)
1432
-
1433
- # Add next steps
1434
- response["next_steps"] = [
1435
- "Review the generated CLAUDE.md documentation",
1436
- "Verify the project structure meets your needs",
1437
- "Run 'claude-mpm run' to start using the optimized setup",
1438
- ]
1439
-
1440
- # Display results
1441
- self._display_results(response, verbose)
1442
-
1443
- return response
1444
- # Extract meaningful error message
1445
- error_msg = (
1446
- result.stderr
1447
- if result.stderr
1448
- else result.stdout if result.stdout else "Unknown error occurred"
1449
- )
1450
-
1451
- logger.error(f"claude-mpm run failed: {error_msg}")
1452
- return {
1453
- "status": "error",
1454
- "message": f"Initialization failed: {error_msg}",
1455
- }
1456
-
1457
- except FileNotFoundError:
1458
- logger.error("claude-mpm command not found")
1459
- console.print(
1460
- "[red]Error: claude-mpm command not found. Ensure Claude MPM is properly installed.[/red]"
1461
- )
1462
- return {"status": "error", "message": "claude-mpm not found"}
1463
- except Exception as e:
1464
- logger.error(f"Initialization failed: {e}")
1465
- return {"status": "error", "message": str(e)}
1466
-
1467
- def handle_context(
1468
- self,
1469
- session_id: Optional[str] = None,
1470
- list_sessions: bool = False,
1471
- days: int = 7,
1472
- ) -> Dict[str, Any]:
1473
- """
1474
- Provide intelligent context for resuming work based on git history.
1475
-
1476
- Analyzes recent commits to identify:
1477
- - Active work streams (what was being worked on)
1478
- - Intent and motivation (why this work)
1479
- - Risks and blockers
1480
- - Recommended next actions
1481
-
1482
- This delegates to Research agent for deep analysis.
1483
-
1484
- Args:
1485
- session_id: Unused parameter (for compatibility)
1486
- list_sessions: Unused parameter (for compatibility)
1487
- days: Number of days of git history to analyze (default: 7)
1488
-
1489
- Returns:
1490
- Dict containing context result
1491
- """
1492
- from claude_mpm.utils.git_analyzer import analyze_recent_activity
1493
-
1494
- # 1. Analyze git history with adaptive window
1495
- console.print(f"\n🔍 Analyzing last {days} days of git history...\n")
1496
- git_analysis = analyze_recent_activity(
1497
- repo_path=str(self.project_path), days=days, max_commits=50, min_commits=25
1498
- )
1499
-
1500
- # Show adaptive behavior to user
1501
- if git_analysis.get("adaptive_mode"):
1502
- console.print(
1503
- f"[cyan]ℹ️ Note: Analyzed {git_analysis.get('actual_time_span', 'extended period')} "
1504
- f"to get meaningful context[/cyan]"
1505
- )
1506
- if git_analysis.get("reason"):
1507
- console.print(f"[dim] Reason: {git_analysis['reason']}[/dim]\n")
1508
- else:
1509
- console.print()
1510
-
1511
- if git_analysis.get("error"):
1512
- console.print(
1513
- f"[yellow]⚠️ Could not analyze git history: {git_analysis['error']}[/yellow]"
1514
- )
1515
- console.print(
1516
- "[dim]Ensure this is a git repository with commit history.[/dim]\n"
1517
- )
1518
- return {
1519
- "status": "error",
1520
- "message": git_analysis["error"],
1521
- }
1522
-
1523
- if not git_analysis.get("has_activity"):
1524
- console.print(
1525
- f"[yellow]⚠️ No git activity found in the last {days} days.[/yellow]"
1526
- )
1527
- console.print("[dim]Try increasing the --days parameter.[/dim]\n")
1528
- return {
1529
- "status": "error",
1530
- "message": f"No git activity in last {days} days",
1531
- }
1532
-
1533
- # 2. Build Research delegation prompt
1534
- research_prompt = self._build_research_context_prompt(git_analysis, days)
1535
-
1536
- # 3. Display prompt for PM to delegate
1537
- console.print("\n" + "=" * 80)
1538
- console.print("📋 DELEGATE TO RESEARCH AGENT:")
1539
- console.print("=" * 80 + "\n")
1540
- console.print(research_prompt)
1541
- console.print("\n" + "=" * 80 + "\n")
1542
-
1543
- return {
1544
- "status": "context_ready",
1545
- "git_analysis": git_analysis,
1546
- "research_prompt": research_prompt,
1547
- "recommendation": "PM should delegate this prompt to Research agent",
1548
- }
1549
-
1550
- def _build_research_context_prompt(
1551
- self, git_analysis: Dict[str, Any], days: int
1552
- ) -> str:
1553
- """Build structured Research agent delegation prompt from git analysis."""
1554
-
1555
- # Extract key data
1556
- commits = git_analysis.get("commits", [])
1557
- branches = git_analysis.get("branches", [])
1558
- contributors = git_analysis.get("contributors", {})
1559
- file_changes = git_analysis.get("file_changes", {})
1560
-
1561
- # Build prompt following Prompt Engineer's template
1562
- prompt = f"""# Project Context Analysis Mission
1563
-
1564
- You are Research agent analyzing git history to provide PM with intelligent project context for resuming work.
1565
-
1566
- ## Analysis Scope
1567
- - **Time Range**: Last {days} days"""
1568
-
1569
- # Add adaptive mode note if applicable
1570
- if git_analysis.get("adaptive_mode"):
1571
- actual_days = git_analysis.get("actual_time_span", "extended period")
1572
- prompt += f""" (adaptive: {actual_days} days analyzed)
1573
- - **Note**: {git_analysis.get('reason', 'Analysis window adjusted to ensure meaningful context')}"""
1574
-
1575
- prompt += f"""
1576
- - **Commits Analyzed**: {len(commits)} commits
1577
- - **Branches**: {', '.join(branches[:5]) if branches else 'main'}
1578
- - **Contributors**: {', '.join(contributors.keys()) if contributors else 'Unknown'}
1579
-
1580
- ## Your Mission
1581
-
1582
- Analyze git history to answer these questions for PM:
1583
-
1584
- 1. **What was being worked on?** (Active work streams)
1585
- 2. **Why was this work happening?** (Intent and motivation)
1586
- 3. **What's the natural next step?** (Continuation recommendations)
1587
- 4. **What needs attention?** (Risks, stalls, conflicts)
1588
-
1589
- ## Git Data Provided
1590
-
1591
- ### Recent Commits ({min(len(commits), 10)} most recent):
1592
- """
1593
-
1594
- # Add recent commits
1595
- for commit in commits[:10]:
1596
- author = commit.get("author", "Unknown")
1597
- timestamp = commit.get("timestamp", "Unknown date")
1598
- message = commit.get("message", "No message")
1599
- files = commit.get("files", [])
1600
-
1601
- prompt += f"\n- **{timestamp}** by {author}"
1602
- prompt += f"\n {message}"
1603
- prompt += f"\n Files changed: {len(files)}\n"
1604
-
1605
- # Add file change summary
1606
- if file_changes:
1607
- # Sort by modifications count
1608
- sorted_files = sorted(
1609
- file_changes.items(),
1610
- key=lambda x: x[1].get("modifications", 0),
1611
- reverse=True,
1612
- )
1613
- prompt += "\n### Most Changed Files:\n"
1614
- for file_path, file_data in sorted_files[:10]:
1615
- modifications = file_data.get("modifications", 0)
1616
- file_contributors = file_data.get("contributors", [])
1617
- prompt += f"- {file_path}: {modifications} changes ({len(file_contributors)} contributor{'s' if len(file_contributors) != 1 else ''})\n"
1618
-
1619
- # Add contributor summary
1620
- if contributors:
1621
- prompt += "\n### Contributors:\n"
1622
- sorted_contributors = sorted(
1623
- contributors.items(),
1624
- key=lambda x: x[1].get("commits", 0),
1625
- reverse=True,
1626
- )
1627
- for name, info in sorted_contributors[:5]:
1628
- commit_count = info.get("commits", 0)
1629
- prompt += f"- {name}: {commit_count} commit{'s' if commit_count != 1 else ''}\n"
1630
-
1631
- # Add analysis instructions
1632
- prompt += """
1633
-
1634
- ## Analysis Instructions
1635
-
1636
- ### Phase 1: Work Stream Identification
1637
- Group related commits into thematic work streams. For each stream:
1638
- - **Name**: Infer from commit messages (e.g., "Authentication refactor")
1639
- - **Status**: ongoing/completed/stalled
1640
- - **Commits**: Count of commits in this stream
1641
- - **Intent**: WHY this work (from commit bodies/messages)
1642
- - **Key Files**: Most changed files in this stream
1643
-
1644
- ### Phase 2: Risk Detection
1645
- Identify:
1646
- - **Stalled Work**: Work streams with no activity >3 days
1647
- - **Anti-Patterns**: WIP commits, temp commits, debug commits
1648
- - **Documentation Lag**: Code changes without doc updates
1649
- - **Conflicts**: Merge conflicts or divergent branches
1650
-
1651
- ### Phase 3: Recommendations
1652
- Based on analysis:
1653
- 1. **Primary Focus**: Most active/recent work to continue
1654
- 2. **Quick Wins**: Small tasks that could be finished
1655
- 3. **Blockers**: Issues preventing progress
1656
- 4. **Next Steps**: Logical continuation points
1657
-
1658
- ## Output Format
1659
-
1660
- Provide a clear markdown summary with:
1661
-
1662
- 1. **Active Work Streams** (What was being worked on)
1663
- 2. **Intent Summary** (Why this work matters)
1664
- 3. **Risks Detected** (What needs attention)
1665
- 4. **Recommended Next Actions** (What to work on)
1666
-
1667
- Keep it concise (<1000 words) but actionable.
1668
-
1669
- ## Success Criteria
1670
- - Work streams accurately reflect development themes
1671
- - Intent captures the "why" not just "what"
1672
- - Recommendations are specific and actionable
1673
- - Risks are prioritized by impact
1674
- """
1675
-
1676
- return prompt
1677
-
1678
- def _display_results(self, result: Dict, verbose: bool):
1679
- """Display initialization results."""
1680
- if result["status"] == "success":
1681
- console.print("\n[green]✅ Project Initialization Complete![/green]\n")
1682
-
1683
- # Display files created
1684
- if result.get("files_created"):
1685
- self.display.display_files_list(
1686
- "Files Created:", result["files_created"]
1687
- )
1688
-
1689
- # Display files updated
1690
- if result.get("files_updated"):
1691
- self.display.display_files_list(
1692
- "Files Updated:", result["files_updated"]
1693
- )
1694
-
1695
- # Display next steps
1696
- if result.get("next_steps"):
1697
- self.display.display_next_steps(result["next_steps"])
1698
-
1699
- # Display success panel
1700
- success_content = (
1701
- "[green]Your project is now optimized for Claude Code and Claude MPM![/green]\n\n"
1702
- "Key files:\n"
1703
- "• [cyan]CLAUDE.md[/cyan] - Main documentation for AI agents\n"
1704
- " - Organized with priority rankings (🔴🟡🟢⚪)\n"
1705
- " - Instructions ranked by importance for AI understanding\n"
1706
- " - Holistic documentation review completed\n"
1707
- "• [cyan].claude-mpm/[/cyan] - Configuration and memories\n"
1708
- "• [cyan]CODE_STRUCTURE.md[/cyan] - AST-derived architecture documentation (if enabled)\n\n"
1709
- "[dim]Run 'claude-mpm run' to start using the optimized setup[/dim]"
1710
- )
1711
- self.display.display_success_panel("Success", success_content)
1712
-
1713
-
1714
- @click.group(name="mpm-init", invoke_without_command=True)
1715
- @click.option(
1716
- "--project-type",
1717
- type=click.Choice(
1718
- ["web", "api", "cli", "library", "mobile", "desktop", "fullstack"]
1719
- ),
1720
- help="Type of project to initialize",
1721
- )
1722
- @click.option(
1723
- "--framework",
1724
- type=str,
1725
- help="Specific framework (e.g., react, django, fastapi, express)",
1726
- )
1727
- @click.option(
1728
- "--force",
1729
- is_flag=True,
1730
- help="Force reinitialization even if project is already configured",
1731
- )
1732
- @click.option(
1733
- "--update",
1734
- is_flag=True,
1735
- help="Update existing CLAUDE.md instead of recreating",
1736
- )
1737
- @click.option(
1738
- "--review",
1739
- is_flag=True,
1740
- help="Review project state without making changes",
1741
- )
1742
- @click.option(
1743
- "--organize",
1744
- is_flag=True,
1745
- help="Automatically organize misplaced files into proper directories",
1746
- )
1747
- @click.option(
1748
- "--auto-safe/--no-auto-safe",
1749
- default=True,
1750
- help="Only move files with high confidence (default: safe mode on)",
1751
- )
1752
- @click.option(
1753
- "--preserve-custom/--no-preserve-custom",
1754
- default=True,
1755
- help="Preserve custom sections when updating (default: preserve)",
1756
- )
1757
- @click.option(
1758
- "--skip-archive",
1759
- is_flag=True,
1760
- help="Skip archiving existing files before updating",
1761
- )
1762
- @click.option(
1763
- "--verbose", is_flag=True, help="Show detailed output during initialization"
1764
- )
1765
- @click.option(
1766
- "--ast-analysis/--no-ast-analysis",
1767
- default=True,
1768
- help="Enable/disable AST analysis for enhanced documentation (default: enabled)",
1769
- )
1770
- @click.option(
1771
- "--quick-update",
1772
- is_flag=True,
1773
- help="Perform lightweight update based on recent git activity (default: 30 days)",
1774
- )
1775
- @click.option(
1776
- "--catchup",
1777
- is_flag=True,
1778
- help="Show recent commit history from all branches for PM context",
1779
- )
1780
- @click.option(
1781
- "--non-interactive",
1782
- is_flag=True,
1783
- help="Non-interactive mode - display report only without prompting (use with --quick-update)",
1784
- )
1785
- @click.option(
1786
- "--days",
1787
- type=int,
1788
- default=30,
1789
- help="Number of days for git history analysis in quick update mode (default: 30)",
1790
- )
1791
- @click.option(
1792
- "--export",
1793
- type=str,
1794
- default=None,
1795
- help="Export activity report to file (default: docs/reports/activity-report-{timestamp}.md)",
1796
- )
1797
- @click.argument(
1798
- "project_path",
1799
- type=click.Path(exists=True, file_okay=False, dir_okay=True),
1800
- required=False,
1801
- default=".",
1802
- )
1803
- @click.pass_context
1804
- def mpm_init(
1805
- ctx,
1806
- project_type,
1807
- framework,
1808
- force,
1809
- update,
1810
- review,
1811
- organize,
1812
- auto_safe,
1813
- preserve_custom,
1814
- skip_archive,
1815
- verbose,
1816
- ast_analysis,
1817
- quick_update,
1818
- catchup,
1819
- non_interactive,
1820
- days,
1821
- export,
1822
- project_path,
1823
- ):
1824
- """
1825
- Initialize or update a project for optimal use with Claude Code and Claude MPM.
1826
-
1827
- This command uses the Agentic Coder Optimizer agent to:
1828
- - Create or update comprehensive CLAUDE.md documentation
1829
- - Establish single-path workflows (ONE way to do ANYTHING)
1830
- - Configure development tools and standards
1831
- - Set up memory systems for project knowledge
1832
- - Optimize for AI agent understanding
1833
- - Perform AST analysis for enhanced developer documentation
1834
-
1835
- Context Management:
1836
- - resume: Analyze git history to provide context for resuming work
1837
- - --catchup: Show recent commit history for PM context
1838
-
1839
- Update Mode:
1840
- When CLAUDE.md exists, the command offers to update rather than recreate,
1841
- preserving custom content while refreshing standard sections.
1842
-
1843
- Examples:
1844
- claude-mpm mpm-init # Initialize/update current directory
1845
- claude-mpm mpm-init --catchup # Show recent git history for context
1846
- claude-mpm mpm-init --review # Review project state without changes
1847
- claude-mpm mpm-init --update # Force update mode
1848
- claude-mpm mpm-init --organize # Organize misplaced files
1849
- claude-mpm mpm-init --project-type web # Initialize as web project
1850
- claude-mpm mpm-init /path/to/project --force # Force reinitialize project
1851
- """
1852
- # If a subcommand is being invoked, don't run the main command
1853
- if ctx.invoked_subcommand is not None:
1854
- return
1855
-
1856
- try:
1857
- # Create command instance
1858
- command = MPMInitCommand(Path(project_path))
1859
-
1860
- # Run initialization (now synchronous)
1861
- result = command.initialize_project(
1862
- project_type=project_type,
1863
- framework=framework,
1864
- force=force,
1865
- verbose=verbose,
1866
- ast_analysis=ast_analysis,
1867
- update_mode=update,
1868
- review_only=review,
1869
- organize_files=organize,
1870
- preserve_custom=preserve_custom,
1871
- skip_archive=skip_archive,
1872
- quick_update=quick_update,
1873
- catchup=catchup,
1874
- non_interactive=non_interactive,
1875
- days=days,
1876
- export=export,
1877
- )
1878
-
1879
- # Exit with appropriate code
1880
- if result["status"] == "success":
1881
- sys.exit(0)
1882
- else:
1883
- sys.exit(1)
1884
-
1885
- except KeyboardInterrupt:
1886
- console.print("\n[yellow]Initialization cancelled by user[/yellow]")
1887
- sys.exit(130)
1888
- except Exception as e:
1889
- console.print(f"[red]Initialization failed: {e}[/red]")
1890
- sys.exit(1)
1891
-
1892
-
1893
- @mpm_init.command(name="context")
1894
- @click.option(
1895
- "--session-id",
1896
- "-i",
1897
- type=str,
1898
- help="Unused (for compatibility) - will be removed in future version",
1899
- )
1900
- @click.option(
1901
- "--days",
1902
- type=int,
1903
- default=7,
1904
- help="Number of days of git history to analyze (default: 7)",
1905
- )
1906
- @click.argument(
1907
- "project_path",
1908
- type=click.Path(exists=True, file_okay=False, dir_okay=True),
1909
- required=False,
1910
- default=".",
1911
- )
1912
- def context_command(session_id, days, project_path):
1913
- """
1914
- Provide intelligent context for resuming work based on git history.
1915
-
1916
- Analyzes recent git history and generates a Research agent delegation
1917
- prompt for intelligent project context reconstruction.
1918
-
1919
- Examples:
1920
- claude-mpm mpm-init context # Analyze last 7 days
1921
- claude-mpm mpm-init context --days 14 # Analyze last 14 days
1922
- claude-mpm mpm-init context --days 30 # Analyze last 30 days
1923
-
1924
- Note: 'resume' is deprecated, use 'context' instead.
1925
- """
1926
- try:
1927
- command = MPMInitCommand(Path(project_path))
1928
-
1929
- result = command.handle_context(session_id=session_id, days=days)
1930
-
1931
- if result["status"] == "success" or result["status"] == "context_ready":
1932
- sys.exit(0)
1933
- else:
1934
- sys.exit(1)
1935
-
1936
- except KeyboardInterrupt:
1937
- console.print("\n[yellow]Context analysis cancelled by user[/yellow]")
1938
- sys.exit(130)
1939
- except Exception as e:
1940
- console.print(f"[red]Context analysis failed: {e}[/red]")
1941
- sys.exit(1)
1942
-
1943
-
1944
- # Add deprecated 'resume' alias for backward compatibility
1945
- @mpm_init.command(name="resume", hidden=True)
1946
- @click.option(
1947
- "--session-id",
1948
- "-i",
1949
- type=str,
1950
- help="Unused (for compatibility) - will be removed in future version",
1951
- )
1952
- @click.option(
1953
- "--days",
1954
- type=int,
1955
- default=7,
1956
- help="Number of days of git history to analyze (default: 7)",
1957
- )
1958
- @click.argument(
1959
- "project_path",
1960
- type=click.Path(exists=True, file_okay=False, dir_okay=True),
1961
- required=False,
1962
- default=".",
1963
- )
1964
- def resume_session(session_id, days, project_path):
1965
- """
1966
- [DEPRECATED] Use 'context' instead.
1967
-
1968
- This command is deprecated and will be removed in a future version.
1969
- Please use 'claude-mpm mpm-init context' instead.
1970
- """
1971
- console.print(
1972
- "[yellow]⚠️ Warning: 'resume' is deprecated. Use 'context' instead.[/yellow]"
1973
- )
1974
- console.print("[dim]Run: claude-mpm mpm-init context[/dim]\n")
1975
-
1976
- try:
1977
- command = MPMInitCommand(Path(project_path))
1978
- result = command.handle_context(session_id=session_id, days=days)
1979
-
1980
- if result["status"] == "success" or result["status"] == "context_ready":
1981
- sys.exit(0)
1982
- else:
1983
- sys.exit(1)
1984
-
1985
- except KeyboardInterrupt:
1986
- console.print("\n[yellow]Context analysis cancelled by user[/yellow]")
1987
- sys.exit(130)
1988
- except Exception as e:
1989
- console.print(f"[red]Context analysis failed: {e}[/red]")
1990
- sys.exit(1)
1991
-
1992
-
1993
- # Export for CLI registration
1994
- __all__ = ["mpm_init"]