claude-mpm 3.3.2__py3-none-any.whl → 3.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 (40) hide show
  1. claude_mpm/cli/commands/memory.py +186 -13
  2. claude_mpm/cli/parser.py +13 -1
  3. claude_mpm/constants.py +1 -0
  4. claude_mpm/core/claude_runner.py +61 -0
  5. claude_mpm/core/config.py +1 -1
  6. claude_mpm/core/simple_runner.py +61 -0
  7. claude_mpm/hooks/builtin/mpm_command_hook.py +5 -5
  8. claude_mpm/hooks/claude_hooks/hook_handler.py +211 -4
  9. claude_mpm/hooks/claude_hooks/hook_wrapper.sh +9 -2
  10. claude_mpm/hooks/memory_integration_hook.py +51 -5
  11. claude_mpm/services/__init__.py +23 -5
  12. claude_mpm/services/agent_memory_manager.py +536 -48
  13. claude_mpm/services/memory_builder.py +338 -6
  14. claude_mpm/services/project_analyzer.py +771 -0
  15. claude_mpm/services/socketio_server.py +473 -33
  16. claude_mpm/services/version_control/git_operations.py +26 -0
  17. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/METADATA +34 -10
  18. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/RECORD +22 -39
  19. claude_mpm/agents/agent-template.yaml +0 -83
  20. claude_mpm/agents/test_fix_deployment/.claude-pm/config/project.json +0 -6
  21. claude_mpm/cli/README.md +0 -109
  22. claude_mpm/cli_module/refactoring_guide.md +0 -253
  23. claude_mpm/core/agent_registry.py.bak +0 -312
  24. claude_mpm/core/base_service.py.bak +0 -406
  25. claude_mpm/hooks/README.md +0 -97
  26. claude_mpm/orchestration/SUBPROCESS_DESIGN.md +0 -66
  27. claude_mpm/schemas/README_SECURITY.md +0 -92
  28. claude_mpm/schemas/agent_schema.json +0 -395
  29. claude_mpm/schemas/agent_schema_documentation.md +0 -181
  30. claude_mpm/schemas/agent_schema_security_notes.md +0 -165
  31. claude_mpm/schemas/examples/standard_workflow.json +0 -505
  32. claude_mpm/schemas/ticket_workflow_documentation.md +0 -482
  33. claude_mpm/schemas/ticket_workflow_schema.json +0 -590
  34. claude_mpm/services/framework_claude_md_generator/README.md +0 -92
  35. claude_mpm/services/parent_directory_manager/README.md +0 -83
  36. claude_mpm/services/version_control/VERSION +0 -1
  37. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/WHEEL +0 -0
  38. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/entry_points.txt +0 -0
  39. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/licenses/LICENSE +0 -0
  40. {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.0.dist-info}/top_level.txt +0 -0
@@ -20,9 +20,33 @@ from datetime import datetime
20
20
  from pathlib import Path
21
21
  from collections import deque
22
22
 
23
- # Quick environment check
23
+ # Quick environment check - must be defined before any code that might use it
24
24
  DEBUG = os.environ.get('CLAUDE_MPM_HOOK_DEBUG', '').lower() == 'true'
25
25
 
26
+ # Add imports for memory hook integration with comprehensive error handling
27
+ MEMORY_HOOKS_AVAILABLE = False
28
+ try:
29
+ # Try to add src to path if not already there (fallback for missing PYTHONPATH)
30
+ import sys
31
+ from pathlib import Path
32
+ src_path = Path(__file__).parent.parent.parent.parent
33
+ if src_path.exists() and str(src_path) not in sys.path:
34
+ sys.path.insert(0, str(src_path))
35
+
36
+ from claude_mpm.services.hook_service import HookService
37
+ from claude_mpm.hooks.memory_integration_hook import (
38
+ MemoryPreDelegationHook,
39
+ MemoryPostDelegationHook
40
+ )
41
+ from claude_mpm.hooks.base_hook import HookContext, HookType
42
+ from claude_mpm.core.config import Config
43
+ MEMORY_HOOKS_AVAILABLE = True
44
+ except Exception as e:
45
+ # Catch all exceptions to prevent any import errors from breaking the handler
46
+ if DEBUG:
47
+ print(f"Memory hooks not available: {e}", file=sys.stderr)
48
+ MEMORY_HOOKS_AVAILABLE = False
49
+
26
50
  # Socket.IO import
27
51
  try:
