claude-mpm 2.0.0__py3-none-any.whl → 2.1.1__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.
claude_mpm/_version.py CHANGED
@@ -1,34 +1,4 @@
1
- """Version information for claude-mpm."""
2
-
3
- try:
4
- # Try to get version from setuptools-scm (when installed as package)
5
- from importlib.metadata import version, PackageNotFoundError
6
- try:
7
- __version__ = version("claude-mpm")
8
- except PackageNotFoundError:
9
- __version__ = "2.0.0"
10
- except ImportError:
11
- # Fallback for older Python versions
12
- __version__ = "2.0.0"
13
-
14
- # This file may be overwritten by setuptools-scm during build
15
- # The try/except ensures we always have a version available
16
-
17
- def get_version_tuple():
18
- """Get version as a tuple of integers."""
19
- parts = __version__.split(".")[:3] # Take only major.minor.patch
20
- try:
21
- return tuple(int(p) for p in parts if p.isdigit())
22
- except:
23
- return (1, 0, 0)
24
-
25
- __version_info__ = get_version_tuple()
26
-
27
- # Version history
28
- # 2.0.0 - BREAKING: Complete agent schema standardization, JSON format, resource tiers
29
- # 1.1.0 - BREAKING: Removed JSON-RPC hooks, enhanced Claude Code hooks with project-specific logging
30
- # 1.0.0 - BREAKING: Architecture simplification, TodoWrite hooks, enhanced CLI, terminal UI
31
- # 0.5.0 - Comprehensive deployment support for PyPI, npm, and local installation
32
- # 0.3.0 - Added hook service architecture for context filtering and ticket automation
33
- # 0.2.0 - Initial interactive subprocess orchestration with pexpect
34
- # 0.1.0 - Basic claude-mpm framework with agent orchestration
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ __version__ = version = '2.1.0'
4
+ __version_tuple__ = version_tuple = (2, 1, 0)
@@ -78,22 +78,7 @@ Context:
78
78
  Priority: <Matches dependent implementation priority>
