claude-mpm 0.3.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 (159) hide show
  1. claude_mpm/__init__.py +17 -0
  2. claude_mpm/__main__.py +14 -0
  3. claude_mpm/_version.py +32 -0
  4. claude_mpm/agents/BASE_AGENT_TEMPLATE.md +88 -0
  5. claude_mpm/agents/INSTRUCTIONS.md +375 -0
  6. claude_mpm/agents/__init__.py +118 -0
  7. claude_mpm/agents/agent_loader.py +621 -0
  8. claude_mpm/agents/agent_loader_integration.py +229 -0
  9. claude_mpm/agents/agents_metadata.py +204 -0
  10. claude_mpm/agents/base_agent.json +27 -0
  11. claude_mpm/agents/base_agent_loader.py +519 -0
  12. claude_mpm/agents/schema/agent_schema.json +160 -0
  13. claude_mpm/agents/system_agent_config.py +587 -0
  14. claude_mpm/agents/templates/__init__.py +101 -0
  15. claude_mpm/agents/templates/data_engineer_agent.json +46 -0
  16. claude_mpm/agents/templates/documentation_agent.json +45 -0
  17. claude_mpm/agents/templates/engineer_agent.json +49 -0
  18. claude_mpm/agents/templates/ops_agent.json +46 -0
  19. claude_mpm/agents/templates/qa_agent.json +45 -0
  20. claude_mpm/agents/templates/research_agent.json +49 -0
  21. claude_mpm/agents/templates/security_agent.json +46 -0
  22. claude_mpm/agents/templates/update-optimized-specialized-agents.json +374 -0
  23. claude_mpm/agents/templates/version_control_agent.json +46 -0
  24. claude_mpm/agents/test_fix_deployment/.claude-pm/config/project.json +6 -0
  25. claude_mpm/cli.py +655 -0
  26. claude_mpm/cli_main.py +13 -0
  27. claude_mpm/cli_module/__init__.py +15 -0
  28. claude_mpm/cli_module/args.py +222 -0
  29. claude_mpm/cli_module/commands.py +203 -0
  30. claude_mpm/cli_module/migration_example.py +183 -0
  31. claude_mpm/cli_module/refactoring_guide.md +253 -0
  32. claude_mpm/cli_old/__init__.py +1 -0
  33. claude_mpm/cli_old/ticket_cli.py +102 -0
  34. claude_mpm/config/__init__.py +5 -0
  35. claude_mpm/config/hook_config.py +42 -0
  36. claude_mpm/constants.py +150 -0
  37. claude_mpm/core/__init__.py +45 -0
  38. claude_mpm/core/agent_name_normalizer.py +248 -0
  39. claude_mpm/core/agent_registry.py +627 -0
  40. claude_mpm/core/agent_registry.py.bak +312 -0
  41. claude_mpm/core/agent_session_manager.py +273 -0
  42. claude_mpm/core/base_service.py +747 -0
  43. claude_mpm/core/base_service.py.bak +406 -0
  44. claude_mpm/core/config.py +334 -0
  45. claude_mpm/core/config_aliases.py +292 -0
  46. claude_mpm/core/container.py +347 -0
  47. claude_mpm/core/factories.py +281 -0
  48. claude_mpm/core/framework_loader.py +472 -0
  49. claude_mpm/core/injectable_service.py +206 -0
  50. claude_mpm/core/interfaces.py +539 -0
  51. claude_mpm/core/logger.py +468 -0
  52. claude_mpm/core/minimal_framework_loader.py +107 -0
  53. claude_mpm/core/mixins.py +150 -0
  54. claude_mpm/core/service_registry.py +299 -0
  55. claude_mpm/core/session_manager.py +190 -0
  56. claude_mpm/core/simple_runner.py +511 -0
  57. claude_mpm/core/tool_access_control.py +173 -0
  58. claude_mpm/hooks/README.md +243 -0
  59. claude_mpm/hooks/__init__.py +5 -0
  60. claude_mpm/hooks/base_hook.py +154 -0
  61. claude_mpm/hooks/builtin/__init__.py +1 -0
  62. claude_mpm/hooks/builtin/logging_hook_example.py +165 -0
  63. claude_mpm/hooks/builtin/post_delegation_hook_example.py +124 -0
  64. claude_mpm/hooks/builtin/pre_delegation_hook_example.py +125 -0
  65. claude_mpm/hooks/builtin/submit_hook_example.py +100 -0
  66. claude_mpm/hooks/builtin/ticket_extraction_hook_example.py +237 -0
  67. claude_mpm/hooks/builtin/todo_agent_prefix_hook.py +239 -0
  68. claude_mpm/hooks/builtin/workflow_start_hook.py +181 -0
  69. claude_mpm/hooks/hook_client.py +264 -0
  70. claude_mpm/hooks/hook_runner.py +370 -0
  71. claude_mpm/hooks/json_rpc_executor.py +259 -0
  72. claude_mpm/hooks/json_rpc_hook_client.py +319 -0
  73. claude_mpm/hooks/tool_call_interceptor.py +204 -0
  74. claude_mpm/init.py +246 -0
  75. claude_mpm/orchestration/SUBPROCESS_DESIGN.md +66 -0
  76. claude_mpm/orchestration/__init__.py +6 -0
  77. claude_mpm/orchestration/archive/direct_orchestrator.py +195 -0
  78. claude_mpm/orchestration/archive/factory.py +215 -0
  79. claude_mpm/orchestration/archive/hook_enabled_orchestrator.py +188 -0
  80. claude_mpm/orchestration/archive/hook_integration_example.py +178 -0
  81. claude_mpm/orchestration/archive/interactive_subprocess_orchestrator.py +826 -0
  82. claude_mpm/orchestration/archive/orchestrator.py +501 -0
  83. claude_mpm/orchestration/archive/pexpect_orchestrator.py +252 -0
  84. claude_mpm/orchestration/archive/pty_orchestrator.py +270 -0
  85. claude_mpm/orchestration/archive/simple_orchestrator.py +82 -0
  86. claude_mpm/orchestration/archive/subprocess_orchestrator.py +801 -0
  87. claude_mpm/orchestration/archive/system_prompt_orchestrator.py +278 -0
  88. claude_mpm/orchestration/archive/wrapper_orchestrator.py +187 -0
  89. claude_mpm/scripts/__init__.py +1 -0
  90. claude_mpm/scripts/ticket.py +269 -0
  91. claude_mpm/services/__init__.py +10 -0
  92. claude_mpm/services/agent_deployment.py +955 -0
  93. claude_mpm/services/agent_lifecycle_manager.py +948 -0
  94. claude_mpm/services/agent_management_service.py +596 -0
  95. claude_mpm/services/agent_modification_tracker.py +841 -0
  96. claude_mpm/services/agent_profile_loader.py +606 -0
  97. claude_mpm/services/agent_registry.py +677 -0
  98. claude_mpm/services/base_agent_manager.py +380 -0
  99. claude_mpm/services/framework_agent_loader.py +337 -0
  100. claude_mpm/services/framework_claude_md_generator/README.md +92 -0
  101. claude_mpm/services/framework_claude_md_generator/__init__.py +206 -0
  102. claude_mpm/services/framework_claude_md_generator/content_assembler.py +151 -0
  103. claude_mpm/services/framework_claude_md_generator/content_validator.py +126 -0
  104. claude_mpm/services/framework_claude_md_generator/deployment_manager.py +137 -0
  105. claude_mpm/services/framework_claude_md_generator/section_generators/__init__.py +106 -0
  106. claude_mpm/services/framework_claude_md_generator/section_generators/agents.py +582 -0
  107. claude_mpm/services/framework_claude_md_generator/section_generators/claude_pm_init.py +97 -0
  108. claude_mpm/services/framework_claude_md_generator/section_generators/core_responsibilities.py +27 -0
  109. claude_mpm/services/framework_claude_md_generator/section_generators/delegation_constraints.py +23 -0
  110. claude_mpm/services/framework_claude_md_generator/section_generators/environment_config.py +23 -0
  111. claude_mpm/services/framework_claude_md_generator/section_generators/footer.py +20 -0
  112. claude_mpm/services/framework_claude_md_generator/section_generators/header.py +26 -0
  113. claude_mpm/services/framework_claude_md_generator/section_generators/orchestration_principles.py +30 -0
  114. claude_mpm/services/framework_claude_md_generator/section_generators/role_designation.py +37 -0
  115. claude_mpm/services/framework_claude_md_generator/section_generators/subprocess_validation.py +111 -0
  116. claude_mpm/services/framework_claude_md_generator/section_generators/todo_task_tools.py +89 -0
  117. claude_mpm/services/framework_claude_md_generator/section_generators/troubleshooting.py +39 -0
  118. claude_mpm/services/framework_claude_md_generator/section_manager.py +106 -0
  119. claude_mpm/services/framework_claude_md_generator/version_manager.py +121 -0
  120. claude_mpm/services/framework_claude_md_generator.py +621 -0
  121. claude_mpm/services/hook_service.py +388 -0
  122. claude_mpm/services/hook_service_manager.py +223 -0
  123. claude_mpm/services/json_rpc_hook_manager.py +92 -0
  124. claude_mpm/services/parent_directory_manager/README.md +83 -0
  125. claude_mpm/services/parent_directory_manager/__init__.py +577 -0
  126. claude_mpm/services/parent_directory_manager/backup_manager.py +258 -0
  127. claude_mpm/services/parent_directory_manager/config_manager.py +210 -0
  128. claude_mpm/services/parent_directory_manager/deduplication_manager.py +279 -0
  129. claude_mpm/services/parent_directory_manager/framework_protector.py +143 -0
  130. claude_mpm/services/parent_directory_manager/operations.py +186 -0
  131. claude_mpm/services/parent_directory_manager/state_manager.py +624 -0
  132. claude_mpm/services/parent_directory_manager/template_deployer.py +579 -0
  133. claude_mpm/services/parent_directory_manager/validation_manager.py +378 -0
  134. claude_mpm/services/parent_directory_manager/version_control_helper.py +339 -0
  135. claude_mpm/services/parent_directory_manager/version_manager.py +222 -0
  136. claude_mpm/services/shared_prompt_cache.py +819 -0
  137. claude_mpm/services/ticket_manager.py +213 -0
  138. claude_mpm/services/ticket_manager_di.py +318 -0
  139. claude_mpm/services/ticketing_service_original.py +508 -0
  140. claude_mpm/services/version_control/VERSION +1 -0
  141. claude_mpm/services/version_control/__init__.py +70 -0
  142. claude_mpm/services/version_control/branch_strategy.py +670 -0
  143. claude_mpm/services/version_control/conflict_resolution.py +744 -0
  144. claude_mpm/services/version_control/git_operations.py +784 -0
  145. claude_mpm/services/version_control/semantic_versioning.py +703 -0
  146. claude_mpm/ui/__init__.py +1 -0
  147. claude_mpm/ui/rich_terminal_ui.py +295 -0
  148. claude_mpm/ui/terminal_ui.py +328 -0
  149. claude_mpm/utils/__init__.py +16 -0
  150. claude_mpm/utils/config_manager.py +468 -0
  151. claude_mpm/utils/import_migration_example.py +80 -0
  152. claude_mpm/utils/imports.py +182 -0
  153. claude_mpm/utils/path_operations.py +357 -0
  154. claude_mpm/utils/paths.py +289 -0
  155. claude_mpm-0.3.0.dist-info/METADATA +290 -0
  156. claude_mpm-0.3.0.dist-info/RECORD +159 -0
  157. claude_mpm-0.3.0.dist-info/WHEEL +5 -0
  158. claude_mpm-0.3.0.dist-info/entry_points.txt +4 -0
  159. claude_mpm-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,621 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Framework INSTRUCTIONS.md Generator Service - Consolidated Module
