claude-mpm 4.3.20__py3-none-any.whl → 4.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. claude_mpm/VERSION +1 -1
  2. claude_mpm/agents/agent_loader.py +2 -2
  3. claude_mpm/agents/agent_loader_integration.py +2 -2
  4. claude_mpm/agents/async_agent_loader.py +2 -2
  5. claude_mpm/agents/base_agent_loader.py +2 -2
  6. claude_mpm/agents/frontmatter_validator.py +2 -2
  7. claude_mpm/agents/system_agent_config.py +2 -2
  8. claude_mpm/agents/templates/data_engineer.json +1 -2
  9. claude_mpm/cli/commands/doctor.py +2 -2
  10. claude_mpm/cli/commands/mpm_init.py +560 -47
  11. claude_mpm/cli/commands/mpm_init_handler.py +6 -0
  12. claude_mpm/cli/parsers/mpm_init_parser.py +39 -1
  13. claude_mpm/cli/startup_logging.py +11 -9
  14. claude_mpm/commands/mpm-init.md +76 -12
  15. claude_mpm/config/agent_config.py +2 -2
  16. claude_mpm/config/paths.py +2 -2
  17. claude_mpm/core/agent_name_normalizer.py +2 -2
  18. claude_mpm/core/config.py +2 -1
  19. claude_mpm/core/config_aliases.py +2 -2
  20. claude_mpm/core/file_utils.py +1 -0
  21. claude_mpm/core/log_manager.py +2 -2
  22. claude_mpm/core/tool_access_control.py +2 -2
  23. claude_mpm/core/unified_agent_registry.py +2 -2
  24. claude_mpm/core/unified_paths.py +2 -2
  25. claude_mpm/experimental/cli_enhancements.py +3 -2
  26. claude_mpm/hooks/base_hook.py +2 -2
  27. claude_mpm/hooks/instruction_reinforcement.py +2 -2
  28. claude_mpm/hooks/memory_integration_hook.py +1 -1
  29. claude_mpm/hooks/validation_hooks.py +2 -2
  30. claude_mpm/scripts/mpm_doctor.py +2 -2
  31. claude_mpm/services/agents/loading/agent_profile_loader.py +2 -2
  32. claude_mpm/services/agents/loading/base_agent_manager.py +2 -2
  33. claude_mpm/services/agents/loading/framework_agent_loader.py +2 -2
  34. claude_mpm/services/agents/management/agent_capabilities_generator.py +2 -2
  35. claude_mpm/services/agents/management/agent_management_service.py +2 -2
  36. claude_mpm/services/agents/memory/content_manager.py +5 -2
  37. claude_mpm/services/agents/memory/memory_categorization_service.py +5 -2
  38. claude_mpm/services/agents/memory/memory_file_service.py +28 -6
  39. claude_mpm/services/agents/memory/memory_format_service.py +5 -2
  40. claude_mpm/services/agents/memory/memory_limits_service.py +4 -2
  41. claude_mpm/services/agents/registry/deployed_agent_discovery.py +2 -2
  42. claude_mpm/services/agents/registry/modification_tracker.py +4 -4
  43. claude_mpm/services/async_session_logger.py +2 -1
  44. claude_mpm/services/claude_session_logger.py +2 -2
  45. claude_mpm/services/core/path_resolver.py +3 -2
  46. claude_mpm/services/diagnostics/diagnostic_runner.py +4 -3
  47. claude_mpm/services/event_bus/direct_relay.py +2 -1
  48. claude_mpm/services/event_bus/event_bus.py +2 -1
  49. claude_mpm/services/event_bus/relay.py +2 -2
  50. claude_mpm/services/framework_claude_md_generator/content_assembler.py +2 -2
  51. claude_mpm/services/infrastructure/daemon_manager.py +2 -2
  52. claude_mpm/services/memory/cache/simple_cache.py +2 -2
  53. claude_mpm/services/project/archive_manager.py +981 -0
  54. claude_mpm/services/project/documentation_manager.py +536 -0
  55. claude_mpm/services/project/enhanced_analyzer.py +491 -0
  56. claude_mpm/services/project/project_organizer.py +904 -0
  57. claude_mpm/services/response_tracker.py +2 -2
  58. claude_mpm/services/socketio/handlers/connection.py +14 -33
  59. claude_mpm/services/socketio/server/eventbus_integration.py +2 -2
  60. claude_mpm/services/unified/__init__.py +65 -0
  61. claude_mpm/services/unified/analyzer_strategies/__init__.py +44 -0
  62. claude_mpm/services/unified/analyzer_strategies/code_analyzer.py +473 -0
  63. claude_mpm/services/unified/analyzer_strategies/dependency_analyzer.py +643 -0
  64. claude_mpm/services/unified/analyzer_strategies/performance_analyzer.py +804 -0
  65. claude_mpm/services/unified/analyzer_strategies/security_analyzer.py +661 -0
  66. claude_mpm/services/unified/analyzer_strategies/structure_analyzer.py +696 -0
  67. claude_mpm/services/unified/deployment_strategies/__init__.py +97 -0
  68. claude_mpm/services/unified/deployment_strategies/base.py +557 -0
  69. claude_mpm/services/unified/deployment_strategies/cloud_strategies.py +486 -0
  70. claude_mpm/services/unified/deployment_strategies/local.py +594 -0
  71. claude_mpm/services/unified/deployment_strategies/utils.py +672 -0
  72. claude_mpm/services/unified/deployment_strategies/vercel.py +471 -0
  73. claude_mpm/services/unified/interfaces.py +499 -0
  74. claude_mpm/services/unified/migration.py +532 -0
  75. claude_mpm/services/unified/strategies.py +551 -0
  76. claude_mpm/services/unified/unified_analyzer.py +534 -0
  77. claude_mpm/services/unified/unified_config.py +688 -0
  78. claude_mpm/services/unified/unified_deployment.py +470 -0
  79. claude_mpm/services/version_control/version_parser.py +5 -4
  80. claude_mpm/storage/state_storage.py +2 -2
  81. claude_mpm/utils/agent_dependency_loader.py +49 -0
  82. claude_mpm/utils/common.py +542 -0
  83. claude_mpm/utils/database_connector.py +298 -0
  84. claude_mpm/utils/error_handler.py +2 -1
  85. claude_mpm/utils/log_cleanup.py +2 -2
  86. claude_mpm/utils/path_operations.py +2 -2
  87. claude_mpm/utils/robust_installer.py +56 -0
  88. claude_mpm/utils/session_logging.py +2 -2
  89. claude_mpm/utils/subprocess_utils.py +2 -2
  90. claude_mpm/validation/agent_validator.py +2 -2
  91. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/METADATA +1 -1
  92. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/RECORD +96 -71
  93. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/WHEEL +0 -0
  94. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/entry_points.txt +0 -0
  95. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/licenses/LICENSE +0 -0
  96. {claude_mpm-4.3.20.dist-info → claude_mpm-4.4.0.dist-info}/top_level.txt +0 -0
