claude-mpm 4.15.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 (194) 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/PM_INSTRUCTIONS.md +49 -0
  5. claude_mpm/agents/agent_loader.py +4 -4
  6. claude_mpm/agents/templates/engineer.json +5 -1
  7. claude_mpm/agents/templates/php-engineer.json +10 -4
  8. claude_mpm/agents/templates/python_engineer.json +8 -3
  9. claude_mpm/agents/templates/rust_engineer.json +12 -7
  10. claude_mpm/agents/templates/svelte-engineer.json +225 -0
  11. claude_mpm/cli/commands/__init__.py +2 -0
  12. claude_mpm/cli/commands/mpm_init/__init__.py +73 -0
  13. claude_mpm/cli/commands/mpm_init/core.py +525 -0
  14. claude_mpm/cli/commands/mpm_init/display.py +341 -0
  15. claude_mpm/cli/commands/mpm_init/git_activity.py +427 -0
  16. claude_mpm/cli/commands/mpm_init/modes.py +397 -0
  17. claude_mpm/cli/commands/mpm_init/prompts.py +442 -0
  18. claude_mpm/cli/commands/mpm_init_cli.py +396 -0
  19. claude_mpm/cli/commands/mpm_init_handler.py +67 -1
  20. claude_mpm/cli/commands/skills.py +488 -0
  21. claude_mpm/cli/executor.py +2 -0
  22. claude_mpm/cli/parsers/base_parser.py +7 -0
  23. claude_mpm/cli/parsers/mpm_init_parser.py +42 -0
  24. claude_mpm/cli/parsers/skills_parser.py +137 -0
  25. claude_mpm/cli/startup.py +57 -0
  26. claude_mpm/commands/mpm-auto-configure.md +52 -0
  27. claude_mpm/commands/mpm-help.md +3 -0
  28. claude_mpm/commands/mpm-init.md +112 -6
  29. claude_mpm/commands/mpm-version.md +113 -0
  30. claude_mpm/commands/mpm.md +1 -0
  31. claude_mpm/config/agent_config.py +2 -2
  32. claude_mpm/constants.py +12 -0
  33. claude_mpm/core/config.py +42 -0
  34. claude_mpm/core/factories.py +1 -1
  35. claude_mpm/core/interfaces.py +56 -1
  36. claude_mpm/core/optimized_agent_loader.py +3 -3
  37. claude_mpm/hooks/__init__.py +8 -0
  38. claude_mpm/hooks/claude_hooks/response_tracking.py +35 -1
  39. claude_mpm/hooks/session_resume_hook.py +121 -0
  40. claude_mpm/models/resume_log.py +340 -0
  41. claude_mpm/services/agents/auto_config_manager.py +1 -1
  42. claude_mpm/services/agents/deployment/agent_configuration_manager.py +1 -1
  43. claude_mpm/services/agents/deployment/agent_record_service.py +1 -1
  44. claude_mpm/services/agents/deployment/agent_validator.py +17 -1
  45. claude_mpm/services/agents/deployment/async_agent_deployment.py +1 -1
  46. claude_mpm/services/agents/deployment/local_template_deployment.py +1 -1
  47. claude_mpm/services/agents/local_template_manager.py +1 -1
  48. claude_mpm/services/agents/recommender.py +47 -0
  49. claude_mpm/services/cli/resume_service.py +617 -0
  50. claude_mpm/services/cli/session_manager.py +87 -0
  51. claude_mpm/services/cli/session_pause_manager.py +504 -0
  52. claude_mpm/services/cli/session_resume_helper.py +372 -0
  53. claude_mpm/services/core/interfaces.py +56 -1
  54. claude_mpm/services/core/models/agent_config.py +3 -0
  55. claude_mpm/services/core/models/process.py +4 -0
  56. claude_mpm/services/core/path_resolver.py +1 -1
  57. claude_mpm/services/diagnostics/models.py +21 -0
  58. claude_mpm/services/infrastructure/resume_log_generator.py +439 -0
  59. claude_mpm/services/local_ops/__init__.py +2 -0
  60. claude_mpm/services/mcp_config_manager.py +7 -131
  61. claude_mpm/services/mcp_gateway/auto_configure.py +31 -25
  62. claude_mpm/services/mcp_gateway/core/process_pool.py +19 -10
  63. claude_mpm/services/mcp_gateway/tools/external_mcp_services.py +26 -21
  64. claude_mpm/services/session_manager.py +205 -1
  65. claude_mpm/services/unified/deployment_strategies/local.py +1 -1
  66. claude_mpm/services/version_service.py +104 -1
  67. claude_mpm/skills/__init__.py +21 -0
  68. claude_mpm/skills/agent_skills_injector.py +324 -0
  69. claude_mpm/skills/bundled/LICENSE_ATTRIBUTIONS.md +79 -0
  70. claude_mpm/skills/bundled/api-documentation.md +393 -0
  71. claude_mpm/skills/bundled/async-testing.md +571 -0
  72. claude_mpm/skills/bundled/code-review.md +143 -0
  73. claude_mpm/skills/bundled/collaboration/brainstorming/SKILL.md +79 -0
  74. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/SKILL.md +178 -0
  75. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/agent-prompts.md +577 -0
  76. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/coordination-patterns.md +467 -0
  77. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/examples.md +537 -0
  78. claude_mpm/skills/bundled/collaboration/dispatching-parallel-agents/references/troubleshooting.md +730 -0
  79. claude_mpm/skills/bundled/collaboration/requesting-code-review/SKILL.md +112 -0
  80. claude_mpm/skills/bundled/collaboration/requesting-code-review/references/code-reviewer-template.md +146 -0
  81. claude_mpm/skills/bundled/collaboration/requesting-code-review/references/review-examples.md +412 -0
  82. claude_mpm/skills/bundled/collaboration/writing-plans/SKILL.md +81 -0
  83. claude_mpm/skills/bundled/collaboration/writing-plans/references/best-practices.md +362 -0
  84. claude_mpm/skills/bundled/collaboration/writing-plans/references/plan-structure-templates.md +312 -0
  85. claude_mpm/skills/bundled/database-migration.md +199 -0
  86. claude_mpm/skills/bundled/debugging/root-cause-tracing/SKILL.md +152 -0
  87. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/advanced-techniques.md +668 -0
  88. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/examples.md +587 -0
  89. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/integration.md +438 -0
  90. claude_mpm/skills/bundled/debugging/root-cause-tracing/references/tracing-techniques.md +391 -0
  91. claude_mpm/skills/bundled/debugging/systematic-debugging/CREATION-LOG.md +119 -0
  92. claude_mpm/skills/bundled/debugging/systematic-debugging/SKILL.md +148 -0
  93. claude_mpm/skills/bundled/debugging/systematic-debugging/references/anti-patterns.md +483 -0
  94. claude_mpm/skills/bundled/debugging/systematic-debugging/references/examples.md +452 -0
  95. claude_mpm/skills/bundled/debugging/systematic-debugging/references/troubleshooting.md +449 -0
  96. claude_mpm/skills/bundled/debugging/systematic-debugging/references/workflow.md +411 -0
  97. claude_mpm/skills/bundled/debugging/systematic-debugging/test-academic.md +14 -0
  98. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-1.md +58 -0
  99. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-2.md +68 -0
  100. claude_mpm/skills/bundled/debugging/systematic-debugging/test-pressure-3.md +69 -0
  101. claude_mpm/skills/bundled/debugging/verification-before-completion/SKILL.md +131 -0
  102. claude_mpm/skills/bundled/debugging/verification-before-completion/references/gate-function.md +325 -0
  103. claude_mpm/skills/bundled/debugging/verification-before-completion/references/integration-and-workflows.md +490 -0
  104. claude_mpm/skills/bundled/debugging/verification-before-completion/references/red-flags-and-failures.md +425 -0
  105. claude_mpm/skills/bundled/debugging/verification-before-completion/references/verification-patterns.md +499 -0
  106. claude_mpm/skills/bundled/docker-containerization.md +194 -0
  107. claude_mpm/skills/bundled/express-local-dev.md +1429 -0
  108. claude_mpm/skills/bundled/fastapi-local-dev.md +1199 -0
  109. claude_mpm/skills/bundled/git-workflow.md +414 -0
  110. claude_mpm/skills/bundled/imagemagick.md +204 -0
  111. claude_mpm/skills/bundled/json-data-handling.md +223 -0
  112. claude_mpm/skills/bundled/main/artifacts-builder/SKILL.md +86 -0
  113. claude_mpm/skills/bundled/main/internal-comms/SKILL.md +43 -0
  114. claude_mpm/skills/bundled/main/internal-comms/examples/3p-updates.md +47 -0
  115. claude_mpm/skills/bundled/main/internal-comms/examples/company-newsletter.md +65 -0
  116. claude_mpm/skills/bundled/main/internal-comms/examples/faq-answers.md +30 -0
  117. claude_mpm/skills/bundled/main/internal-comms/examples/general-comms.md +16 -0
  118. claude_mpm/skills/bundled/main/mcp-builder/SKILL.md +160 -0
  119. claude_mpm/skills/bundled/main/mcp-builder/reference/design_principles.md +412 -0
  120. claude_mpm/skills/bundled/main/mcp-builder/reference/evaluation.md +602 -0
  121. claude_mpm/skills/bundled/main/mcp-builder/reference/mcp_best_practices.md +915 -0
  122. claude_mpm/skills/bundled/main/mcp-builder/reference/node_mcp_server.md +916 -0
  123. claude_mpm/skills/bundled/main/mcp-builder/reference/python_mcp_server.md +752 -0
  124. claude_mpm/skills/bundled/main/mcp-builder/reference/workflow.md +1237 -0
  125. claude_mpm/skills/bundled/main/mcp-builder/scripts/connections.py +157 -0
  126. claude_mpm/skills/bundled/main/mcp-builder/scripts/evaluation.py +425 -0
  127. claude_mpm/skills/bundled/main/skill-creator/SKILL.md +189 -0
  128. claude_mpm/skills/bundled/main/skill-creator/references/best-practices.md +500 -0
  129. claude_mpm/skills/bundled/main/skill-creator/references/creation-workflow.md +464 -0
  130. claude_mpm/skills/bundled/main/skill-creator/references/examples.md +619 -0
  131. claude_mpm/skills/bundled/main/skill-creator/references/progressive-disclosure.md +437 -0
  132. claude_mpm/skills/bundled/main/skill-creator/references/skill-structure.md +231 -0
  133. claude_mpm/skills/bundled/main/skill-creator/scripts/init_skill.py +303 -0
  134. claude_mpm/skills/bundled/main/skill-creator/scripts/package_skill.py +113 -0
  135. claude_mpm/skills/bundled/main/skill-creator/scripts/quick_validate.py +72 -0
  136. claude_mpm/skills/bundled/nextjs-local-dev.md +807 -0
  137. claude_mpm/skills/bundled/pdf.md +141 -0
  138. claude_mpm/skills/bundled/performance-profiling.md +567 -0
  139. claude_mpm/skills/bundled/php/espocrm-development/SKILL.md +170 -0
  140. claude_mpm/skills/bundled/php/espocrm-development/references/architecture.md +602 -0
  141. claude_mpm/skills/bundled/php/espocrm-development/references/common-tasks.md +821 -0
  142. claude_mpm/skills/bundled/php/espocrm-development/references/development-workflow.md +742 -0
  143. claude_mpm/skills/bundled/php/espocrm-development/references/frontend-customization.md +726 -0
  144. claude_mpm/skills/bundled/php/espocrm-development/references/hooks-and-services.md +764 -0
  145. claude_mpm/skills/bundled/php/espocrm-development/references/testing-debugging.md +831 -0
  146. claude_mpm/skills/bundled/refactoring-patterns.md +180 -0
  147. claude_mpm/skills/bundled/rust/desktop-applications/SKILL.md +226 -0
  148. claude_mpm/skills/bundled/rust/desktop-applications/references/architecture-patterns.md +901 -0
  149. claude_mpm/skills/bundled/rust/desktop-applications/references/native-gui-frameworks.md +901 -0
  150. claude_mpm/skills/bundled/rust/desktop-applications/references/platform-integration.md +775 -0
  151. claude_mpm/skills/bundled/rust/desktop-applications/references/state-management.md +937 -0
  152. claude_mpm/skills/bundled/rust/desktop-applications/references/tauri-framework.md +770 -0
  153. claude_mpm/skills/bundled/rust/desktop-applications/references/testing-deployment.md +961 -0
  154. claude_mpm/skills/bundled/security-scanning.md +327 -0
  155. claude_mpm/skills/bundled/systematic-debugging.md +473 -0
  156. claude_mpm/skills/bundled/test-driven-development.md +378 -0
  157. claude_mpm/skills/bundled/testing/condition-based-waiting/SKILL.md +119 -0
  158. claude_mpm/skills/bundled/testing/condition-based-waiting/references/patterns-and-implementation.md +253 -0
  159. claude_mpm/skills/bundled/testing/test-driven-development/SKILL.md +145 -0
  160. claude_mpm/skills/bundled/testing/test-driven-development/references/anti-patterns.md +543 -0
  161. claude_mpm/skills/bundled/testing/test-driven-development/references/examples.md +741 -0
  162. claude_mpm/skills/bundled/testing/test-driven-development/references/integration.md +470 -0
  163. claude_mpm/skills/bundled/testing/test-driven-development/references/philosophy.md +458 -0
  164. claude_mpm/skills/bundled/testing/test-driven-development/references/workflow.md +639 -0
  165. claude_mpm/skills/bundled/testing/testing-anti-patterns/SKILL.md +140 -0
  166. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/completeness-anti-patterns.md +572 -0
  167. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/core-anti-patterns.md +411 -0
  168. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/detection-guide.md +569 -0
  169. claude_mpm/skills/bundled/testing/testing-anti-patterns/references/tdd-connection.md +695 -0
  170. claude_mpm/skills/bundled/testing/webapp-testing/SKILL.md +184 -0
  171. claude_mpm/skills/bundled/testing/webapp-testing/decision-tree.md +459 -0
  172. claude_mpm/skills/bundled/testing/webapp-testing/examples/console_logging.py +35 -0
  173. claude_mpm/skills/bundled/testing/webapp-testing/examples/element_discovery.py +44 -0
  174. claude_mpm/skills/bundled/testing/webapp-testing/examples/static_html_automation.py +34 -0
  175. claude_mpm/skills/bundled/testing/webapp-testing/playwright-patterns.md +479 -0
  176. claude_mpm/skills/bundled/testing/webapp-testing/reconnaissance-pattern.md +687 -0
  177. claude_mpm/skills/bundled/testing/webapp-testing/scripts/with_server.py +129 -0
  178. claude_mpm/skills/bundled/testing/webapp-testing/server-management.md +758 -0
  179. claude_mpm/skills/bundled/testing/webapp-testing/troubleshooting.md +868 -0
  180. claude_mpm/skills/bundled/vite-local-dev.md +1061 -0
  181. claude_mpm/skills/bundled/web-performance-optimization.md +2305 -0
  182. claude_mpm/skills/bundled/xlsx.md +157 -0
  183. claude_mpm/skills/registry.py +97 -9
  184. claude_mpm/skills/skills_registry.py +348 -0
  185. claude_mpm/skills/skills_service.py +739 -0
  186. claude_mpm/utils/agent_dependency_loader.py +2 -2
  187. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/METADATA +211 -33
  188. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/RECORD +192 -60
  189. claude_mpm/agents/INSTRUCTIONS_OLD_DEPRECATED.md +0 -602
  190. claude_mpm/cli/commands/mpm_init.py +0 -2008
  191. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/WHEEL +0 -0
  192. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/entry_points.txt +0 -0
  193. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/licenses/LICENSE +0 -0
  194. {claude_mpm-4.15.6.dist-info → claude_mpm-4.21.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,73 @@
1
+ """MPM initialization command package.
2
+
3
+ This package provides comprehensive project initialization and update capabilities
4
+ for Claude Code and Claude MPM. It includes:
5
+
6
+ - Core command class (MPMInitCommand) for orchestrating initialization
7
+ - Click CLI commands for command-line interface
8
+ - Modular components for prompts, display, git analysis, and modes
9
+ - Support for multiple initialization modes (create, update, review, quick-update, catchup)
10
+
11
+ Main Components:
12
+ - core.py: MPMInitCommand class - main initialization orchestrator
13
+ - mpm_init_cli.py: Click command definitions and CLI entry points
14
+ - prompts.py: Prompt building functions for agent delegation
15
+ - display.py: Display and UI helper functions
16
+ - git_activity.py: Git history analysis and context building
17
+ - modes.py: Mode-specific handlers (review, dry-run, quick-update, etc.)
18
+
19
+ Public API:
20
+ - MPMInitCommand: Main command class (from core)
21
+ - mpm_init: Click command group (from mpm_init_cli)
22
+
23
+ Example Usage:
24
+ # Programmatic usage
25
+ from claude_mpm.cli.commands.mpm_init import MPMInitCommand
26
+ command = MPMInitCommand(project_path)
27
+ result = command.initialize_project()
28
+
29
+ # CLI usage (via Click)
30
+ from claude_mpm.cli.commands.mpm_init import mpm_init
31
+ # Command is registered with Click and invoked via CLI
32
+ """
33
+
34
+ # Import core components for re-export
35
+ from .core import MPMInitCommand
36
+
37
+ # Import the Click command group - this must be imported from parent level
38
+ # to avoid circular dependencies, as mpm_init_cli imports from core
39
+ # We'll handle this via late import in __all__
40
+
41
+ __all__ = [
42
+ # Main command class
43
+ "MPMInitCommand",
44
+ "core",
45
+ # Internal modules (for internal package use)
46
+ "display",
47
+ "git_activity",
48
+ "modes",
49
+ # Click CLI command (imported via __getattr__ to avoid circular import)
50
+ "mpm_init",
51
+ "prompts",
52
+ ]
53
+
54
+
55
+ def __getattr__(name):
56
+ """Lazy import to avoid circular dependencies.
57
+
58
+ This allows importing mpm_init Click command without importing
59
+ mpm_init_cli at module load time, which would cause circular imports.
60
+ """
61
+ if name == "mpm_init":
62
+ # Lazy import the Click command group
63
+ from ..mpm_init_cli import mpm_init as _mpm_init
64
+
65
+ return _mpm_init
66
+
67
+ # For internal module imports, import them directly
68
+ if name in ("display", "git_activity", "prompts", "modes", "core"):
69
+ import importlib
70
+
71
+ return importlib.import_module(f".{name}", __package__)
72
+
73
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,525 @@
1
+ """Core MPMInitCommand class for project initialization.
2
+
3
+ This module contains the main command class responsible for orchestrating
4
+ the MPM project initialization process, including configuration generation,
5
+ agent delegation, and workflow management.
6
+ """
7
+
8
+ import contextlib
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ from rich.console import Console
15
+ from rich.progress import Progress, SpinnerColumn, TextColumn
16
+
17
+ from claude_mpm.core.enums import OperationResult
18
+ from claude_mpm.core.logging_utils import get_logger
19
+ from claude_mpm.services.project.archive_manager import ArchiveManager
20
+ from claude_mpm.services.project.documentation_manager import DocumentationManager
21
+ from claude_mpm.services.project.enhanced_analyzer import EnhancedProjectAnalyzer
22
+ from claude_mpm.services.project.project_organizer import ProjectOrganizer
23
+ from claude_mpm.utils.display_helper import DisplayHelper
24
+
25
+ # Import from sibling modules in the mpm_init package
26
+ from . import display, git_activity, modes, prompts
27
+
28
+ logger = get_logger(__name__)
29
+
30
+
31
+ class MPMInitCommand:
32
+ """Initialize projects for optimal Claude Code and Claude MPM usage."""
33
+
34
+ def __init__(self, project_path: Optional[Path] = None):
35
+ """Initialize the MPM-Init command."""
36
+ self.project_path = project_path or Path.cwd()
37
+ self.claude_mpm_script = self._find_claude_mpm_script()
38
+ self.console = Console()
39
+
40
+ # Initialize service components
41
+ self.doc_manager = DocumentationManager(self.project_path)
42
+ self.organizer = ProjectOrganizer(self.project_path)
43
+ self.archive_manager = ArchiveManager(self.project_path)
44
+ self.analyzer = EnhancedProjectAnalyzer(self.project_path)
45
+ self.display = DisplayHelper(self.console)
46
+
47
+ def initialize_project(
48
+ self,
49
+ project_type: Optional[str] = None,
50
+ framework: Optional[str] = None,
51
+ force: bool = False,
52
+ verbose: bool = False,
53
+ ast_analysis: bool = True,
54
+ update_mode: bool = False,
55
+ review_only: bool = False,
56
+ organize_files: bool = False,
57
+ preserve_custom: bool = True,
58
+ skip_archive: bool = False,
59
+ dry_run: bool = False,
60
+ quick_update: bool = False,
61
+ catchup: bool = False,
62
+ non_interactive: bool = False,
63
+ days: int = 30,
64
+ export: Optional[str] = None,
65
+ ) -> Dict:
66
+ """
67
+ Initialize project with Agentic Coder Optimizer standards.
68
+
69
+ Args:
70
+ project_type: Type of project (web, api, cli, library, etc.)
71
+ framework: Specific framework if applicable
72
+ force: Force initialization even if project already configured
73
+ verbose: Show detailed output
74
+ ast_analysis: Enable AST analysis for enhanced documentation
75
+ update_mode: Update existing CLAUDE.md instead of recreating
76
+ review_only: Review project state without making changes
77
+ organize_files: Organize misplaced files into proper directories
78
+ preserve_custom: Preserve custom sections when updating
79
+ skip_archive: Skip archiving existing files
80
+ dry_run: Show what would be done without making changes
81
+ quick_update: Perform lightweight update based on recent git activity
82
+ catchup: Show recent commit history from all branches for PM context
83
+ non_interactive: Non-interactive mode - display report only without prompting
84
+ days: Number of days for git history analysis (7, 14, 30, 60, or 90)
85
+ export: Export report to file (path or "auto" for default location)
86
+
87
+ Returns:
88
+ Dict containing initialization results
89
+ """
90
+ try:
91
+ # Determine initialization mode
92
+ claude_md = self.project_path / "CLAUDE.md"
93
+ has_existing = claude_md.exists()
94
+
95
+ if review_only:
96
+ return self._run_review_mode()
97
+
98
+ if catchup:
99
+ data = self._catchup()
100
+ self._display_catchup(data)
101
+ return {
102
+ "status": OperationResult.SUCCESS,
103
+ "mode": "catchup",
104
+ "catchup_data": data,
105
+ }
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
+ self.console.print(
119
+ "[cyan]Auto-selecting update mode for organization tasks.[/cyan]\n"
120
+ )
121
+ else:
122
+ # Offer update mode
123
+ self.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": OperationResult.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") == OperationResult.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=self.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") == OperationResult.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
+ self.console.print(f"[red]❌ Error: {e}[/red]")
206
+ return {"status": OperationResult.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_claude_mpm_command(self, verbose: bool) -> List[str]:
219
+ """Build the claude-mpm run command with appropriate arguments."""
220
+ cmd = [str(self.claude_mpm_script)]
221
+
222
+ # Add top-level flags that go before 'run' subcommand
223
+ cmd.append("--no-check-dependencies")
224
+
225
+ # Now add the run subcommand
226
+ cmd.append("run")
227
+
228
+ # Add non-interactive mode
229
+ # We'll pass the prompt via stdin instead of -i flag
230
+ cmd.append("--non-interactive")
231
+
232
+ # Add verbose flag if requested (run subcommand argument)
233
+ if verbose:
234
+ cmd.append("--verbose")
235
+
236
+ return cmd
237
+
238
+ def _run_initialization(
239
+ self,
240
+ prompt: str,
241
+ verbose: bool,
242
+ update_mode: bool = False,
243
+ ) -> Dict:
244
+ """Run the initialization through subprocess calling claude-mpm."""
245
+ try:
246
+ # Write prompt to temporary file
247
+ with tempfile.NamedTemporaryFile(
248
+ mode="w", suffix=".txt", delete=False
249
+ ) as tmp_file:
250
+ tmp_file.write(prompt)
251
+ prompt_file = tmp_file.name
252
+
253
+ try:
254
+ # Build the command
255
+ cmd = self._build_claude_mpm_command(verbose)
256
+ # Add the input file flag
257
+ cmd.extend(["-i", prompt_file])
258
+
259
+ # Log the command if verbose
260
+ if verbose:
261
+ self.console.print(f"[dim]Running: {' '.join(cmd)}[/dim]")
262
+ self.console.print(f"[dim]Prompt file: {prompt_file}[/dim]")
263
+
264
+ # Execute the command
265
+ result = subprocess.run(
266
+ cmd,
267
+ capture_output=True,
268
+ text=True,
269
+ cwd=str(self.project_path),
270
+ check=False,
271
+ )
272
+ finally:
273
+ # Clean up temporary file
274
+ with contextlib.suppress(Exception):
275
+ Path(prompt_file).unlink()
276
+
277
+ # Display output if verbose
278
+ if verbose and result.stdout:
279
+ self.console.print(result.stdout)
280
+ if verbose and result.stderr:
281
+ self.console.print(f"[yellow]{result.stderr}[/yellow]")
282
+
283
+ # Check result - be more lenient with return codes
284
+ if result.returncode == 0 or (self.project_path / "CLAUDE.md").exists():
285
+ response = {
286
+ "status": OperationResult.SUCCESS,
287
+ "message": "Project initialized successfully",
288
+ "files_created": [],
289
+ "files_updated": [],
290
+ "next_steps": [],
291
+ }
292
+
293
+ # Check if CLAUDE.md was created
294
+ claude_md = self.project_path / "CLAUDE.md"
295
+ if claude_md.exists():
296
+ response["files_created"].append("CLAUDE.md")
297
+
298
+ # Check for other common files
299
+ for file_name in ["CODE.md", "DEVELOPER.md", "STRUCTURE.md", "OPS.md"]:
300
+ file_path = self.project_path / file_name
301
+ if file_path.exists():
302
+ response["files_created"].append(file_name)
303
+
304
+ # Add next steps
305
+ response["next_steps"] = [
306
+ "Review the generated CLAUDE.md documentation",
307
+ "Verify the project structure meets your needs",
308
+ "Run 'claude-mpm run' to start using the optimized setup",
309
+ ]
310
+
311
+ # Display results
312
+ self._display_results(response, verbose)
313
+
314
+ return response
315
+
316
+ # Extract meaningful error message
317
+ error_msg = (
318
+ result.stderr
319
+ if result.stderr
320
+ else result.stdout if result.stdout else "Unknown error occurred"
321
+ )
322
+
323
+ logger.error(f"claude-mpm run failed: {error_msg}")
324
+ return {
325
+ "status": OperationResult.ERROR,
326
+ "message": f"Initialization failed: {error_msg}",
327
+ }
328
+
329
+ except FileNotFoundError:
330
+ logger.error("claude-mpm command not found")
331
+ self.console.print(
332
+ "[red]Error: claude-mpm command not found. Ensure Claude MPM is properly installed.[/red]"
333
+ )
334
+ return {"status": OperationResult.ERROR, "message": "claude-mpm not found"}
335
+ except Exception as e:
336
+ logger.error(f"Initialization failed: {e}")
337
+ return {"status": OperationResult.ERROR, "message": str(e)}
338
+
339
+ def _run_pre_initialization_checks(
340
+ self, organize_files: bool, skip_archive: bool, has_existing: bool
341
+ ) -> Dict:
342
+ """Run pre-initialization checks and preparations."""
343
+ checks_passed = []
344
+ warnings = []
345
+
346
+ # Run comprehensive project readiness check
347
+ ready, actions = self.organizer.ensure_project_ready(
348
+ auto_organize=organize_files,
349
+ safe_mode=True, # Only perform safe operations by default
350
+ )
351
+
352
+ if actions:
353
+ checks_passed.extend(actions)
354
+
355
+ # Get structure validation report
356
+ validation = self.organizer.validate_structure()
357
+ if validation["warnings"]:
358
+ warnings.extend(validation["warnings"])
359
+ if validation["errors"]:
360
+ warnings.extend(validation["errors"])
361
+
362
+ # Show structure grade
363
+ if validation.get("grade"):
364
+ checks_passed.append(f"Structure validation: {validation['grade']}")
365
+
366
+ # Archive existing documentation if needed
367
+ if has_existing and not skip_archive:
368
+ if self.archive_manager.auto_archive_before_update(
369
+ self.project_path / "CLAUDE.md", update_reason="Before mpm-init update"
370
+ ):
371
+ checks_passed.append("Archived existing CLAUDE.md")
372
+
373
+ # Check for issues in validation report
374
+ if validation.get("issues"):
375
+ for issue in validation["issues"]:
376
+ warnings.append(issue["description"])
377
+
378
+ if warnings:
379
+ self.console.print("\n[yellow]⚠️ Project issues detected:[/yellow]")
380
+ for warning in warnings[:5]:
381
+ self.console.print(f" • {warning}")
382
+ self.console.print()
383
+
384
+ if checks_passed:
385
+ self.console.print("[green]✅ Pre-initialization checks:[/green]")
386
+ for check in checks_passed:
387
+ self.console.print(f" • {check}")
388
+ self.console.print()
389
+
390
+ return {
391
+ "status": OperationResult.SUCCESS,
392
+ "checks_passed": checks_passed,
393
+ "warnings": warnings,
394
+ }
395
+
396
+ def _build_initialization_prompt(
397
+ self,
398
+ project_type: Optional[str] = None,
399
+ framework: Optional[str] = None,
400
+ ast_analysis: bool = True,
401
+ ) -> str:
402
+ """Build the initialization prompt for the agent."""
403
+ return prompts.build_initialization_prompt(
404
+ self.project_path, project_type, framework, ast_analysis
405
+ )
406
+
407
+ def _build_update_prompt(
408
+ self,
409
+ project_type: Optional[str],
410
+ framework: Optional[str],
411
+ ast_analysis: bool,
412
+ preserve_custom: bool,
413
+ ) -> str:
414
+ """Build prompt for update mode."""
415
+ # Get existing content analysis
416
+ doc_analysis = self.doc_manager.analyze_existing_content()
417
+
418
+ return prompts.build_update_prompt(
419
+ self.project_path,
420
+ doc_analysis,
421
+ project_type,
422
+ framework,
423
+ ast_analysis,
424
+ preserve_custom,
425
+ )
426
+
427
+ def _display_documentation_status(self, analysis: Dict) -> None:
428
+ """Display current documentation status."""
429
+ display.display_documentation_status(self.display, analysis)
430
+
431
+ def _prompt_update_action(self) -> str:
432
+ """Prompt user for update action."""
433
+ return modes.prompt_update_action(self.console)
434
+
435
+ def _run_review_mode(self) -> Dict:
436
+ """Run review mode to analyze project without changes."""
437
+ return modes.run_review_mode(
438
+ self.console,
439
+ self.display,
440
+ self.organizer,
441
+ self.doc_manager,
442
+ self.analyzer,
443
+ )
444
+
445
+ def _run_quick_update_mode(
446
+ self,
447
+ days: int = 30,
448
+ non_interactive: bool = False,
449
+ export: Optional[str] = None,
450
+ ) -> Dict:
451
+ """Run quick update mode - lightweight update based on recent git activity."""
452
+ return modes.run_quick_update_mode(
453
+ self.console,
454
+ self.display,
455
+ self.project_path,
456
+ self.analyzer,
457
+ self.doc_manager,
458
+ self.archive_manager,
459
+ days=days,
460
+ non_interactive=non_interactive,
461
+ export=export,
462
+ )
463
+
464
+ def _catchup(self) -> Dict[str, Any]:
465
+ """Get recent commit history for PM context."""
466
+ return git_activity.catchup(self.project_path)
467
+
468
+ def _display_catchup(self, data: Dict[str, Any]) -> None:
469
+ """Display catchup information to console.
470
+
471
+ Args:
472
+ data: Commit history data from _catchup()
473
+ """
474
+ display.display_catchup(self.display, self.console, data)
475
+
476
+ def _run_dry_run_mode(self, organize_files: bool, has_existing: bool) -> Dict:
477
+ """Run dry-run mode to show what would be done without making changes."""
478
+ return modes.run_dry_run_mode(
479
+ self.console,
480
+ self.organizer,
481
+ self.doc_manager,
482
+ organize_files,
483
+ has_existing,
484
+ )
485
+
486
+ def _show_update_plan(self, ast_analysis: bool, preserve_custom: bool) -> None:
487
+ """Show update mode plan."""
488
+ display.show_update_plan(self.console, ast_analysis, preserve_custom)
489
+
490
+ def _show_initialization_plan(self, ast_analysis: bool) -> None:
491
+ """Show standard initialization plan."""
492
+ display.show_initialization_plan(self.console, ast_analysis)
493
+
494
+ def _handle_update_post_processing(self) -> None:
495
+ """Handle post-processing after successful update."""
496
+ modes.handle_update_post_processing(
497
+ self.console,
498
+ self.project_path,
499
+ self.doc_manager,
500
+ self.archive_manager,
501
+ )
502
+
503
+ def _display_results(self, result: Dict, verbose: bool):
504
+ """Display initialization results."""
505
+ display.display_results(self.display, self.console, result, verbose)
506
+
507
+ def handle_context(
508
+ self,
509
+ session_id: Optional[str] = None,
510
+ list_sessions: bool = False,
511
+ days: int = 7,
512
+ ) -> Dict[str, Any]:
513
+ """Provide intelligent context for resuming work based on git history."""
514
+ return git_activity.handle_context(
515
+ self.project_path, session_id, list_sessions, days
516
+ )
517
+
518
+ def _build_research_context_prompt(
519
+ self, git_analysis: Dict[str, Any], days: int
520
+ ) -> str:
521
+ """Build structured Research agent delegation prompt from git analysis."""
522
+ return prompts.build_research_context_prompt(git_analysis, days)
523
+
524
+
525
+ __all__ = ["MPMInitCommand"]