4
+ ===============================================================
5
+
6
+ This service provides structured generation of the framework INSTRUCTIONS.md template
7
+ (legacy: CLAUDE.md) with auto-versioning, section management, and deployment capabilities.
8
+
9
+ This is a consolidated version combining all functionality from the previous
10
+ multi-file implementation for better maintainability.
11
+ """
12
+
13
+ import os
14
+ import shutil
15
+ import logging
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Dict, Optional, Any, List, Tuple, Callable
19
+ from dataclasses import dataclass, field
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ # ============================================================================
25
+ # Data Models
26
+ # ============================================================================
27
+
28
+ @dataclass
29
+ class SectionContent:
30
+ """Represents a section of the INSTRUCTIONS.md file."""
31
+ id: str
32
+ title: str
33
+ content: str
34
+ order: int
35
+ required: bool = True
36
+ metadata: Dict[str, Any] = field(default_factory=dict)
37
+
38
+
39
+ @dataclass
40
+ class ValidationResult:
41
+ """Results from content validation."""
42
+ is_valid: bool
43
+ errors: List[str] = field(default_factory=list)
44
+ warnings: List[str] = field(default_factory=list)
45
+ suggestions: List[str] = field(default_factory=list)
46
+
47
+
48
+ # ============================================================================
49
+ # Section Generators
50
+ # ============================================================================
51
+
52
+ class SectionGenerators:
53
+ """All section generators in a single class for maintainability."""
54
+
55
+ @staticmethod
56
+ def generate_header(version: str, **kwargs) -> str:
57
+ """Generate the header section."""
58
+ return f"""# Multi-Agent Project Management Framework v{version}
59
+ ## INSTRUCTIONS.md - Claude PM Orchestrator Agent
60
+ Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
61
+ """
62
+
63
+ @staticmethod
64
+ def generate_claude_pm_init(**kwargs) -> str:
65
+ """Generate Claude PM initialization section."""
66
+ return """## Claude PM Initialization
67
+
68
+ You are the Claude PM (Project Manager) orchestrator agent. Your primary role is to:
69
+
70
+ 1. **Orchestrate Multi-Agent Workflows**: Delegate tasks to specialized agents based on their expertise
71
+ 2. **Maintain Project Context**: Keep track of project state, goals, and progress
72
+ 3. **Ensure Quality**: Monitor agent outputs and ensure they meet project standards
73
+ 4. **Coordinate Communication**: Facilitate information flow between agents
74
+
75
+ ### Key Responsibilities:
76
+ - Analyze incoming requests and determine appropriate agent delegation
77
+ - Monitor subprocess execution and handle results
78
+ - Maintain project consistency across agent boundaries
79
+ - Provide clear, actionable feedback to users
80
+ """
81
+
82
+ @staticmethod
83
+ def generate_role_designation(**kwargs) -> str:
84
+ """Generate role designation section."""
85
+ return """## Role Designation
86
+
87
+ As the PM orchestrator, you have access to the following specialized agents:
88
+
89
+ ### Core Agents:
90
+ - **Engineer**: Code implementation, debugging, refactoring
91
+ - **Architect**: System design, technical architecture, scalability
92
+ - **QA**: Testing, quality assurance, test automation
93
+ - **Security**: Security analysis, vulnerability assessment
94
+ - **Documentation**: Technical writing, API docs, user guides
95
+ - **Ops**: DevOps, deployment, infrastructure
96
+ - **Data**: Data engineering, analytics, database design
97
+ - **Research**: Technical research, feasibility studies
98
+ - **Version Control**: Git operations, branching strategies
99
+
100
+ ### Specialized Agents:
101
+ - Additional domain-specific agents available based on project needs
102
+ """
103
+
104
+ @staticmethod
105
+ def generate_core_responsibilities(**kwargs) -> str:
106
+ """Generate core responsibilities section."""
107
+ return """## Core Responsibilities
108
+
109
+ ### 1. Request Analysis
110
+ - Parse and understand user requirements
111
+ - Identify required expertise and resources
112
+ - Determine optimal agent delegation strategy
113
+
114
+ ### 2. Agent Delegation
115
+ - Select appropriate agents based on task requirements
116
+ - Prepare clear, specific instructions for each agent
117
+ - Use subprocess execution for agent tasks
118
+
119
+ ### 3. Result Synthesis
120
+ - Collect and validate agent outputs
121
+ - Ensure consistency across deliverables
122
+ - Present cohesive results to users
123
+
124
+ ### 4. Quality Assurance
125
+ - Monitor agent performance
126
+ - Validate outputs meet requirements
127
+ - Request revisions when necessary
128
+ """
129
+
130
+ @staticmethod
131
+ def generate_orchestration_principles(**kwargs) -> str:
132
+ """Generate orchestration principles section."""
133
+ return """## Orchestration Principles
134
+
135
+ ### Delegation Guidelines:
136
+ 1. **Single Responsibility**: Each agent handles their domain expertise
137
+ 2. **Clear Instructions**: Provide specific, actionable tasks
138
+ 3. **Context Preservation**: Pass necessary context between agents
139
+ 4. **Result Validation**: Verify outputs before presenting to users
140
+
141
+ ### Communication Protocol:
142
+ - Use structured task definitions
143
+ - Include success criteria in delegations
144
+ - Request specific output formats
145
+ - Handle errors gracefully
146
+ """
147
+
148
+ @staticmethod
149
+ def generate_delegation_constraints(**kwargs) -> str:
150
+ """Generate delegation constraints section."""
151
+ return """## Delegation Constraints
152
+
153
+ ### Never Delegate:
154
+ - User authentication/authorization decisions
155
+ - Sensitive data handling without oversight
156
+ - Direct production deployments
157
+ - Financial or legal decisions
158
+
159
+ ### Always Delegate:
160
+ - Domain-specific implementation tasks
161
+ - Technical analysis requiring expertise
162
+ - Large-scale code generation
163
+ - Specialized testing scenarios
164
+ """
165
+
166
+ @staticmethod
167
+ def generate_subprocess_validation(**kwargs) -> str:
168
+ """Generate subprocess validation section."""
169
+ return """## Subprocess Validation
170
+
171
+ ### Pre-Delegation Checks:
172
+ 1. Validate agent availability
173
+ 2. Ensure task is within agent capabilities
174
+ 3. Verify resource requirements
175
+ 4. Check for circular dependencies
176
+
177
+ ### Post-Execution Validation:
178
+ 1. Verify subprocess completed successfully
179
+ 2. Validate output format and content
180
+ 3. Check for errors or warnings
181
+ 4. Ensure deliverables meet requirements
182
+
183
+ ### Error Handling:
184
+ - Capture and log subprocess errors
185
+ - Provide meaningful error messages
186
+ - Suggest alternatives when agents fail
187
+ - Maintain graceful degradation
188
+ """
189
+
190
+ @staticmethod
191
+ def generate_agents(agent_profiles: Optional[List[Dict]] = None, **kwargs) -> str:
192
+ """Generate comprehensive agents section."""
193
+ if not agent_profiles:
194
+ # Default agent profiles
195
+ agent_profiles = [
196
+ {
197
+ "name": "Engineer",
198
+ "role": "Software Engineering Expert",
199
+ "capabilities": [
200
+ "Code implementation in multiple languages",
201
+ "Debugging and troubleshooting",
202
+ "Performance optimization",
203
+ "Code refactoring"
204
+ ]
205
+ },
206
+ {
207
+ "name": "Architect",
208
+ "role": "System Architecture Expert",
209
+ "capabilities": [
210
+ "System design and architecture",
211
+ "Technology selection",
212
+ "Scalability planning",
213
+ "Integration design"
214
+ ]
215
+ },
216
+ # Add more default profiles as needed
217
+ ]
218
+
219
+ content = "## Available Agents\n\n"
220
+
221
+ for profile in agent_profiles:
222
+ content += f"### {profile['name']} Agent\n"
223
+ content += f"**Role**: {profile['role']}\n\n"
224
+ content += "**Capabilities**:\n"
225
+ for capability in profile.get('capabilities', []):
226
+ content += f"- {capability}\n"
227
+ content += "\n"
228
+
229
+ return content
230
+
231
+ @staticmethod
232
+ def generate_todo_task_tools(**kwargs) -> str:
233
+ """Generate todo/task tools section."""
234
+ return """## Task Management Tools
235
+
236
+ ### TodoWrite Tool
237
+ Use the TodoWrite tool to manage task lists and track progress:
238
+ - Create structured task lists for complex workflows
239
+ - Track task status (pending, in_progress, completed)
240
+ - Organize multi-step operations
241
+ - Demonstrate thoroughness to users
242
+
243
+ **CRITICAL TodoWrite Requirement**:
244
+ - **ALWAYS** prefix each todo item with [Agent] to indicate delegation target
245
+ - Examples: [Research], [Engineer], [QA], [Security], [Documentation], [Ops], [Version Control]
246
+ - This ensures proper task attribution and tracking across the multi-agent system
247
+ - The system will automatically validate and enforce this requirement
248
+
249
+ ### Task Tool (Subprocess Execution)
250
+ The Task tool enables subprocess delegation:
251
+ - Execute specialized agent tasks
252
+ - Run isolated operations
253
+ - Maintain clean execution contexts
254
+ - Handle long-running operations
255
+
256
+ ### Usage Guidelines:
257
+ 1. Use TodoWrite for task planning and tracking with [Agent] prefixes
258
+ 2. Use Task tool for actual agent delegation
259
+ 3. Update todo items as tasks complete
260
+ 4. Maintain clear task descriptions with proper agent attribution
261
+ """
262
+
263
+ @staticmethod
264
+ def generate_environment_config(**kwargs) -> str:
265
+ """Generate environment configuration section."""
266
+ return """## Environment Configuration
267
+
268
+ ### Working Directory Structure:
269
+ - Maintain awareness of project structure
270
+ - Respect existing file organization
271
+ - Create new directories only when necessary
272
+ - Follow project conventions
273
+
274
+ ### Resource Management:
275
+ - Monitor subprocess resource usage
276
+ - Implement timeouts for long operations
277
+ - Clean up temporary resources
278
+ - Handle resource conflicts gracefully
279
+ """
280
+
281
+ @staticmethod
282
+ def generate_troubleshooting(**kwargs) -> str:
283
+ """Generate troubleshooting section."""
284
+ return """## Troubleshooting Guide
285
+
286
+ ### Common Issues:
287
+
288
+ 1. **Agent Not Found**
289
+ - Verify agent name spelling
290
+ - Check agent availability
291
+ - Use fallback strategies
292
+
293
+ 2. **Subprocess Timeout**
294
+ - Increase timeout for complex tasks
295
+ - Break down large operations
296
+ - Monitor resource usage
297
+
298
+ 3. **Output Validation Failure**
299
+ - Review agent instructions
300
+ - Check output format requirements
301
+ - Request clarification if needed
302
+
303
+ 4. **Context Loss**
304
+ - Maintain explicit context passing
305
+ - Use structured data formats
306
+ - Implement checkpoints
307
+ """
308
+
309
+ @staticmethod
310
+ def generate_footer(version: str, **kwargs) -> str:
311
+ """Generate footer section."""
312
+ return f"""
313
+ ---
314
+ Framework Version: {version}
315
+ Last Updated: {datetime.now().strftime('%Y-%m-%d')}
316
+ """
317
+
318
+
319
+ # ============================================================================
320
+ # Main Generator Class
321
+ # ============================================================================
322
+
323
+ class FrameworkClaudeMdGenerator:
324
+ """
325
+ Generates and manages the framework INSTRUCTIONS.md template (legacy: CLAUDE.md)
326
+ with structured sections, auto-versioning, and deployment capabilities.
327
+
328
+ This consolidated version combines all functionality into a single module.
329
+ """
330
+
331
+ def __init__(self):
332
+ """Initialize the generator with current framework version."""
333
+ self.framework_version = self._detect_framework_version()
334
+ self.sections: List[SectionContent] = []
335
+ self.section_generators = SectionGenerators()
336
+
337
+ # Deployment paths
338
+ self.framework_root = self._find_framework_root()
339
+ self.deployment_targets = {
340
+ 'framework': self.framework_root / 'INSTRUCTIONS.md' if self.framework_root else None,
341
+ 'user': Path.home() / '.claude-pm' / 'INSTRUCTIONS.md',
342
+ 'project': Path.cwd() / 'INSTRUCTIONS.md'
343
+ }
344
+
345
+ # Initialize default sections
346
+ self._initialize_sections()
347
+
348
+ logger.info(f"FrameworkClaudeMdGenerator initialized with version {self.framework_version}")
349
+
350
+ def _detect_framework_version(self) -> str:
351
+ """Detect the current framework version."""
352
+ # Try multiple locations for VERSION file
353
+ version_locations = [
354
+ Path(__file__).parent.parent / 'framework' / 'VERSION',
355
+ Path.cwd() / 'framework' / 'VERSION',
356
+ Path.home() / '.claude-pm' / 'VERSION'
357
+ ]
358
+
359
+ for version_file in version_locations:
360
+ if version_file.exists():
361
+ try:
362
+ return version_file.read_text().strip()
363
+ except Exception:
364
+ pass
365
+
366
+ # Default version
367
+ return "1.0.0"
368
+
369
+ def _find_framework_root(self) -> Optional[Path]:
370
+ """Find the framework root directory."""
371
+ possible_roots = [
372
+ Path(__file__).parent.parent / 'framework',
373
+ Path.cwd() / 'framework',
374
+ Path.cwd() / 'src' / 'claude_mpm' / 'framework'
375
+ ]
376
+
377
+ for root in possible_roots:
378
+ if root.exists():
379
+ return root
380
+
381
+ return None
382
+
383
+ def _initialize_sections(self) -> None:
384
+ """Initialize all sections in the required order."""
385
+ section_configs = [
386
+ ("header", "Header", self.section_generators.generate_header, True),
387
+ ("claude_pm_init", "Claude PM Initialization", self.section_generators.generate_claude_pm_init, True),
388
+ ("role_designation", "Role Designation", self.section_generators.generate_role_designation, True),
389
+ ("core_responsibilities", "Core Responsibilities", self.section_generators.generate_core_responsibilities, True),
390
+ ("orchestration_principles", "Orchestration Principles", self.section_generators.generate_orchestration_principles, True),
391
+ ("delegation_constraints", "Delegation Constraints", self.section_generators.generate_delegation_constraints, True),
392
+ ("subprocess_validation", "Subprocess Validation", self.section_generators.generate_subprocess_validation, True),
393
+ ("agents", "Available Agents", self.section_generators.generate_agents, True),
394
+ ("todo_task_tools", "Task Management Tools", self.section_generators.generate_todo_task_tools, True),
395
+ ("environment_config", "Environment Configuration", self.section_generators.generate_environment_config, False),
396
+ ("troubleshooting", "Troubleshooting Guide", self.section_generators.generate_troubleshooting, False),
397
+ ("footer", "Footer", self.section_generators.generate_footer, True)
398
+ ]
399
+
400
+ for order, (section_id, title, generator, required) in enumerate(section_configs):
401
+ self.add_section(section_id, title, generator, order, required)
402
+
403
+ def add_section(self, section_id: str, title: str,
404
+ generator: Callable, order: int, required: bool = True) -> None:
405
+ """Add a section to the generator."""
406
+ section = SectionContent(
407
+ id=section_id,
408
+ title=title,
409
+ content="", # Will be generated
410
+ order=order,
411
+ required=required
412
+ )
413
+ self.sections.append(section)
414
+
415
+ # Store generator reference
416
+ section.metadata['generator'] = generator
417
+
418
+ def generate_content(self, include_optional: bool = True,
419
+ custom_data: Optional[Dict[str, Any]] = None) -> str:
420
+ """Generate the complete INSTRUCTIONS.md content."""
421
+ content_parts = []
422
+ custom_data = custom_data or {}
423
+
424
+ # Sort sections by order
425
+ sorted_sections = sorted(self.sections, key=lambda s: s.order)
426
+
427
+ for section in sorted_sections:
428
+ # Skip optional sections if not included
429
+ if not section.required and not include_optional:
430
+ continue
431
+
432
+ # Generate section content
433
+ generator = section.metadata.get('generator')
434
+ if generator:
435
+ section_content = generator(
436
+ version=self.framework_version,
437
+ **custom_data
438
+ )
439
+ section.content = section_content
440
+ content_parts.append(section_content)
441
+
442
+ return "\n".join(content_parts)
443
+
444
+ def validate_content(self, content: str) -> ValidationResult:
445
+ """Validate generated content."""
446
+ errors = []
447
+ warnings = []
448
+ suggestions = []
449
+
450
+ # Check minimum length
451
+ if len(content) < 1000:
452
+ errors.append("Content seems too short")
453
+
454
+ # Check for required sections
455
+ required_sections = [
456
+ "Claude PM Initialization",
457
+ "Role Designation",
458
+ "Core Responsibilities"
459
+ ]
460
+
461
+ for required in required_sections:
462
+ if required not in content:
463
+ errors.append(f"Missing required section: {required}")
464
+
465
+ # Check for version
466
+ if self.framework_version not in content:
467
+ warnings.append("Framework version not found in content")
468
+
469
+ # Structure validation
470
+ if content.count('#') < 5:
471
+ warnings.append("Content may lack proper structure (too few headers)")
472
+
473
+ # Suggestions
474
+ if "```" not in content:
475
+ suggestions.append("Consider adding code examples")
476
+
477
+ return ValidationResult(
478
+ is_valid=len(errors) == 0,
479
+ errors=errors,
480
+ warnings=warnings,
481
+ suggestions=suggestions
482
+ )
483
+
484
+ def deploy(self, target: str = 'framework',
485
+ backup: bool = True,
486
+ validate: bool = True) -> Tuple[bool, str]:
487
+ """Deploy generated content to target location."""
488
+ if target not in self.deployment_targets:
489
+ return False, f"Unknown deployment target: {target}"
490
+
491
+ target_path = self.deployment_targets[target]
492
+ if not target_path:
493
+ return False, f"Target path for '{target}' not configured"
494
+
495
+ # Generate content
496
+ content = self.generate_content()
497
+
498
+ # Validate if requested
499
+ if validate:
500
+ validation_result = self.validate_content(content)
501
+ if not validation_result.is_valid:
502
+ return False, f"Validation failed: {', '.join(validation_result.errors)}"
503
+
504
+ # Create target directory if needed
505
+ target_path.parent.mkdir(parents=True, exist_ok=True)
506
+
507
+ # Backup existing file if requested
508
+ if backup and target_path.exists():
509
+ backup_path = target_path.with_suffix(f'.backup.{datetime.now().strftime("%Y%m%d_%H%M%S")}')
510
+ shutil.copy2(target_path, backup_path)
511
+ logger.info(f"Created backup: {backup_path}")
512
+
513
+ # Write new content
514
+ try:
515
+ target_path.write_text(content)
516
+ logger.info(f"Deployed to: {target_path}")
517
+ return True, f"Successfully deployed to {target_path}"
518
+ except Exception as e:
519
+ return False, f"Deployment failed: {e}"
520
+
521
+ def update_version(self, new_version: str) -> None:
522
+ """Update the framework version."""
523
+ self.framework_version = new_version
524
+ logger.info(f"Updated framework version to {new_version}")
525
+
526
+ def get_deployment_status(self) -> Dict[str, Any]:
527
+ """Get deployment status for all targets."""
528
+ status = {}
529
+
530
+ for target, path in self.deployment_targets.items():
531
+ if not path:
532
+ status[target] = {'exists': False, 'accessible': False}
533
+ continue
534
+
535
+ status[target] = {
536
+ 'exists': path.exists(),
537
+ 'accessible': path.parent.exists() and os.access(path.parent, os.W_OK),
538
+ 'path': str(path)
539
+ }
540
+
541
+ if path.exists():
542
+ stat = path.stat()
543
+ status[target].update({
544
+ 'size': stat.st_size,
545
+ 'modified': datetime.fromtimestamp(stat.st_mtime).isoformat()
546
+ })
547
+
548
+ return status
549
+
550
+ def export_template(self, output_path: Path,
551
+ format: str = 'markdown') -> bool:
552
+ """Export template to specified path and format."""
553
+ content = self.generate_content()
554
+
555
+ try:
556
+ if format == 'markdown':
557
+ output_path.write_text(content)
558
+ elif format == 'html':
559
+ # Simple markdown to HTML conversion
560
+ import re
561
+ html_content = content
562
+ # Convert headers
563
+ html_content = re.sub(r'^### (.+)$', r'<h3>\1</h3>', html_content, flags=re.MULTILINE)
564
+ html_content = re.sub(r'^## (.+)$', r'<h2>\1</h2>', html_content, flags=re.MULTILINE)
565
+ html_content = re.sub(r'^# (.+)$', r'<h1>\1</h1>', html_content, flags=re.MULTILINE)
566
+ # Convert lists
567
+ html_content = re.sub(r'^- (.+)$', r'<li>\1</li>', html_content, flags=re.MULTILINE)
568
+ # Wrap in basic HTML
569
+ html_content = f"""<!DOCTYPE html>
570
+ <html>
571
+ <head>
572
+ <title>Framework INSTRUCTIONS.md</title>
573
+ <style>
574
+ body {{ font-family: Arial, sans-serif; margin: 40px; }}
575
+ h1, h2, h3 {{ color: #333; }}
576
+ code {{ background: #f4f4f4; padding: 2px 4px; }}
577
+ </style>
578
+ </head>
579
+ <body>
580
+ {html_content}
581
+ </body>
582
+ </html>"""
583
+ output_path.write_text(html_content)
584
+ else:
585
+ return False
586
+
587
+ logger.info(f"Exported template to {output_path} as {format}")
588
+ return True
589
+
590
+ except Exception as e:
591
+ logger.error(f"Export failed: {e}")
592
+ return False
593
+
594
+ def get_section_by_id(self, section_id: str) -> Optional[SectionContent]:
595
+ """Get a specific section by ID."""
596
+ for section in self.sections:
597
+ if section.id == section_id:
598
+ return section
599
+ return None
600
+
601
+ def update_section_content(self, section_id: str, new_content: str) -> bool:
602
+ """Update content for a specific section."""
603
+ section = self.get_section_by_id(section_id)
604
+ if section:
605
+ section.content = new_content
606
+ return True
607
+ return False
608
+
609
+ def get_statistics(self) -> Dict[str, Any]:
610
+ """Get generator statistics."""
611
+ content = self.generate_content()
612
+
613
+ return {
614
+ 'framework_version': self.framework_version,
615
+ 'total_sections': len(self.sections),
616
+ 'required_sections': len([s for s in self.sections if s.required]),
617
+ 'optional_sections': len([s for s in self.sections if not s.required]),
618
+ 'content_length': len(content),
619
+ 'line_count': content.count('\n'),
620
+ 'deployment_targets': list(self.deployment_targets.keys())
621
+ }