@@ -9,7 +9,6 @@ documentation with code structure analysis.
9
9
  """
10
10
 
11
11
  import contextlib
12
- import logging
13
12
  import subprocess
14
13
  import sys
15
14
  from pathlib import Path
@@ -19,8 +18,17 @@ import click
19
18
  from rich.console import Console
20
19
  from rich.panel import Panel
21
20
  from rich.progress import Progress, SpinnerColumn, TextColumn
21
+ from rich.prompt import Confirm, Prompt
22
+ from rich.table import Table
22
23
 
23
- logger = logging.getLogger(__name__)
24
+ # Import new services
25
+ from claude_mpm.services.project.archive_manager import ArchiveManager
26
+ from claude_mpm.services.project.documentation_manager import DocumentationManager
27
+ from claude_mpm.services.project.enhanced_analyzer import EnhancedProjectAnalyzer
28
+ from claude_mpm.services.project.project_organizer import ProjectOrganizer
29
+
30
+ from claude_mpm.core.logging_utils import get_logger
31
+ logger = get_logger(__name__)
24
32
  console = Console()
25
33
 
26
34
 
@@ -32,6 +40,12 @@ class MPMInitCommand:
32
40
  self.project_path = project_path or Path.cwd()
33
41
  self.claude_mpm_script = self._find_claude_mpm_script()
34
42
 
43
+ # Initialize service components
44
+ self.doc_manager = DocumentationManager(self.project_path)
45
+ self.organizer = ProjectOrganizer(self.project_path)
46
+ self.archive_manager = ArchiveManager(self.project_path)
47
+ self.analyzer = EnhancedProjectAnalyzer(self.project_path)
48
+
35
49
  def initialize_project(
36
50
  self,
37
51
  project_type: Optional[str] = None,
@@ -40,6 +54,12 @@ class MPMInitCommand:
40
54
  verbose: bool = False,
41
55
  use_venv: bool = False,
42
56
  ast_analysis: bool = True,
57
+ update_mode: bool = False,
58
+ review_only: bool = False,
59
+ organize_files: bool = False,
60
+ preserve_custom: bool = True,
61
+ skip_archive: bool = False,
62
+ dry_run: bool = False,
43
63
  ) -> Dict:
44
64
  """
45
65
  Initialize project with Agentic Coder Optimizer standards.
@@ -51,48 +71,76 @@ class MPMInitCommand:
51
71
  verbose: Show detailed output
52
72
  use_venv: Force use of venv instead of mamba
53
73
  ast_analysis: Enable AST analysis for enhanced documentation