79
79
  ```
80
80
 
81
- ## Agent Names & Capabilities
82
- **Core Agents**: research, engineer, qa, documentation, security, ops, version-control, data-engineer
83
-
84
- **Agent Name Formats** (both valid):
85
- - Capitalized: "Research", "Engineer", "QA"
86
- - Lowercase-hyphenated: "research", "engineer", "qa"
87
-
88
- **Agent Capabilities**:
89
- - **Research**: Codebase analysis, best practices, technical investigation
90
- - **Engineer**: Implementation, refactoring, debugging
91
- - **QA**: Testing, validation, quality assurance with sign-off authority
92
- - **Documentation**: Technical docs, API documentation, user guides
93
- - **Security**: Security review, vulnerability assessment, compliance
94
- - **Ops**: Deployment, CI/CD, infrastructure, monitoring
95
- - **Version Control**: Git operations, branching, merge conflict resolution
96
- - **Data Engineer**: Database design, ETL pipelines, data modeling
81
+ {{capabilities-list}}
97
82
 
98
83
  ## TodoWrite Requirements
99
84
  **MANDATORY**: Always prefix tasks with [Agent]:
@@ -1,107 +1,75 @@
1
1
  {
2
- "id": "research",
3
- "version": "1.0.0",
2
+ "schema_version": "1.0.0",
3
+ "agent_id": "research_agent",
4
+ "agent_version": "2.1.0",
5
+ "agent_type": "research",
4
6
  "metadata": {
5
7
  "name": "Research Agent",
6
- "description": "Tree-sitter codebase analysis and hierarchical summary generation",
7
- "category": "research",
8
+ "description": "Prescriptive codebase analysis with confidence validation and PM escalation for reliable implementation guidance",
9
+ "created_at": "2025-07-27T03:45:51.485006Z",
10
+ "updated_at": "2025-07-27T10:30:00.000000Z",
8
11
  "tags": [
9
12
  "research",
10
13
  "tree-sitter",
11
14
  "codebase-analysis",
12
- "ast",
13
- "patterns"
15
+ "confidence-validation",
16
+ "pm-escalation"
14
17
  ],
15
- "author": "Claude MPM Team",
16
- "created_at": "2025-07-27T03:45:51.485006Z",
17
- "updated_at": "2025-07-27T03:45:51.485011Z"
18
+ "specializations": [
19
+ "tree-sitter-analysis",
20
+ "confidence-assessment",
21
+ "requirement-validation",
22
+ "pm-escalation"
23
+ ]
18
24
  },
19
25
  "capabilities": {
20
- "model": "claude-sonnet-4-20250514",
26
+ "when_to_use": [
27
+ "Pre-implementation codebase analysis with confidence validation",
28
+ "Technical requirement clarification and validation",
29
+ "Implementation guidance preparation for specialized agents",
30
+ "Risk assessment and constraint identification",
31
+ "PM escalation when information gaps prevent reliable guidance"
32
+ ],
33
+ "specialized_knowledge": [
34
+ "Tree-sitter AST analysis and code structure extraction",
35
+ "Confidence assessment frameworks and escalation protocols",
36
+ "Security pattern recognition and vulnerability assessment",
37
+ "Performance pattern identification and optimization opportunities",
38
+ "PM communication and requirement clarification techniques"
39
+ ],
40
+ "unique_capabilities": [
41
+ "Validate confidence levels before agent delegation",
42
+ "Generate specific questions for PM when information gaps exist",
43
+ "Assess implementation readiness with quantifiable confidence metrics",
44
+ "Create risk-aware analysis with mitigation strategies",
45
+ "Escalate to PM with actionable clarification requests"
46
+ ]
47
+ },
48
+ "configuration": {
49
+ "model": "claude-4-sonnet-20250514",
21
50
  "tools": [
22
51
  "Read",
23
- "Grep",
52
+ "Grep",
24
53
  "Glob",
25
54
  "LS",
26
55
  "WebSearch",
27
56
  "WebFetch",
28
57
  "Bash"
29
58
  ],
30
- "resource_tier": "intensive",
31
- "max_tokens": 12288,
32
- "temperature": 0.2,
33
- "timeout": 900,
34
- "memory_limit": 6144,
35
- "cpu_limit": 80,
36
- "network_access": true,
37
- "file_access": {
38
- "read_paths": [
39
- "./"
40
- ],
41
- "write_paths": [
42
- "./"
43
- ]
44
- }
45
- },
46
- "instructions": "# Research Agent - CODEBASE ANALYSIS SPECIALIST\n\nConduct comprehensive codebase analysis using tree-sitter to generate hierarchical summaries optimized for LLM consumption and agent delegation.\n\n## Core Analysis Protocol\n\n### Phase 1: Repository Structure Analysis (5 min)\n```bash\n# Get overall structure and file inventory\nfind . -name \"*.ts\" -o -name \"*.js\" -o -name \"*.py\" -o -name \"*.java\" -o -name \"*.rb\" -o -name \"*.php\" -o -name \"*.go\" | head -20\ntree -I 'node_modules|.git|dist|build|vendor|gems' -L 3\n```\n\n### Phase 2: Tree-sitter Structural Extraction (10-15 min)\n```bash\n# Parse key files for structural data\ntree-sitter parse [file] --quiet | grep -E \"(function_declaration|class_declaration|interface_declaration|import_statement)\"\n```\n\n### Phase 3: Pattern Detection (5-10 min)\n```bash\n# Security patterns\ngrep -r \"password\\|token\\|auth\\|crypto\\|encrypt\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.py\" --include=\"*.rb\" --include=\"*.php\" --include=\"*.go\" .\n# Performance patterns (JS/TS)\ngrep -r \"async\\|await\\|Promise\" --include=\"*.ts\" --include=\"*.js\" .\n# Performance patterns (Go)\ngrep -r \"goroutine\\|channel\\|sync\\.\" --include=\"*.go\" .\n# Error handling\ngrep -r \"try.*catch\\|throw\\|Error\\|rescue\\|panic\\|recover\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.py\" --include=\"*.rb\" --include=\"*.php\" --include=\"*.go\" .\n```\n\n### Phase 4: Generate Hierarchical Summary\nProduce token-efficient analysis following this structure:\n\n```markdown\n# Tree-sitter Code Analysis Report\n\n## Executive Summary\n- **Codebase**: [Project name]\n- **Primary Language**: [TypeScript/Python/Ruby/PHP/Go/JavaScript/Java]\n- **Architecture**: [MVC/Component-based/Microservices]\n- **Complexity Level**: [Low/Medium/High]\n- **Ready for [Agent Type] Work**: [\u2713/\u26a0\ufe0f/\u274c]\n\n## Key Components Analysis\n### [Critical File 1]\n- **Type**: [Component/Service/Utility]\n- **Size**: [X lines, Y functions, Z classes]\n- **Key Functions**: `funcName()` - [purpose] (lines X-Y)\n- **Patterns**: [Error handling: \u2713/\u26a0\ufe0f/\u274c, Async: \u2713/\u26a0\ufe0f/\u274c]\n\n## Agent-Specific Insights\n### For Security Agent:\n- Authentication mechanisms: [OAuth/JWT/Session]\n- Vulnerability surface: [Input validation, auth flows]\n- Risk areas: [Specific concerns with line numbers]\n\n### For Engineer Agent:\n- Code patterns: [Functional/OOP, async patterns]\n- Refactoring opportunities: [DRY violations, complex functions]\n- Implementation constraints: [Framework limitations, dependencies]\n\n### For QA Agent:\n- Testing infrastructure: [Framework, coverage]\n- Quality gates: [Linting, type checking]\n- Risk areas: [Complex functions, error handling gaps]\n\n## Recommendations\n1. **Immediate**: [Most urgent actions]\n2. **Implementation**: [Specific guidance for Engineer Agent]\n3. **Quality**: [Testing and validation needs]\n```\n\n## Analysis Quality Standards\n- \u2713 Token budget <2K for hierarchical summary\n- \u2713 Agent-specific actionable insights\n- \u2713 File paths and line numbers for reference\n- \u2713 Security and performance concerns highlighted\n- \u2713 Clear implementation recommendations\n\n## Tools Integration\n- Use tree-sitter-cli with language-specific parsers\n- Fallback to regex analysis if parsing fails\n- Focus on exported functions and public APIs\n- Provide partial analysis rather than failing completely",
47
- "knowledge": {
48
- "domain_expertise": [
49
- "Tree-sitter AST analysis and code structure extraction",
50
- "Dependency graph analysis and circular dependency detection",
51
- "Security pattern recognition and vulnerability assessment",
52
- "Performance pattern identification and optimization opportunities",
53
- "Testing infrastructure analysis and coverage assessment"
54
- ],
55
- "best_practices": [
56
- "Generate hierarchical code summaries optimized for LLM consumption",
57
- "Extract semantic patterns from AST structures using tree-sitter",
58
- "Identify critical integration points and API surfaces",
59
- "Synthesize agent-specific actionable insights from codebase analysis",
60
- "Create token-efficient context for specialized agent delegation"
61
- ],
62
- "constraints": [],
63
- "examples": []
64
- },
65
- "interactions": {
66
- "input_format": {
67
- "required_fields": [
68
- "task"
69
- ],
70
- "optional_fields": [
71
- "context",
72
- "constraints"
73
- ]
59
+ "parameters": {
60
+ "temperature": 0.20,
61
+ "max_tokens": 12288
74
62
  },
75
- "output_format": {
76
- "structure": "markdown",
77
- "includes": [
78
- "analysis",
79
- "recommendations",
80
- "code"
81
- ]
63
+ "limits": {
64
+ "timeout": 900,
65
+ "memory_limit": 3072,
66
+ "cpu_limit": 60
82
67
  },
83
- "handoff_agents": [
84
- "engineer",
85
- "qa"
86
- ],
87
- "triggers": []
88
- },
89
- "testing": {
90
- "test_cases": [
91
- {
92
- "name": "Basic research task",
93
- "input": "Perform a basic research analysis",
94
- "expected_behavior": "Agent performs research tasks correctly",
95
- "validation_criteria": [
96
- "completes_task",
97
- "follows_format"
98
- ]
99
- }
100
- ],
101
- "performance_benchmarks": {
102
- "response_time": 300,
103
- "token_usage": 8192,
104
- "success_rate": 0.95
68
+ "permissions": {
69
+ "file_access": "project_only",
70
+ "network_access": true,
71
+ "dangerous_tools": false
105
72
  }
106
- }
73
+ },
74
+ "instructions": "# Research Agent - PRESCRIPTIVE ANALYSIS WITH CONFIDENCE VALIDATION\n\nConduct comprehensive codebase analysis with mandatory confidence validation. If confidence <80%, escalate to PM with specific questions needed to reach analysis threshold.\n\n## MANDATORY CONFIDENCE PROTOCOL\n\n### Confidence Assessment Framework\nAfter each analysis phase, evaluate confidence using this rubric:\n\n**80-100% Confidence (PROCEED)**: \n- All technical requirements clearly understood\n- Implementation patterns and constraints identified\n- Security and performance considerations documented\n- Clear path forward for target agent\n\n**60-79% Confidence (CONDITIONAL)**: \n- Core understanding present but gaps exist\n- Some implementation details unclear\n- Minor ambiguities in requirements\n- **ACTION**: Document gaps and proceed with caveats\n\n**<60% Confidence (ESCALATE)**: \n- Significant knowledge gaps preventing effective analysis\n- Unclear requirements or conflicting information\n- Unable to provide actionable guidance to target agent\n- **ACTION**: MANDATORY escalation to PM with specific questions\n\n### Escalation Protocol\nWhen confidence <80%, use TodoWrite to escalate:\n\n```\n[Research] CONFIDENCE THRESHOLD NOT MET - PM CLARIFICATION REQUIRED\n\nCurrent Confidence: [X]%\nTarget Agent: [Engineer/QA/Security/etc.]\n\nCRITICAL GAPS IDENTIFIED:\n1. [Specific gap 1] - Need: [Specific information needed]\n2. [Specific gap 2] - Need: [Specific information needed]\n3. [Specific gap 3] - Need: [Specific information needed]\n\nQUESTIONS FOR PM TO ASK USER:\n1. [Specific question about requirement/constraint]\n2. [Specific question about technical approach]\n3. [Specific question about integration/dependencies]\n\nIMPACT: Cannot provide reliable guidance to [Target Agent] without this information.\nRISK: Implementation may fail or require significant rework.\n```\n\n## Enhanced Analysis Protocol\n\n### Phase 1: Repository Structure Analysis (5 min)\n```bash\n# Get overall structure and file inventory\nfind . -name \"*.ts\" -o -name \"*.js\" -o -name \"*.py\" -o -name \"*.java\" -o -name \"*.rb\" -o -name \"*.php\" -o -name \"*.go\" | head -20\ntree -I 'node_modules|.git|dist|build|vendor|gems' -L 3\n\n# CONFIDENCE CHECK 1: Can I understand the project structure?\n# Required: Framework identification, file organization, entry points\n```\n\n### Phase 2: Tree-sitter Structural Extraction (10-15 min)\n```bash\n# Parse key files for structural data\ntree-sitter parse [file] --quiet | grep -E \"(function_declaration|class_declaration|interface_declaration|import_statement)\"\n\n# CONFIDENCE CHECK 2: Do I understand the code patterns and architecture?\n# Required: Component relationships, data flow, integration points\n```\n\n### Phase 3: Requirement Validation (5-10 min)\n```bash\n# Security patterns\ngrep -r \"password\\|token\\|auth\\|crypto\\|encrypt\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.py\" --include=\"*.rb\" --include=\"*.php\" --include=\"*.go\" .\n# Performance patterns\ngrep -r \"async\\|await\\|Promise\\|goroutine\\|channel\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.go\" .\n# Error handling\ngrep -r \"try.*catch\\|throw\\|Error\\|rescue\\|panic\\|recover\" --include=\"*.ts\" --include=\"*.js\" --include=\"*.py\" --include=\"*.rb\" --include=\"*.php\" --include=\"*.go\" .\n\n# CONFIDENCE CHECK 3: Do I understand the specific task requirements?\n# Required: Clear understanding of what needs to be implemented/fixed/analyzed\n```\n\n### Phase 4: Target Agent Preparation Assessment\n```bash\n# Assess readiness for specific agent delegation\n# For Engineer Agent: Implementation patterns, constraints, dependencies\n# For QA Agent: Testing infrastructure, validation requirements\n# For Security Agent: Attack surfaces, authentication flows, data handling\n\n# CONFIDENCE CHECK 4: Can I provide actionable guidance to the target agent?\n# Required: Specific recommendations, clear constraints, risk identification\n```\n\n### Phase 5: Final Confidence Evaluation\n**MANDATORY**: Before generating final report, assess overall confidence:\n\n1. **Technical Understanding**: Do I understand the codebase structure and patterns? [1-10]\n2. **Requirement Clarity**: Are the task requirements clear and unambiguous? [1-10]\n3. **Implementation Path**: Can I provide clear guidance for the target agent? [1-10]\n4. **Risk Assessment**: Have I identified the key risks and constraints? [1-10]\n5. **Context Completeness**: Do I have all necessary context for success? [1-10]\n\n**Overall Confidence**: (Sum / 5) * 10 = [X]%\n\n**Decision Matrix**:\n- 80-100%: Generate report and delegate\n- 60-79%: Generate report with clear caveats\n- <60%: ESCALATE to PM immediately\n\n## Enhanced Output Format\n\n```markdown\n# Tree-sitter Code Analysis Report\n\n## CONFIDENCE ASSESSMENT\n- **Overall Confidence**: [X]% \n- **Technical Understanding**: [X]/10\n- **Requirement Clarity**: [X]/10 \n- **Implementation Path**: [X]/10\n- **Risk Assessment**: [X]/10\n- **Context Completeness**: [X]/10\n- **Status**: [PROCEED/CONDITIONAL/ESCALATED]\n\n## Executive Summary\n- **Codebase**: [Project name]\n- **Primary Language**: [TypeScript/Python/Ruby/PHP/Go/JavaScript/Java]\n- **Architecture**: [MVC/Component-based/Microservices]\n- **Complexity Level**: [Low/Medium/High]\n- **Ready for [Agent Type] Work**: [✓/⚠️/❌]\n- **Confidence Level**: [High/Medium/Low]\n\n## Key Components Analysis\n### [Critical File 1]\n- **Type**: [Component/Service/Utility]\n- **Size**: [X lines, Y functions, Z classes]\n- **Key Functions**: `funcName()` - [purpose] (lines X-Y)\n- **Patterns**: [Error handling: ✓/⚠️/❌, Async: ✓/⚠️/❌]\n- **Confidence**: [High/Medium/Low] - [Rationale]\n\n## Agent-Specific Guidance\n### For [Target Agent]:\n**Confidence Level**: [X]%\n\n**Clear Requirements**:\n1. [Specific requirement 1] - [Confidence: High/Medium/Low]\n2. [Specific requirement 2] - [Confidence: High/Medium/Low]\n\n**Implementation Constraints**:\n1. [Technical constraint 1] - [Impact level]\n2. [Business constraint 2] - [Impact level]\n\n**Risk Areas**:\n1. [Risk 1] - [Likelihood/Impact] - [Mitigation strategy]\n2. [Risk 2] - [Likelihood/Impact] - [Mitigation strategy]\n\n**Success Criteria**:\n1. [Measurable outcome 1]\n2. [Measurable outcome 2]\n\n## KNOWLEDGE GAPS (if confidence <80%)\n### Unresolved Questions:\n1. [Question about requirement/constraint]\n2. [Question about technical approach]\n3. [Question about integration/dependencies]\n\n### Information Needed:\n1. [Specific information needed for confident analysis]\n2. [Additional context required]\n\n### Escalation Required:\n[YES/NO] - If YES, see TodoWrite escalation above\n\n## Recommendations\n1. **Immediate**: [Most urgent actions with confidence level]\n2. **Implementation**: [Specific guidance for target agent with confidence level]\n3. **Quality**: [Testing and validation needs with confidence level]\n4. **Risk Mitigation**: [Address identified uncertainties]\n```\n\n## Quality Standards\n- ✓ Confidence assessment completed for each phase\n- ✓ Overall confidence ≥80% OR escalation to PM\n- ✓ Agent-specific actionable insights with confidence levels\n- ✓ File paths and line numbers for reference\n- ✓ Security and performance concerns highlighted\n- ✓ Clear implementation recommendations with risk assessment\n- ✓ Knowledge gaps explicitly documented\n- ✓ Success criteria defined for target agent\n\n## Escalation Triggers\n- Confidence <80% on any critical aspect\n- Ambiguous or conflicting requirements\n- Missing technical context needed for implementation\n- Unclear success criteria or acceptance criteria\n- Unknown integration constraints or dependencies\n- Security implications not fully understood\n- Performance requirements unclear or unmeasurable"
107
75
  }
claude_mpm/cli.py CHANGED
@@ -323,6 +323,74 @@ def _get_user_input(args, logger):
323
323
  return sys.stdin.read()
324
324
 
325
325
 
326
+ def _get_agent_versions_display():
327
+ """Get formatted agent versions display as a string.
328
+
329
+ WHY: This function was created to provide a single source of truth for agent version
330
+ information that can be displayed both at startup and on-demand via the /mpm agents command.
331
+ This ensures consistency in how agent versions are presented to users.
332
+
333
+ Returns:
334
+ str: Formatted string containing agent version information, or None if failed
335
+ """
336
+ try:
337
+ from .services.agent_deployment import AgentDeploymentService
338
+ deployment_service = AgentDeploymentService()
339
+
340
+ # Get deployed agents
341
+ verification = deployment_service.verify_deployment()
342
+ if not verification.get("agents_found"):
343
+ return None
344
+
345
+ output_lines = []
346
+ output_lines.append("\nDeployed Agent Versions:")
347
+ output_lines.append("-" * 40)
348
+
349
+ # Sort agents by name for consistent display
350
+ agents = sorted(verification["agents_found"], key=lambda x: x.get('name', x.get('file', '')))
351
+
352
+ for agent in agents:
353
+ name = agent.get('name', 'unknown')
354
+ version = agent.get('version', 'unknown')
355
+ # Format: name (version)
356
+ output_lines.append(f" {name:<20} {version}")
357
+
358
+ # Add base agent version info
359
+ try:
360
+ import json
361
+ base_agent_path = deployment_service.base_agent_path
362
+ if base_agent_path.exists():
363
+ base_data = json.loads(base_agent_path.read_text())
364
+ # Parse version the same way as AgentDeploymentService
365
+ raw_version = base_data.get('base_version') or base_data.get('version', 0)
366
+ base_version_tuple = deployment_service._parse_version(raw_version)
367
+ base_version_str = deployment_service._format_version_display(base_version_tuple)
368
+ output_lines.append(f"\n Base Agent Version: {base_version_str}")
369
+ except:
370
+ pass
371
+
372
+ # Check for agents needing migration
373
+ if verification.get("agents_needing_migration"):
374
+ output_lines.append(f"\n ⚠️ {len(verification['agents_needing_migration'])} agent(s) need migration to semantic versioning")
375
+ output_lines.append(f" Run 'claude-mpm agents deploy' to update")
376
+
377
+ output_lines.append("-" * 40)
378
+ return "\n".join(output_lines)
379
+ except Exception as e:
380
+ # Log error but don't fail
381
+ logger = get_logger("cli")
382
+ logger.debug(f"Failed to get agent versions: {e}")
383
+ return None
384
+
385
+
386
+ def _list_agent_versions_at_startup():
387
+ """List deployed agent versions at startup."""
388
+ agent_versions = _get_agent_versions_display()
389
+ if agent_versions:
390
+ print(agent_versions)
391
+ print() # Extra newline after the display
392
+
393
+
326
394
 
327
395
 
328
396
  def run_session(args):
@@ -339,6 +407,9 @@ def run_session(args):
339
407
  # Skip native agents if disabled
340
408
  if getattr(args, 'no_native_agents', False):
341
409
  print("Native agents disabled")
410
+ else:
411
+ # List deployed agent versions at startup
412
+ _list_agent_versions_at_startup()
342
413
 
343
414
  # Create simple runner
344
415
  enable_tickets = not args.no_tickets
@@ -420,17 +491,15 @@ def manage_agents(args):
420
491
  deployment_service = AgentDeploymentService()
421
492
 
422
493
  if not args.agents_command:
423
- print("Error: No agent command specified")
424
- print("\nUsage: claude-mpm --mpm:agents <command> [options]")
425
- print("\nAvailable commands:")
426
- print(" list - List available agents")
427
- print(" deploy - Deploy system agents")
428
- print(" force-deploy - Force deploy all system agents")
429
- print(" clean - Remove deployed system agents")
430
- print("\nExamples:")
431
- print(" claude-mpm --mpm:agents list --system")
432
- print(" claude-mpm --mpm:agents deploy")
433
- print(" claude-mpm --mpm:agents force-deploy")
494
+ # When no subcommand is provided, display agent versions
495
+ # WHY: This provides a quick way for users to check deployed agent versions
496
+ # without needing to specify additional subcommands, matching the startup display
497
+ agent_versions = _get_agent_versions_display()
498
+ if agent_versions:
499
+ print(agent_versions)
500
+ else:
501
+ print("No deployed agents found")
502
+ print("\nTo deploy agents, run: claude-mpm --mpm:agents deploy")
434
503
  return
435
504
 
436
505
  if args.agents_command == AgentCommands.LIST.value:
@@ -417,7 +417,11 @@ class SimpleClaudeRunner:
417
417
  self.logger.debug(f"Ticket extraction failed: {e}")
418
418
 
419
419
  def _load_system_instructions(self) -> Optional[str]:
420
- """Load system instructions from agents/INSTRUCTIONS.md."""
420
+ """Load and process system instructions from agents/INSTRUCTIONS.md.
421
+
422
+ WHY: Process template variables like {{capabilities-list}} to include
423
+ dynamic agent capabilities in the PM's system instructions.
424
+ """
421
425
  try:
422
426
  # Find the INSTRUCTIONS.md file
423
427
  module_path = Path(__file__).parent.parent
@@ -427,9 +431,22 @@ class SimpleClaudeRunner:
427
431
  self.logger.warning(f"System instructions not found: {instructions_path}")
428
432
  return None
429
433
 
430
- instructions = instructions_path.read_text()
431
- self.logger.info("Loaded PM framework system instructions")
432
- return instructions
434
+ # Read raw instructions
435
+ raw_instructions = instructions_path.read_text()
436
+
437
+ # Process template variables if ContentAssembler is available
438
+ try:
439
+ from claude_mpm.services.framework_claude_md_generator.content_assembler import ContentAssembler
440
+ assembler = ContentAssembler()
441
+ processed_instructions = assembler.apply_template_variables(raw_instructions)
442
+ self.logger.info("Loaded and processed PM framework system instructions with dynamic capabilities")
443
+ return processed_instructions
444
+ except ImportError:
445
+ self.logger.warning("ContentAssembler not available, using raw instructions")
446
+ return raw_instructions
447
+ except Exception as e:
448
+ self.logger.warning(f"Failed to process template variables: {e}, using raw instructions")
449
+ return raw_instructions
433
450
 
434
451
  except Exception as e:
435
452
  self.logger.error(f"Failed to load system instructions: {e}")
@@ -488,9 +505,32 @@ class SimpleClaudeRunner:
488
505
  component="command"
489
506
  )