28
52
  import socketio
@@ -59,6 +83,13 @@ class ClaudeHookHandler:
59
83
  self._git_branch_cache = {}
60
84
  self._git_branch_cache_time = {}
61
85
 
86
+ # Initialize memory hooks if available
87
+ self.memory_hooks_initialized = False
88
+ self.pre_delegation_hook = None
89
+ self.post_delegation_hook = None
90
+ if MEMORY_HOOKS_AVAILABLE:
91
+ self._initialize_memory_hooks()
92
+
62
93
  # No fallback server needed - we only use Socket.IO now
63
94
 
64
95
  def _track_delegation(self, session_id: str, agent_type: str):
@@ -100,6 +131,49 @@ class ClaudeHookHandler:
100
131
 
101
132
  return 'unknown'
102
133
 
134
+ def _initialize_memory_hooks(self):
135
+ """Initialize memory hooks for automatic agent memory management.
136
+
137
+ WHY: This activates the memory system by connecting Claude Code hook events
138
+ to our memory integration hooks. This enables automatic memory injection
139
+ before delegations and learning extraction after delegations.
140
+
141
+ DESIGN DECISION: We initialize hooks here in the Claude hook handler because
142
+ this is where Claude Code events are processed. This ensures memory hooks
143
+ are triggered at the right times during agent delegation.
144
+ """
145
+ try:
146
+ # Create configuration
147
+ config = Config()
148
+
149
+ # Only initialize if memory system is enabled
150
+ if not config.get('memory.enabled', True):
151
+ if DEBUG:
152
+ print("Memory system disabled - skipping hook initialization", file=sys.stderr)
153
+ return
154
+
155
+ # Initialize pre-delegation hook for memory injection
156
+ self.pre_delegation_hook = MemoryPreDelegationHook(config)
157
+
158
+ # Initialize post-delegation hook if auto-learning is enabled
159
+ if config.get('memory.auto_learning', True): # Default to True now
160
+ self.post_delegation_hook = MemoryPostDelegationHook(config)
161
+
162
+ self.memory_hooks_initialized = True
163
+
164
+ if DEBUG:
165
+ hooks_info = []
166
+ if self.pre_delegation_hook:
167
+ hooks_info.append("pre-delegation")
168
+ if self.post_delegation_hook:
169
+ hooks_info.append("post-delegation")
170
+ print(f"✅ Memory hooks initialized: {', '.join(hooks_info)}", file=sys.stderr)
171
+
172
+ except Exception as e:
173
+ if DEBUG:
174
+ print(f"❌ Failed to initialize memory hooks: {e}", file=sys.stderr)
175
+ # Don't fail the entire handler - memory system is optional
176
+
103
177
  def _get_git_branch(self, working_dir: str = None) -> str:
104
178
  """Get git branch for the given directory with caching.
105
179
 
@@ -366,6 +440,9 @@ class ClaudeHookHandler:
366
440
  session_id = event.get('session_id', '')
367
441
  if session_id and agent_type != 'unknown':
368
442
  self._track_delegation(session_id, agent_type)
443
+
444
+ # Trigger memory pre-delegation hook
445
+ self._trigger_memory_pre_delegation_hook(agent_type, tool_input, session_id)
369
446
 
370
447
  self._emit_socketio_event('/hook', 'pre_tool', pre_tool_data)
371
448
 
@@ -407,6 +484,12 @@ class ClaudeHookHandler:
407
484
  'output_size': len(str(result_data.get('output', ''))) if result_data.get('output') else 0
408
485
  }
409
486
 
487
+ # Handle Task delegation completion for memory hooks
488
+ if tool_name == 'Task':
489
+ session_id = event.get('session_id', '')
490
+ agent_type = self._get_delegation_agent_type(session_id)
491
+ self._trigger_memory_post_delegation_hook(agent_type, event, session_id)
492
+
410
493
  self._emit_socketio_event('/hook', 'post_tool', post_tool_data)
411
494
 
412
495
  def _extract_tool_parameters(self, tool_name: str, tool_input: dict) -> dict:
@@ -711,6 +794,122 @@ class ClaudeHookHandler:
711
794
  # Emit to /hook namespace
712
795
  self._emit_socketio_event('/hook', 'subagent_stop', subagent_stop_data)
713
796
 
797
+ def _trigger_memory_pre_delegation_hook(self, agent_type: str, tool_input: dict, session_id: str):
798
+ """Trigger memory pre-delegation hook for agent memory injection.
799
+
800
+ WHY: This connects Claude Code's Task delegation events to our memory system.
801
+ When Claude is about to delegate to an agent, we inject the agent's memory
802
+ into the delegation context so the agent has access to accumulated knowledge.
803
+
804
+ DESIGN DECISION: We modify the tool_input in place to inject memory context.
805
+ This ensures the agent receives the memory as part of their initial context.
806
+ """
807
+ if not self.memory_hooks_initialized or not self.pre_delegation_hook:
808
+ return
809
+
810
+ try:
811
+ # Create hook context for memory injection
812
+ hook_context = HookContext(
813
+ hook_type=HookType.PRE_DELEGATION,
814
+ data={
815
+ 'agent': agent_type,
816
+ 'context': tool_input,
817
+ 'session_id': session_id
818
+ },
819
+ metadata={
820
+ 'source': 'claude_hook_handler',
821
+ 'tool_name': 'Task'
822
+ },
823
+ timestamp=datetime.now().isoformat(),
824
+ session_id=session_id
825
+ )
826
+
827
+ # Execute pre-delegation hook
828
+ result = self.pre_delegation_hook.execute(hook_context)
829
+
830
+ if result.success and result.modified and result.data:
831
+ # Update tool_input with memory-enhanced context
832
+ enhanced_context = result.data.get('context', {})
833
+ if enhanced_context and 'agent_memory' in enhanced_context:
834
+ # Inject memory into the task prompt/description
835
+ original_prompt = tool_input.get('prompt', '')
836
+ memory_section = enhanced_context['agent_memory']
837
+
838
+ # Prepend memory to the original prompt
839
+ enhanced_prompt = f"{memory_section}\n\n{original_prompt}"
840
+ tool_input['prompt'] = enhanced_prompt
841
+
842
+ if DEBUG:
843
+ memory_size = len(memory_section.encode('utf-8'))
844
+ print(f"✅ Injected {memory_size} bytes of memory for agent '{agent_type}'", file=sys.stderr)
845
+
846
+ except Exception as e:
847
+ if DEBUG:
848
+ print(f"❌ Memory pre-delegation hook failed: {e}", file=sys.stderr)
849
+ # Don't fail the delegation - memory is optional
850
+
851
+ def _trigger_memory_post_delegation_hook(self, agent_type: str, event: dict, session_id: str):
852
+ """Trigger memory post-delegation hook for learning extraction.
853
+
854
+ WHY: This connects Claude Code's Task completion events to our memory system.
855
+ When an agent completes a task, we extract learnings from the result and
856
+ store them in the agent's memory for future use.
857
+
858
+ DESIGN DECISION: We extract learnings from both the tool output and any
859
+ error messages, providing comprehensive context for the memory system.
860
+ """
861
+ if not self.memory_hooks_initialized or not self.post_delegation_hook:
862
+ return
863
+
864
+ try:
865
+ # Extract result content from the event
866
+ result_content = ""
867
+ output = event.get('output', '')
868
+ error = event.get('error', '')
869
+ exit_code = event.get('exit_code', 0)
870
+
871
+ # Build result content
872
+ if output:
873
+ result_content = str(output)
874
+ elif error:
875
+ result_content = f"Error: {str(error)}"
876
+ else:
877
+ result_content = f"Task completed with exit code: {exit_code}"
878
+
879
+ # Create hook context for learning extraction
880
+ hook_context = HookContext(
881
+ hook_type=HookType.POST_DELEGATION,
882
+ data={
883
+ 'agent': agent_type,
884
+ 'result': {
885
+ 'content': result_content,
886
+ 'success': exit_code == 0,
887
+ 'exit_code': exit_code
888
+ },
889
+ 'session_id': session_id
890
+ },
891
+ metadata={
892
+ 'source': 'claude_hook_handler',
893
+ 'tool_name': 'Task',
894
+ 'duration_ms': event.get('duration_ms', 0)
895
+ },
896
+ timestamp=datetime.now().isoformat(),
897
+ session_id=session_id
898
+ )
899
+
900
+ # Execute post-delegation hook
901
+ result = self.post_delegation_hook.execute(hook_context)
902
+
903
+ if result.success and result.metadata:
904
+ learnings_extracted = result.metadata.get('learnings_extracted', 0)
905
+ if learnings_extracted > 0 and DEBUG:
906
+ print(f"✅ Extracted {learnings_extracted} learnings for agent '{agent_type}'", file=sys.stderr)
907
+
908
+ except Exception as e:
909
+ if DEBUG:
910
+ print(f"❌ Memory post-delegation hook failed: {e}", file=sys.stderr)
911
+ # Don't fail the delegation result - memory is optional
912
+
714
913
  def __del__(self):
715
914
  """Cleanup Socket.IO client on handler destruction."""
716
915
  if self.sio_client and self.sio_connected:
@@ -721,9 +920,17 @@ class ClaudeHookHandler:
721
920
 
722
921
 
723
922
  def main():
724
- """Entry point."""
725
- handler = ClaudeHookHandler()
726
- handler.handle()
923
+ """Entry point with comprehensive error handling."""
924
+ try:
925
+ handler = ClaudeHookHandler()
926
+ handler.handle()
927
+ except Exception as e:
928
+ # Always output continue action to not block Claude
929
+ print(json.dumps({"action": "continue"}))
930
+ # Log error for debugging
931
+ if DEBUG:
932
+ print(f"Hook handler error: {e}", file=sys.stderr)
933
+ sys.exit(0) # Exit cleanly even on error
727
934
 
728
935
 
729
936
  if __name__ == "__main__":
@@ -48,5 +48,12 @@ echo "[$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)] PYTHONPATH: $PYTHONPATH" >> /tmp/hook
48
48
  echo "[$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)] Running: $PYTHON_CMD $SCRIPT_DIR/hook_handler.py" >> /tmp/hook-wrapper.log
49
49
  echo "[$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)] SOCKETIO_PORT: $CLAUDE_MPM_SOCKETIO_PORT" >> /tmp/hook-wrapper.log
50
50
 
51
- # Run the Python hook handler (now optimized by default)
52
- exec "$PYTHON_CMD" "$SCRIPT_DIR/hook_handler.py" "$@"
51
+ # Run the Python hook handler with error handling
52
+ # Use exec to replace the shell process, but wrap in error handling
53
+ if ! "$PYTHON_CMD" "$SCRIPT_DIR/hook_handler.py" "$@" 2>/tmp/hook-error.log; then
54
+ # If the Python handler fails, always return continue to not block Claude
55
+ echo '{"action": "continue"}'
56
+ # Log the error for debugging
57
+ echo "[$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)] Hook handler failed, see /tmp/hook-error.log" >> /tmp/hook-wrapper.log
58
+ exit 0
59
+ fi
@@ -15,13 +15,29 @@ agent outputs because:
15
15
  import re
16
16
  from typing import Dict, Any, List
17
17
  from claude_mpm.hooks.base_hook import PreDelegationHook, PostDelegationHook, HookContext, HookResult
18
- from claude_mpm.services.agent_memory_manager import AgentMemoryManager
19
- from claude_mpm.services.socketio_server import get_socketio_server
20
18
  from claude_mpm.core.config import Config
21
19
  from claude_mpm.core.logger import get_logger
22
20
 
23
21
  logger = get_logger(__name__)
24
22
 
23
+ # Try to import memory manager with fallback handling
24
+ try:
25
+ from claude_mpm.services.agent_memory_manager import AgentMemoryManager
26
+ MEMORY_MANAGER_AVAILABLE = True
27
+ except ImportError as e:
28
+ logger.warning(f"AgentMemoryManager not available: {e}")
29
+ MEMORY_MANAGER_AVAILABLE = False
30
+ AgentMemoryManager = None
31
+
32
+ # Try to import socketio server with fallback handling
33
+ try:
34
+ from claude_mpm.services.socketio_server import get_socketio_server
35
+ SOCKETIO_AVAILABLE = True
36
+ except ImportError as e:
37
+ logger.debug(f"SocketIO server not available: {e}")
38
+ SOCKETIO_AVAILABLE = False
39
+ get_socketio_server = None
40
+
25
41
 
26
42
  class MemoryPreDelegationHook(PreDelegationHook):
27
43
  """Inject agent memory into delegation context.