74
+ update_mode: Update existing CLAUDE.md instead of recreating
75
+ review_only: Review project state without making changes
76
+ organize_files: Organize misplaced files into proper directories
77
+ preserve_custom: Preserve custom sections when updating
78
+ skip_archive: Skip archiving existing files
79
+ dry_run: Show what would be done without making changes
54
80
 
55
81
  Returns:
56
82
  Dict containing initialization results
57
83
  """
58
84
  try:
59
- # Check if project already initialized
85
+ # Determine initialization mode
60
86
  claude_md = self.project_path / "CLAUDE.md"
61
- if claude_md.exists() and not force:
62
- console.print("[yellow]⚠️ Project already has CLAUDE.md file.[/yellow]")
63
- console.print(
64
- "[yellow]Use --force to reinitialize the project.[/yellow]"
87
+ has_existing = claude_md.exists()
88
+
89
+ if review_only:
90
+ return self._run_review_mode()
91
+
92
+ if has_existing and not force and not update_mode:
93
+ # Auto-select update mode if organize_files or dry_run is specified
94
+ if organize_files or dry_run:
95
+ update_mode = True
96
+ console.print("[cyan]Auto-selecting update mode for organization tasks.[/cyan]\n")
97
+ else:
98
+ # Offer update mode
99
+ console.print("[yellow]⚠️ Project already has CLAUDE.md file.[/yellow]\n")
100
+
101
+ # Show current documentation analysis
102
+ doc_analysis = self.doc_manager.analyze_existing_content()
103
+ self._display_documentation_status(doc_analysis)
104
+
105
+ # Ask user what to do
106
+ action = self._prompt_update_action()
107
+
108
+ if action == "update":
109
+ update_mode = True
110
+ elif action == "recreate":
111
+ force = True
112
+ elif action == "review":
113
+ return self._run_review_mode()
114
+ else:
115
+ return {"status": "cancelled", "message": "Initialization cancelled"}
116
+
117
+ # Handle dry-run mode
118
+ if dry_run:
119
+ return self._run_dry_run_mode(organize_files, has_existing)
120
+
121
+ # Run pre-initialization checks
122
+ if not review_only:
123
+ pre_check_result = self._run_pre_initialization_checks(
124
+ organize_files, skip_archive, has_existing
65
125
  )
66
- return {"status": "cancelled", "message": "Initialization cancelled"}
126
+ if pre_check_result.get("status") == "error":
127
+ return pre_check_result
67
128
 
68
129
  # Build the delegation prompt
69
- prompt = self._build_initialization_prompt(
70
- project_type, framework, ast_analysis
71
- )
72
-
73
- # Show initialization plan
74
- console.print(
75
- Panel(
76
- "[bold cyan]🤖👥 Claude MPM Project Initialization[/bold cyan]\n\n"
77
- "This will set up your project with:\n"
78
- "• Clear CLAUDE.md documentation for AI agents\n"
79
- "• Single-path workflows (ONE way to do ANYTHING)\n"
80
- "• Optimized project structure\n"
81
- "• Tool configurations (linting, formatting, testing)\n"
82
- "• GitHub workflows and CI/CD setup\n"
83
- "• Memory system initialization\n"
84
- + (
85
- "• AST analysis for comprehensive code documentation\n"
86
- if ast_analysis
87
- else ""
88
- )
89
- + "• Holistic CLAUDE.md organization with ranked instructions\n"
90
- + "• Priority-based content structure (🔴🟡🟢⚪)\n"
91
- + "\n[dim]Powered by Agentic Coder Optimizer Agent[/dim]",
92
- title="MPM-Init",
93
- border_style="cyan",
130
+ if update_mode:
131
+ prompt = self._build_update_prompt(
132
+ project_type, framework, ast_analysis, preserve_custom
94
133
  )
95
- )
134
+ else:
135
+ prompt = self._build_initialization_prompt(
136
+ project_type, framework, ast_analysis
137
+ )
138
+
139
+ # Show appropriate plan based on mode
140
+ if update_mode:
141
+ self._show_update_plan(ast_analysis, preserve_custom)
142
+ else:
143
+ self._show_initialization_plan(ast_analysis)
96
144
 
97
145
  # Execute via claude-mpm run command
98
146
  with Progress(
@@ -100,14 +148,26 @@ class MPMInitCommand:
100
148
  TextColumn("[progress.description]{task.description}"),
101
149
  console=console,
102
150
  ) as progress:
103
- task = progress.add_task(
104
- "[cyan]Delegating to Agentic Coder Optimizer...", total=None
151
+ task_desc = (
152
+ "[cyan]Updating documentation..."
153
+ if update_mode
154
+ else "[cyan]Delegating to Agentic Coder Optimizer..."
105
155
  )
156
+ task = progress.add_task(task_desc, total=None)
106
157
 
107
158
  # Run the initialization through subprocess
108
- result = self._run_initialization(prompt, verbose, use_venv)
159
+ result = self._run_initialization(prompt, verbose, use_venv, update_mode)
160
+
161
+ complete_desc = (
162
+ "[green]✓ Update complete"
163
+ if update_mode
164
+ else "[green]✓ Initialization complete"
165
+ )
166
+ progress.update(task, description=complete_desc)
109
167
 
110
- progress.update(task, description="[green]✓ Initialization complete")
168
+ # Post-processing for update mode
169
+ if update_mode and result.get("status") == "success":
170
+ self._handle_update_post_processing()
111
171
 
112
172
  return result
113
173
 
@@ -339,8 +399,408 @@ The final CLAUDE.md should be a comprehensive, well-organized guide that any AI
339
399
 
340
400
  return cmd
341
401
 
402
+ def _display_documentation_status(self, analysis: Dict) -> None:
403
+ """Display current documentation status."""
404
+ table = Table(title="Current CLAUDE.md Status", show_header=True)
405
+ table.add_column("Property", style="cyan")
406
+ table.add_column("Value", style="white")
407
+
408
+ table.add_row("Size", f"{analysis.get('size', 0):,} characters")
409
+ table.add_row("Lines", str(analysis.get('lines', 0)))
410
+ table.add_row("Sections", str(len(analysis.get('sections', []))))
411
+ table.add_row("Has Priority Index", "✓" if analysis.get('has_priority_index') else "✗")
412
+ table.add_row("Has Priority Markers", "✓" if analysis.get('has_priority_markers') else "✗")
413
+
414
+ if analysis.get('last_modified'):
415
+ table.add_row("Last Modified", analysis['last_modified'])
416
+
417
+ console.print(table)
418
+
419
+ if analysis.get('outdated_patterns'):
420
+ console.print("\n[yellow]⚠️ Outdated patterns detected:[/yellow]")
421
+ for pattern in analysis['outdated_patterns']:
422
+ console.print(f" • {pattern}")
423
+
424
+ if analysis.get('custom_sections'):
425
+ console.print("\n[blue]ℹ️ Custom sections found:[/blue]")
426
+ for section in analysis['custom_sections'][:5]:
427
+ console.print(f" • {section}")
428
+
429
+ def _prompt_update_action(self) -> str:
430
+ """Prompt user for update action."""
431
+ console.print("\n[bold]How would you like to proceed?[/bold]\n")
432
+
433
+ choices = {
434
+ "1": ("update", "Update existing CLAUDE.md (preserves custom content)"),
435
+ "2": ("recreate", "Recreate CLAUDE.md from scratch"),
436
+ "3": ("review", "Review project state without changes"),
437
+ "4": ("cancel", "Cancel operation"),
438
+ }
439
+
440
+ for key, (_, desc) in choices.items():
441
+ console.print(f" [{key}] {desc}")
442
+
443
+ choice = Prompt.ask("\nSelect option", choices=list(choices.keys()), default="1")
444
+ return choices[choice][0]
445
+
446
+ def _run_review_mode(self) -> Dict:
447
+ """Run review mode to analyze project without changes."""
448
+ console.print("\n[bold cyan]🔍 Project Review Mode[/bold cyan]\n")
449
+
450
+ with Progress(
451
+ SpinnerColumn(),
452
+ TextColumn("[progress.description]{task.description}"),
453
+ console=console,
454
+ ) as progress:
455
+ # Analyze project structure
456
+ task = progress.add_task("[cyan]Analyzing project structure...", total=None)
457
+ structure_report = self.organizer.verify_structure()
458
+ progress.update(task, description="[green]✓ Structure analysis complete")
459
+
460
+ # Analyze documentation
461
+ task = progress.add_task("[cyan]Analyzing documentation...", total=None)
462
+ doc_analysis = self.doc_manager.analyze_existing_content()
463
+ progress.update(task, description="[green]✓ Documentation analysis complete")
464
+
465
+ # Analyze git history
466
+ if self.analyzer.is_git_repo:
467
+ task = progress.add_task("[cyan]Analyzing git history...", total=None)
468
+ git_analysis = self.analyzer.analyze_git_history()
469
+ progress.update(task, description="[green]✓ Git analysis complete")
470
+ else:
471
+ git_analysis = None
472
+
473
+ # Detect project state
474
+ task = progress.add_task("[cyan]Detecting project state...", total=None)
475
+ project_state = self.analyzer.detect_project_state()
476
+ progress.update(task, description="[green]✓ State detection complete")
477
+
478
+ # Display comprehensive report
479
+ self._display_review_report(structure_report, doc_analysis, git_analysis, project_state)
480
+
481
+ return {
482
+ "status": "success",
483
+ "mode": "review",
484
+ "structure_report": structure_report,
485
+ "documentation_analysis": doc_analysis,
486
+ "git_analysis": git_analysis,
487
+ "project_state": project_state,
488
+ }
489
+
490
+ def _display_review_report(
491
+ self, structure: Dict, docs: Dict, git: Optional[Dict], state: Dict
492
+ ) -> None:
493
+ """Display comprehensive review report."""
494
+ console.print("\n" + "=" * 60)
495
+ console.print("[bold]PROJECT REVIEW REPORT[/bold]")
496
+ console.print("=" * 60 + "\n")
497
+
498
+ # Project State
499
+ console.print("[bold cyan]📊 Project State[/bold cyan]")
500
+ console.print(f" Phase: {state.get('phase', 'unknown')}")
501
+ if state.get('indicators'):
502
+ console.print(" Indicators:")
503
+ for indicator in state['indicators'][:5]:
504
+ console.print(f" • {indicator}")
505
+
506
+ # Structure Report
507
+ console.print("\n[bold cyan]📁 Project Structure[/bold cyan]")
508
+ console.print(f" Existing directories: {len(structure.get('exists', []))}")
509
+ console.print(f" Missing directories: {len(structure.get('missing', []))}")
510
+ if structure.get('issues'):
511
+ console.print(f" Issues found: {len(structure['issues'])}")
512
+ for issue in structure['issues'][:3]:
513
+ console.print(f" ⚠️ {issue['description']}")
514
+
515
+ # Documentation Report
516
+ console.print("\n[bold cyan]📚 Documentation Status[/bold cyan]")
517
+ if docs.get('exists'):
518
+ console.print(f" CLAUDE.md: Found ({docs.get('size', 0):,} chars)")
519
+ console.print(f" Sections: {len(docs.get('sections', []))}")
520
+ console.print(f" Priority markers: {'Yes' if docs.get('has_priority_markers') else 'No'}")
521
+ else:
522
+ console.print(" CLAUDE.md: Not found")
523
+
524
+ # Git Analysis
525
+ if git and git.get('git_available'):
526
+ console.print("\n[bold cyan]📈 Recent Activity (30 days)[/bold cyan]")
527
+ console.print(f" Commits: {len(git.get('recent_commits', []))}")
528
+ console.print(f" Authors: {git.get('authors', {}).get('total_authors', 0)}")
529
+ console.print(f" Changed files: {git.get('changed_files', {}).get('total_files', 0)}")
530
+
531
+ if git.get('branch_info'):
532
+ branch_info = git['branch_info']
533
+ console.print(f" Current branch: {branch_info.get('current_branch', 'unknown')}")
534
+ if branch_info.get('has_uncommitted_changes'):
535
+ console.print(f" ⚠️ Uncommitted changes: {branch_info.get('uncommitted_files', 0)} files")
536
+
537
+ # Recommendations
538
+ if state.get('recommendations'):
539
+ console.print("\n[bold cyan]💡 Recommendations[/bold cyan]")
540
+ for rec in state['recommendations'][:5]:
541
+ console.print(f" → {rec}")
542
+
543
+ console.print("\n" + "=" * 60 + "\n")
544
+
545
+ def _run_dry_run_mode(self, organize_files: bool, has_existing: bool) -> Dict:
546
+ """Run dry-run mode to show what would be done without making changes."""
547
+ console.print("\n[bold cyan]🔍 Dry Run Mode - Preview Changes[/bold cyan]\n")
548
+
549
+ actions_planned = []
550
+
551
+ # Check what organization would do
552
+ if organize_files:
553
+ console.print("[bold]📁 File Organization Analysis:[/bold]")
554
+
555
+ # Get structure validation without making changes
556
+ validation = self.organizer.validate_structure()
557
+ if validation.get("issues"):
558
+ console.print(" [yellow]Files that would be organized:[/yellow]")
559
+ for issue in validation["issues"][:10]:
560
+ actions_planned.append(f"Organize: {issue.get('description', 'Unknown')}")
561
+ console.print(f" • {issue.get('description', 'Unknown')}")
562
+ else:
563
+ console.print(" ✅ Project structure is already well-organized")
564
+
565
+ # Check what documentation updates would occur
566
+ if has_existing:
567
+ console.print("\n[bold]📚 Documentation Updates:[/bold]")
568
+ doc_analysis = self.doc_manager.analyze_existing_content()
569
+
570
+ if not doc_analysis.get('has_priority_markers'):
571
+ actions_planned.append("Add priority markers (🔴🟡🟢⚪)")
572
+ console.print(" • Add priority markers (🔴🟡🟢⚪)")
573
+
574
+ if doc_analysis.get('outdated_patterns'):
575
+ actions_planned.append("Update outdated patterns")
576
+ console.print(" • Update outdated patterns")
577
+
578
+ if not doc_analysis.get('has_priority_index'):
579
+ actions_planned.append("Add priority index section")
580
+ console.print(" • Add priority index section")
581
+
582
+ # Archive would be created
583
+ actions_planned.append("Archive current CLAUDE.md to docs/_archive/")
584
+ console.print(" • Archive current CLAUDE.md to docs/_archive/")
585
+ else:
586
+ console.print("\n[bold]📚 Documentation Creation:[/bold]")
587
+ actions_planned.append("Create new CLAUDE.md with priority structure")
588
+ console.print(" • Create new CLAUDE.md with priority structure")
589
+
590
+ # General improvements
591
+ console.print("\n[bold]🔧 General Improvements:[/bold]")
592
+ actions_planned.extend([
593
+ "Update/create .gitignore if needed",
594
+ "Verify project structure compliance",
595
+ "Add memory system initialization",
596
+ "Set up single-path workflows"
597
+ ])
598
+ for action in actions_planned[-4:]:
599
+ console.print(f" • {action}")
600
+
601
+ console.print(f"\n[bold cyan]Summary: {len(actions_planned)} actions would be performed[/bold cyan]")
602
+ console.print("\n[dim]Run without --dry-run to execute these changes.[/dim]\n")
603
+
604
+ return {
605
+ "status": "success",
606
+ "mode": "dry_run",
607
+ "actions_planned": actions_planned,
608
+ "message": "Dry run completed - no changes made"
609
+ }
610
+
611
+ def _run_pre_initialization_checks(
612
+ self, organize_files: bool, skip_archive: bool, has_existing: bool
613
+ ) -> Dict:
614
+ """Run pre-initialization checks and preparations."""
615
+ checks_passed = []
616
+ warnings = []
617
+
618
+ # Run comprehensive project readiness check
619
+ ready, actions = self.organizer.ensure_project_ready(
620
+ auto_organize=organize_files,
621
+ safe_mode=True # Only perform safe operations by default
622
+ )
623
+
624
+ if actions:
625
+ checks_passed.extend(actions)
626
+
627
+ # Get structure validation report
628
+ validation = self.organizer.validate_structure()
629
+ if validation["warnings"]:
630
+ warnings.extend(validation["warnings"])
631
+ if validation["errors"]:
632
+ warnings.extend(validation["errors"])
633
+
634
+ # Show structure grade
635
+ if validation.get("grade"):
636
+ checks_passed.append(f"Structure validation: {validation['grade']}")
637
+
638
+ # Archive existing documentation if needed
639
+ if has_existing and not skip_archive:
640
+ if self.archive_manager.auto_archive_before_update(
641
+ self.project_path / "CLAUDE.md",
642
+ update_reason="Before mpm-init update"
643
+ ):
644
+ checks_passed.append("Archived existing CLAUDE.md")
645
+
646
+ # Check for issues
647
+ if structure_report.get('issues'):
648
+ for issue in structure_report['issues']:
649
+ warnings.append(issue['description'])
650
+
651
+ if warnings:
652
+ console.print("\n[yellow]⚠️ Project issues detected:[/yellow]")
653
+ for warning in warnings[:5]:
654
+ console.print(f" • {warning}")
655
+ console.print()
656
+
657
+ if checks_passed:
658
+ console.print("[green]✅ Pre-initialization checks:[/green]")
659
+ for check in checks_passed:
660
+ console.print(f" • {check}")
661
+ console.print()
662
+
663
+ return {"status": "success", "checks_passed": checks_passed, "warnings": warnings}
664
+
665
+ def _show_update_plan(self, ast_analysis: bool, preserve_custom: bool) -> None:
666
+ """Show update mode plan."""
667
+ console.print(
668
+ Panel(
669
+ "[bold cyan]🔄 Claude MPM Documentation Update[/bold cyan]\n\n"
670
+ "This will update your existing CLAUDE.md with:\n"
671
+ "• Smart merging of new and existing content\n"
672
+ + ("• Preservation of custom sections\n" if preserve_custom else "")
673
+ + "• Priority-based reorganization (🔴🟡🟢⚪)\n"
674
+ "• Updated single-path workflows\n"
675
+ "• Refreshed tool configurations\n"
676
+ + ("• AST analysis for enhanced documentation\n" if ast_analysis else "")
677
+ + "• Automatic archival of previous version\n"
678
+ + "• Holistic review and optimization\n"
679
+ + "\n[dim]Previous version will be archived in docs/_archive/[/dim]",
680
+ title="Update Mode",
681
+ border_style="blue",
682
+ )
683
+ )
684
+
685
+ def _show_initialization_plan(self, ast_analysis: bool) -> None:
686
+ """Show standard initialization plan."""
687
+ console.print(
688
+ Panel(
689
+ "[bold cyan]🤖👥 Claude MPM Project Initialization[/bold cyan]\n\n"
690
+ "This will set up your project with:\n"
691
+ "• Clear CLAUDE.md documentation for AI agents\n"
692
+ "• Single-path workflows (ONE way to do ANYTHING)\n"
693
+ "• Optimized project structure\n"
694
+ "• Tool configurations (linting, formatting, testing)\n"
695
+ "• GitHub workflows and CI/CD setup\n"
696
+ "• Memory system initialization\n"
697
+ + ("• AST analysis for comprehensive code documentation\n" if ast_analysis else "")
698
+ + "• Holistic CLAUDE.md organization with ranked instructions\n"
699
+ + "• Priority-based content structure (🔴🟡🟢⚪)\n"
700
+ + "\n[dim]Powered by Agentic Coder Optimizer Agent[/dim]",
701
+ title="MPM-Init",
702
+ border_style="cyan",
703
+ )
704
+ )
705
+
706
+ def _build_update_prompt(
707
+ self,
708
+ project_type: Optional[str],
709
+ framework: Optional[str],
710
+ ast_analysis: bool,
711
+ preserve_custom: bool,
712
+ ) -> str:
713
+ """Build prompt for update mode."""
714
+ # Get existing content analysis
715
+ doc_analysis = self.doc_manager.analyze_existing_content()
716
+
717
+ prompt = f"""Please delegate this task to the Agentic Coder Optimizer agent:
718
+
719
+ UPDATE existing CLAUDE.md documentation for this project.
720
+
721
+ Project Path: {self.project_path}
722
+ Update Mode: Smart merge with existing content
723
+ """
724
+ if project_type:
725
+ prompt += f"Project Type: {project_type}\n"
726
+ if framework:
727
+ prompt += f"Framework: {framework}\n"
728
+
729
+ prompt += f"""
730
+ Existing Documentation Analysis:
731
+ - Current CLAUDE.md: {doc_analysis.get('size', 0):,} characters, {doc_analysis.get('lines', 0)} lines
732
+ - Has Priority Index: {'Yes' if doc_analysis.get('has_priority_index') else 'No'}
733
+ - Custom Sections: {len(doc_analysis.get('custom_sections', []))} found
734
+ """
735
+ if preserve_custom and doc_analysis.get('custom_sections'):
736
+ prompt += f"- Preserve Custom Sections: {', '.join(doc_analysis['custom_sections'][:5])}\n"
737
+
738
+ prompt += """
739
+ Please perform the following UPDATE tasks:
740
+
741
+ 1. **Review Existing Content**:
742
+ - Analyze current CLAUDE.md structure and content
743
+ - Identify outdated or missing information
744
+ - Preserve valuable custom sections and project-specific knowledge
745
+
746
+ 2. **Smart Content Merge**:
747
+ - Update project overview if needed
748
+ - Refresh architecture documentation
749
+ - Update development workflows to ensure single-path principle
750
+ - Merge new standard sections while preserving custom content
751
+ - Remove duplicate or contradictory information
752
+
753
+ 3. **Update Priority Organization**:
754
+ - Reorganize content with priority markers (🔴🟡🟢⚪)
755
+ - Ensure critical instructions are at the top
756
+ - Update priority index with all important items
757
+ - Validate instruction clarity and completeness
758
+
759
+ 4. **Refresh Technical Content**:
760
+ - Update build/test/deploy commands
761
+ - Verify tool configurations are current
762
+ - Update dependency information
763
+ - Refresh API documentation if applicable
764
+ """
765
+ if ast_analysis:
766
+ prompt += """
767
+ 5. **Update Code Documentation** (using Code Analyzer agent):
768
+ - Re-analyze code structure for changes
769
+ - Update API documentation
770
+ - Refresh architecture diagrams
771
+ - Update function/class documentation
772
+ """
773
+ prompt += """
774
+ 6. **Final Optimization**:
775
+ - Ensure single-path principle throughout
776
+ - Validate all links and references
777
+ - Add/update timestamp in meta section
778
+ - Verify AI agent readability
779
+
780
+ IMPORTANT: This is an UPDATE operation. Intelligently merge new content with existing,
781
+ preserving valuable project-specific information while refreshing standard sections.
782
+ """
783
+ return prompt
784
+
785
+ def _handle_update_post_processing(self) -> None:
786
+ """Handle post-processing after successful update."""
787
+ # Generate update report
788
+ if self.doc_manager.has_existing_documentation():
789
+ latest_archive = self.archive_manager.get_latest_archive("CLAUDE.md")
790
+ if latest_archive:
791
+ comparison = self.archive_manager.compare_with_archive(
792
+ self.project_path / "CLAUDE.md",
793
+ latest_archive.name
794
+ )
795
+
796
+ if not comparison.get("identical"):
797
+ console.print("\n[bold cyan]📊 Update Summary[/bold cyan]")
798
+ console.print(f" Lines changed: {comparison.get('lines_added', 0):+d}")
799
+ console.print(f" Size change: {comparison.get('size_change', 0):+,} characters")
800
+ console.print(f" Previous version: {latest_archive.name}")
801
+
342
802
  def _run_initialization(
343
- self, prompt: str, verbose: bool, use_venv: bool = False
803
+ self, prompt: str, verbose: bool, use_venv: bool = False, update_mode: bool = False
344
804
  ) -> Dict:
345
805
  """Run the initialization through subprocess calling claude-mpm."""
346
806
  import tempfile
@@ -529,6 +989,36 @@ The final CLAUDE.md should be a comprehensive, well-organized guide that any AI
529
989
  is_flag=True,
530
990
  help="Force reinitialization even if project is already configured",
531
991
  )
992
+ @click.option(
993
+ "--update",
994
+ is_flag=True,
995
+ help="Update existing CLAUDE.md instead of recreating",
996
+ )
997
+ @click.option(
998
+ "--review",
999
+ is_flag=True,
1000
+ help="Review project state without making changes",
1001
+ )
1002
+ @click.option(
1003
+ "--organize",
1004
+ is_flag=True,
1005
+ help="Automatically organize misplaced files into proper directories",
1006
+ )
1007
+ @click.option(
1008
+ "--auto-safe/--no-auto-safe",
1009
+ default=True,
1010
+ help="Only move files with high confidence (default: safe mode on)",
1011
+ )
1012
+ @click.option(
1013
+ "--preserve-custom/--no-preserve-custom",
1014
+ default=True,
1015
+ help="Preserve custom sections when updating (default: preserve)",
1016
+ )
1017
+ @click.option(
1018
+ "--skip-archive",
1019
+ is_flag=True,
1020
+ help="Skip archiving existing files before updating",
1021
+ )
532
1022
  @click.option(
533
1023
  "--verbose", is_flag=True, help="Show detailed output during initialization"
534
1024
  )
@@ -543,24 +1033,42 @@ The final CLAUDE.md should be a comprehensive, well-organized guide that any AI
543
1033
  required=False,
544
1034
  default=".",
545
1035
  )
546
- def mpm_init(project_type, framework, force, verbose, ast_analysis, project_path):
1036
+ def mpm_init(
1037
+ project_type,
1038
+ framework,
1039
+ force,
1040
+ update,
1041
+ review,
1042
+ organize,
1043
+ auto_safe,
1044
+ preserve_custom,
1045
+ skip_archive,
1046
+ verbose,
1047
+ ast_analysis,
1048
+ project_path,
1049
+ ):
547
1050
  """