490
507
  return True
508
+ elif command == "agents":
509
+ # Handle agents command - display deployed agent versions
510
+ # WHY: This provides users with a quick way to check deployed agent versions
511
+ # directly from within Claude Code, maintaining consistency with CLI behavior
512
+ try:
513
+ from claude_mpm.cli import _get_agent_versions_display
514
+ agent_versions = _get_agent_versions_display()
515
+ if agent_versions:
516
+ print(agent_versions)
517
+ else:
518
+ print("No deployed agents found")
519
+ print("\nTo deploy agents, run: claude-mpm --mpm:agents deploy")
520
+
521
+ if self.project_logger:
522
+ self.project_logger.log_system(
523
+ "Executed /mpm:agents command",
524
+ level="INFO",
525
+ component="command"
526
+ )
527
+ return True
528
+ except Exception as e:
529
+ print(f"Error getting agent versions: {e}")
530
+ return False
491
531
  else:
492
532
  print(f"Unknown command: {command}")
493
- print("Available commands: test")
533
+ print("Available commands: test, agents")
494
534
  return True
495
535
 
496
536
  except Exception as e:
@@ -34,6 +34,7 @@ class ClaudeHookHandler:
34
34
  # Available MPM arguments
35
35
  self.mpm_args = {
36
36
  'status': 'Show claude-mpm system status',
37
+ 'agents': 'Show deployed agent versions',
37
38
  # Add more arguments here as they're implemented
38
39
  # 'config': 'Configure claude-mpm settings',
39
40
  # 'debug': 'Toggle debug mode',
@@ -200,6 +201,9 @@ class ClaudeHookHandler:
200
201
  # Extract status args if any
201
202
  status_args = arg[6:].strip() if arg.startswith('status ') else ''
202
203
  return self._handle_mpm_status(status_args)
204
+ elif arg == 'agents' or arg.startswith('agents '):
205
+ # Handle agents command
206
+ return self._handle_mpm_agents()
203
207
  else:
204
208
  # Show help for empty or unknown argument
205
209
  return self._handle_mpm_help(arg)
@@ -215,7 +219,80 @@ class ClaudeHookHandler:
215
219
 
216
220
  def _handle_pre_tool_use(self):
217
221
  """Handle PreToolUse events."""
218
- # For now, just log and continue
222
+ tool_name = self.event.get('tool_name', '')
223
+ tool_input = self.event.get('tool_input', {})
224
+
225
+ # List of tools that perform write operations
226
+ write_tools = ['Write', 'Edit', 'MultiEdit', 'NotebookEdit']
227
+
228
+ # Check if this is a write operation
229
+ if tool_name in write_tools:
230
+ # Get the working directory from the event
231
+ working_dir = Path(self.event.get('cwd', os.getcwd())).resolve()
232
+
233
+ # Extract file path based on tool type
234
+ file_path = None
235
+ if tool_name in ['Write', 'Edit', 'NotebookEdit']:
236
+ file_path = tool_input.get('file_path')
237
+ if tool_name == 'NotebookEdit':
238
+ file_path = tool_input.get('notebook_path')
239
+ elif tool_name == 'MultiEdit':
240
+ file_path = tool_input.get('file_path')
241
+
242
+ if file_path:
243
+ # First check for path traversal attempts before resolving
244
+ if '..' in str(file_path):
245
+ if logger:
246
+ logger.warning(f"Security: Potential path traversal attempt in {tool_name}: {file_path}")
247
+ response = {
248
+ "action": "block",
249
+ "error": f"Security Policy: Path traversal attempts are not allowed.\n\n"
250
+ f"The path '{file_path}' contains '..' which could be used to escape the working directory.\n"
251
+ f"Please use absolute paths or paths relative to the working directory without '..'."
252
+ }
253
+ print(json.dumps(response))
254
+ sys.exit(0)
255
+ return
256
+
257
+ try:
258
+ # Resolve the file path to absolute path
259
+ target_path = Path(file_path).resolve()
260
+
261
+ # Check if the target path is within the working directory
262
+ try:
263
+ target_path.relative_to(working_dir)
264
+ except ValueError:
265
+ # Path is outside working directory
266
+ if logger:
267
+ logger.warning(f"Security: Blocked {tool_name} operation outside working directory: {file_path}")
268
+
269
+ # Return block action with helpful error message
270
+ response = {
271
+ "action": "block",
272
+ "error": f"Security Policy: Cannot write to files outside the working directory.\n\n"
273
+ f"Working directory: {working_dir}\n"
274
+ f"Attempted path: {file_path}\n\n"
275
+ f"Please ensure all file operations are within the project directory."
276
+ }
277
+ print(json.dumps(response))
278
+ sys.exit(0)
279
+ return
280
+
281
+
282
+ except Exception as e:
283
+ if logger:
284
+ logger.error(f"Error validating path in {tool_name}: {e}")
285
+ # In case of error, err on the side of caution and block
286
+ response = {
287
+ "action": "block",
288
+ "error": f"Error validating file path: {str(e)}\n\n"
289
+ f"Please ensure the path is valid and accessible."
290
+ }
291
+ print(json.dumps(response))
292
+ sys.exit(0)
293
+ return
294
+
295
+ # For read operations and other tools, continue normally
219
296
  return self._continue()
220
297
 
221
298
  def _handle_post_tool_use(self):
@@ -349,6 +426,42 @@ class ClaudeHookHandler:
349
426
 
350
427
  return output
351
428
 
429
+ def _handle_mpm_agents(self):
430
+ """Handle the /mpm agents command to display deployed agent versions.
431
+
432
+ WHY: This provides users with a quick way to check deployed agent versions
433
+ directly from within Claude Code, maintaining consistency with the CLI
434
+ and startup display functionality.
435
+ """
436
+ try:
437
+ # Import the agent version display function
438
+ from claude_mpm.cli import _get_agent_versions_display
439
+
440
+ # Get the formatted agent versions
441
+ agent_versions = _get_agent_versions_display()
442
+
443
+ if agent_versions:
444
+ # Display the agent versions
445
+ print(agent_versions, file=sys.stderr)
446
+ else:
447
+ # No agents found
448
+ output = "\nNo deployed agents found\n"
449
+ output += "\nTo deploy agents, run: claude-mpm --mpm:agents deploy\n"
450
+ print(output, file=sys.stderr)
451
+
452
+ except Exception as e:
453
+ # Handle any errors gracefully
454
+ output = f"\nError getting agent versions: {e}\n"
455
+ output += "\nPlease check your claude-mpm installation.\n"
456
+ print(output, file=sys.stderr)
457
+
458
+ # Log the error for debugging
459
+ if logger:
460
+ logger.error(f"Error in _handle_mpm_agents: {e}")
461
+
462
+ # Block LLM processing since we've handled the command
463
+ sys.exit(2)
464
+
352
465
  def _handle_mpm_help(self, unknown_arg=None):
353
466
  """Show help for MPM commands."""
354
467
  # ANSI colors
@@ -375,6 +488,7 @@ class ClaudeHookHandler:
375
488
  output += f" /mpm - Show this help\n"
376
489
  output += f" /mpm status - Show system status\n"
377
490
  output += f" /mpm status --verbose - Show detailed status\n"
491
+ output += f" /mpm agents - Show deployed agent versions\n"
378
492
 
379
493
  output += f"\n{DIM}{'─' * 60}{RESET}"
380
494