@@ -42,7 +58,17 @@ class MemoryPreDelegationHook(PreDelegationHook):
42
58
  """
43
59
  super().__init__(name="memory_pre_delegation", priority=20)
44
60
  self.config = config or Config()
45
- self.memory_manager = AgentMemoryManager(self.config)
61
+
62
+ # Initialize memory manager only if available
63
+ if MEMORY_MANAGER_AVAILABLE and AgentMemoryManager:
64
+ try:
65
+ self.memory_manager = AgentMemoryManager(self.config)
66
+ except Exception as e:
67
+ logger.error(f"Failed to initialize AgentMemoryManager: {e}")
68
+ self.memory_manager = None
69
+ else:
70
+ logger.info("Memory manager not available - hook will be inactive")
71
+ self.memory_manager = None
46
72
 
47
73
  def execute(self, context: HookContext) -> HookResult:
48
74
  """Add agent memory to delegation context.
@@ -50,6 +76,11 @@ class MemoryPreDelegationHook(PreDelegationHook):
50
76
  WHY: By loading memory before delegation, agents can reference their
51
77
  accumulated knowledge when performing tasks, leading to better outcomes.
52
78
  """
79
+ # If memory manager is not available, skip memory injection
80
+ if not self.memory_manager:
81
+ logger.debug("Memory manager not available - skipping memory injection")
82
+ return HookResult(success=True, data=context.data, modified=False)
83
+
53
84
  try:
54
85
  # Extract and normalize agent ID from context
55
86
  agent_name = context.data.get('agent', '')
@@ -152,7 +183,17 @@ class MemoryPostDelegationHook(PostDelegationHook):
152
183
  """