548
- Initialize a project for optimal use with Claude Code and Claude MPM.
1051
+ Initialize or update a project for optimal use with Claude Code and Claude MPM.
549
1052
 
550
1053
  This command uses the Agentic Coder Optimizer agent to:
551
- - Create comprehensive CLAUDE.md documentation
1054
+ - Create or update comprehensive CLAUDE.md documentation
552
1055
  - Establish single-path workflows (ONE way to do ANYTHING)
553
1056
  - Configure development tools and standards
554
1057
  - Set up memory systems for project knowledge
555
1058
  - Optimize for AI agent understanding
556
1059
  - Perform AST analysis for enhanced developer documentation
557
1060
 
1061
+ Update Mode:
1062
+ When CLAUDE.md exists, the command offers to update rather than recreate,
1063
+ preserving custom content while refreshing standard sections.
1064
+
558
1065
  Examples:
559
- claude-mpm mpm-init
560
- claude-mpm mpm-init --project-type web --framework react
561
- claude-mpm mpm-init /path/to/project --force
562
- claude-mpm mpm-init --ast-analysis # Enable AST analysis (default)
563
- claude-mpm mpm-init --no-ast-analysis # Disable AST analysis
1066
+ claude-mpm mpm-init # Initialize/update current directory
1067
+ claude-mpm mpm-init --review # Review project state without changes
1068
+ claude-mpm mpm-init --update # Force update mode
1069
+ claude-mpm mpm-init --organize # Organize misplaced files
1070
+ claude-mpm mpm-init --project-type web # Initialize as web project
1071
+ claude-mpm mpm-init /path/to/project --force # Force reinitialize project
564
1072
  """
565
1073
  try:
566
1074
  # Create command instance
@@ -573,6 +1081,11 @@ def mpm_init(project_type, framework, force, verbose, ast_analysis, project_path
573
1081
  force=force,
574
1082
  verbose=verbose,
575
1083
  ast_analysis=ast_analysis,
1084
+ update_mode=update,
1085
+ review_only=review,
1086
+ organize_files=organize,
1087
+ preserve_custom=preserve_custom,
1088
+ skip_archive=skip_archive,
576
1089
  )
577
1090
 
578
1091
  # Exit with appropriate code