153
184
  super().__init__(name="memory_post_delegation", priority=80)
154
185
  self.config = config or Config()
155
- self.memory_manager = AgentMemoryManager(self.config)
186
+
187
+ # Initialize memory manager only if available
188
+ if MEMORY_MANAGER_AVAILABLE and AgentMemoryManager:
189
+ try:
190
+ self.memory_manager = AgentMemoryManager(self.config)
191
+ except Exception as e:
192
+ logger.error(f"Failed to initialize AgentMemoryManager in PostDelegationHook: {e}")
193
+ self.memory_manager = None
194
+ else:
195
+ logger.info("Memory manager not available - post-delegation hook will be inactive")
196
+ self.memory_manager = None
156
197
 
157
198
  # Map of supported types to memory sections
158
199
  self.type_mapping = {
@@ -172,9 +213,14 @@ class MemoryPostDelegationHook(PostDelegationHook):
172
213
  WHY: Capturing learnings immediately after task completion ensures we
173
214
  don't lose valuable insights that agents discover during execution.
174
215
  """
216
+ # If memory manager is not available, skip learning extraction
217
+ if not self.memory_manager:
218
+ logger.debug("Memory manager not available - skipping learning extraction")
219
+ return HookResult(success=True, data=context.data, modified=False)
220
+
175
221
  try:
176
222
  # Check if auto-learning is enabled
177
- if not self.config.get('memory.auto_learning', False):
223
+ if not self.config.get('memory.auto_learning', True): # Changed default to True
178
224
  return HookResult(success=True, data=context.data, modified=False)
179
225
 
180
226
  # Extract agent ID
@@ -1,15 +1,33 @@
1
1
  """Services for Claude MPM."""
2
2
 
3
- from .ticket_manager import TicketManager
4
- from .agent_deployment import AgentDeploymentService
5
- from .agent_memory_manager import AgentMemoryManager, get_memory_manager
6
- from .hook_service import HookService
3
+ # Use lazy imports to prevent circular dependency issues
4
+ def __getattr__(name):
5
+ """Lazy import to prevent circular dependencies."""
6
+ if name == "TicketManager":
7
+ from .ticket_manager import TicketManager
8
+ return TicketManager
9
+ elif name == "AgentDeploymentService":
10
+ from .agent_deployment import AgentDeploymentService
11
+ return AgentDeploymentService
12
+ elif name == "AgentMemoryManager":
13
+ from .agent_memory_manager import AgentMemoryManager
14
+ return AgentMemoryManager
15
+ elif name == "get_memory_manager":
16
+ from .agent_memory_manager import get_memory_manager
17
+ return get_memory_manager
18
+ elif name == "HookService":
19
+ from .hook_service import HookService
20
+ return HookService
21
+ elif name == "ProjectAnalyzer":
22
+ from .project_analyzer import ProjectAnalyzer
23
+ return ProjectAnalyzer
24
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
7
25
 
8
- # Import other services as needed
9
26
  __all__ = [
10
27
  "TicketManager",
11
28
  "AgentDeploymentService",
12
29
  "AgentMemoryManager",
13
30
  "get_memory_manager",
14
31
  "HookService",
32
+ "ProjectAnalyzer",
15
33
  ]