claude-mpm 3.3.2__py3-none-any.whl → 3.4.2__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/cli/commands/memory.py +192 -14
- claude_mpm/cli/parser.py +13 -1
- claude_mpm/constants.py +1 -0
- claude_mpm/core/claude_runner.py +61 -0
- claude_mpm/core/config.py +161 -1
- claude_mpm/core/simple_runner.py +61 -0
- claude_mpm/hooks/builtin/mpm_command_hook.py +5 -5
- claude_mpm/hooks/claude_hooks/hook_handler.py +211 -4
- claude_mpm/hooks/claude_hooks/hook_wrapper.sh +10 -3
- claude_mpm/hooks/memory_integration_hook.py +51 -5
- claude_mpm/scripts/socketio_daemon.py +49 -9
- claude_mpm/scripts/socketio_server_manager.py +370 -45
- claude_mpm/services/__init__.py +41 -5
- claude_mpm/services/agent_memory_manager.py +541 -51
- claude_mpm/services/exceptions.py +677 -0
- claude_mpm/services/health_monitor.py +892 -0
- claude_mpm/services/memory_builder.py +341 -7
- claude_mpm/services/memory_optimizer.py +6 -2
- claude_mpm/services/project_analyzer.py +771 -0
- claude_mpm/services/recovery_manager.py +670 -0
- claude_mpm/services/socketio_server.py +653 -36
- claude_mpm/services/standalone_socketio_server.py +703 -34
- claude_mpm/services/version_control/git_operations.py +26 -0
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/METADATA +34 -10
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/RECORD +30 -44
- claude_mpm/agents/agent-template.yaml +0 -83
- claude_mpm/agents/test_fix_deployment/.claude-pm/config/project.json +0 -6
- claude_mpm/cli/README.md +0 -109
- claude_mpm/cli_module/refactoring_guide.md +0 -253
- claude_mpm/core/agent_registry.py.bak +0 -312
- claude_mpm/core/base_service.py.bak +0 -406
- claude_mpm/hooks/README.md +0 -97
- claude_mpm/orchestration/SUBPROCESS_DESIGN.md +0 -66
- claude_mpm/schemas/README_SECURITY.md +0 -92
- claude_mpm/schemas/agent_schema.json +0 -395
- claude_mpm/schemas/agent_schema_documentation.md +0 -181
- claude_mpm/schemas/agent_schema_security_notes.md +0 -165
- claude_mpm/schemas/examples/standard_workflow.json +0 -505
- claude_mpm/schemas/ticket_workflow_documentation.md +0 -482
- claude_mpm/schemas/ticket_workflow_schema.json +0 -590
- claude_mpm/services/framework_claude_md_generator/README.md +0 -92
- claude_mpm/services/parent_directory_manager/README.md +0 -83
- claude_mpm/services/version_control/VERSION +0 -1
- /claude_mpm/{web → dashboard}/open_dashboard.py +0 -0
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/WHEEL +0 -0
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/entry_points.txt +0 -0
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/licenses/LICENSE +0 -0
- {claude_mpm-3.3.2.dist-info → claude_mpm-3.4.2.dist-info}/top_level.txt +0 -0
claude_mpm/core/simple_runner.py
CHANGED
|
@@ -13,10 +13,14 @@ import uuid
|
|
|
13
13
|
try:
|
|
14
14
|
from claude_mpm.services.agent_deployment import AgentDeploymentService
|
|
15
15
|
from claude_mpm.services.ticket_manager import TicketManager
|
|
16
|
+
from claude_mpm.services.hook_service import HookService
|
|
17
|
+
from claude_mpm.core.config import Config
|
|
16
18
|
from claude_mpm.core.logger import get_logger, get_project_logger, ProjectLogger
|
|
17
19
|
except ImportError:
|
|
18
20
|
from claude_mpm.services.agent_deployment import AgentDeploymentService
|
|
19
21
|
from claude_mpm.services.ticket_manager import TicketManager
|
|
22
|
+
from claude_mpm.services.hook_service import HookService
|
|
23
|
+
from claude_mpm.core.config import Config
|
|
20
24
|
from claude_mpm.core.logger import get_logger, get_project_logger, ProjectLogger
|
|
21
25
|
|
|
22
26
|
|
|
@@ -76,6 +80,11 @@ class ClaudeRunner:
|
|
|
76
80
|
self.ticket_manager = None
|
|
77
81
|
self.enable_tickets = False
|
|
78
82
|
|
|
83
|
+
# Initialize hook service and register memory hooks
|
|
84
|
+
self.config = Config()
|
|
85
|
+
self.hook_service = HookService(self.config)
|
|
86
|
+
self._register_memory_hooks()
|
|
87
|
+
|
|
79
88
|
# Load system instructions
|
|
80
89
|
self.system_instructions = self._load_system_instructions()
|
|
81
90
|
|
|
@@ -741,6 +750,58 @@ class ClaudeRunner:
|
|
|
741
750
|
except Exception as e:
|
|
742
751
|
self.logger.debug(f"Failed to log session event: {e}")
|
|
743
752
|
|
|
753
|
+
def _register_memory_hooks(self):
|
|
754
|
+
"""Register memory integration hooks with the hook service.
|
|
755
|
+
|
|
756
|
+
WHY: This activates the memory system by registering hooks that automatically
|
|
757
|
+
inject agent memory before delegation and extract learnings after delegation.
|
|
758
|
+
This is the critical connection point between the memory system and the CLI.
|
|
759
|
+
|
|
760
|
+
DESIGN DECISION: We register hooks here instead of in __init__ to ensure
|
|
761
|
+
all services are initialized first. Hooks are only registered if the memory
|
|
762
|
+
system is enabled in configuration.
|
|
763
|
+
"""
|
|
764
|
+
try:
|
|
765
|
+
# Only register if memory system is enabled
|
|
766
|
+
if not self.config.get('memory.enabled', True):
|
|
767
|
+
self.logger.debug("Memory system disabled - skipping hook registration")
|
|
768
|
+
return
|
|
769
|
+
|
|
770
|
+
# Import hook classes (lazy import to avoid circular dependencies)
|
|
771
|
+
from claude_mpm.hooks.memory_integration_hook import (
|
|
772
|
+
MemoryPreDelegationHook,
|
|
773
|
+
MemoryPostDelegationHook
|
|
774
|
+
)
|
|
775
|
+
|
|
776
|
+
# Register pre-delegation hook for memory injection
|
|
777
|
+
pre_hook = MemoryPreDelegationHook(self.config)
|
|
778
|
+
success = self.hook_service.register_hook(pre_hook)
|
|
779
|
+
if success:
|
|
780
|
+
self.logger.info(f"✅ Registered memory pre-delegation hook (priority: {pre_hook.priority})")
|
|
781
|
+
else:
|
|
782
|
+
self.logger.warning("❌ Failed to register memory pre-delegation hook")
|
|
783
|
+
|
|
784
|
+
# Register post-delegation hook if auto-learning is enabled
|
|
785
|
+
if self.config.get('memory.auto_learning', True): # Default to True now
|
|
786
|
+
post_hook = MemoryPostDelegationHook(self.config)
|
|
787
|
+
success = self.hook_service.register_hook(post_hook)
|
|
788
|
+
if success:
|
|
789
|
+
self.logger.info(f"✅ Registered memory post-delegation hook (priority: {post_hook.priority})")
|
|
790
|
+
else:
|
|
791
|
+
self.logger.warning("❌ Failed to register memory post-delegation hook")
|
|
792
|
+
else:
|
|
793
|
+
self.logger.info("ℹ️ Auto-learning disabled - skipping post-delegation hook")
|
|
794
|
+
|
|
795
|
+
# Log summary of registered hooks
|
|
796
|
+
hooks = self.hook_service.list_hooks()
|
|
797
|
+
pre_count = len(hooks.get('pre_delegation', []))
|
|
798
|
+
post_count = len(hooks.get('post_delegation', []))
|
|
799
|
+
self.logger.info(f"📋 Hook Service initialized: {pre_count} pre-delegation, {post_count} post-delegation hooks")
|
|
800
|
+
|
|
801
|
+
except Exception as e:
|
|
802
|
+
self.logger.error(f"❌ Failed to register memory hooks: {e}")
|
|
803
|
+
# Don't fail the entire initialization - memory system is optional
|
|
804
|
+
|
|
744
805
|
def _launch_subprocess_interactive(self, cmd: list, env: dict):
|
|
745
806
|
"""Launch Claude as a subprocess with PTY for interactive mode."""
|
|
746
807
|
import pty
|
|
@@ -12,11 +12,11 @@ logger = get_logger(__name__)
|
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
class MpmCommandHook(SubmitHook):
|
|
15
|
-
"""Hook that intercepts /mpm
|
|
15
|
+
"""Hook that intercepts /mpm commands and routes them to the command router."""
|
|
16
16
|
|
|
17
17
|
def __init__(self):
|
|
18
18
|
super().__init__(name="mpm_command", priority=1) # High priority to intercept early
|
|
19
|
-
self.command_prefix = "/mpm
|
|
19
|
+
self.command_prefix = "/mpm "
|
|
20
20
|
self.command_router_path = self._find_command_router()
|
|
21
21
|
|
|
22
22
|
def _find_command_router(self) -> Path:
|
|
@@ -35,11 +35,11 @@ class MpmCommandHook(SubmitHook):
|
|
|
35
35
|
return Path(".claude/scripts/command_router.py").resolve()
|
|
36
36
|
|
|
37
37
|
def execute(self, context: HookContext) -> HookResult:
|
|
38
|
-
"""Check for /mpm
|
|
38
|
+
"""Check for /mpm commands and execute them directly."""
|
|
39
39
|
try:
|
|
40
40
|
prompt = context.data.get('prompt', '').strip()
|
|
41
41
|
|
|
42
|
-
# Check if this is an /mpm
|
|
42
|
+
# Check if this is an /mpm command
|
|
43
43
|
if not prompt.startswith(self.command_prefix):
|
|
44
44
|
# Not our command, pass through
|
|
45
45
|
return HookResult(
|
|
@@ -67,7 +67,7 @@ class MpmCommandHook(SubmitHook):
|
|
|
67
67
|
command = parts[0]
|
|
68
68
|
args = parts[1:]
|
|
69
69
|
|
|
70
|
-
logger.info(f"Executing /mpm
|
|
70
|
+
logger.info(f"Executing /mpm {command} with args: {args}")
|
|
71
71
|
|
|
72
72
|
# Execute command using command router
|
|
73
73
|
try:
|
|
@@ -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
|
-
|
|
726
|
-
|
|
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__":
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#!/bin/bash
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
2
|
# Claude Code hook wrapper for claude-mpm
|
|
3
3
|
|
|
4
4
|
# Debug log (optional - comment out in production)
|
|
@@ -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
|
|
52
|
-
exec
|
|
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
|
-
|
|
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
|
-
|
|
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',
|
|
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
|
|
@@ -43,11 +43,26 @@ def is_running():
|
|
|
43
43
|
return False
|
|
44
44
|
|
|
45
45
|
def start_server():
|
|
46
|
-
"""Start the Socket.IO server as a daemon."""
|
|
46
|
+
"""Start the Socket.IO server as a daemon with conflict detection."""
|
|
47
47
|
if is_running():
|
|
48
|
-
print("Socket.IO server is already running.")
|
|
48
|
+
print("Socket.IO daemon server is already running.")
|
|
49
|
+
print(f"Use '{__file__} status' for details")
|
|
49
50
|
return
|
|
50
51
|
|
|
52
|
+
# Check for HTTP-managed server conflict
|
|
53
|
+
try:
|
|
54
|
+
import requests
|
|
55
|
+
response = requests.get("http://localhost:8765/health", timeout=1.0)
|
|
56
|
+
if response.status_code == 200:
|
|
57
|
+
data = response.json()
|
|
58
|
+
if 'server_id' in data:
|
|
59
|
+
print(f"⚠️ HTTP-managed server already running: {data.get('server_id')}")
|
|
60
|
+
print(f" Stop it first: socketio_server_manager.py stop --port 8765")
|
|
61
|
+
print(f" Or diagnose: socketio_server_manager.py diagnose")
|
|
62
|
+
return
|
|
63
|
+
except:
|
|
64
|
+
pass # No HTTP server, continue
|
|
65
|
+
|
|
51
66
|
ensure_dirs()
|
|
52
67
|
|
|
53
68
|
# Fork to create daemon
|
|
@@ -96,9 +111,10 @@ def start_server():
|
|
|
96
111
|
signal_handler(signal.SIGINT, None)
|
|
97
112
|
|
|
98
113
|
def stop_server():
|
|
99
|
-
"""Stop the Socket.IO server."""
|
|
114
|
+
"""Stop the Socket.IO daemon server."""
|
|
100
115
|
if not is_running():
|
|
101
|
-
print("Socket.IO server is not running.")
|
|
116
|
+
print("Socket.IO daemon server is not running.")
|
|
117
|
+
print(f"Check for other servers: socketio_server_manager.py status")
|
|
102
118
|
return
|
|
103
119
|
|
|
104
120
|
try:
|
|
@@ -125,11 +141,12 @@ def stop_server():
|
|
|
125
141
|
print(f"Error stopping server: {e}")
|
|
126
142
|
|
|
127
143
|
def status_server():
|
|
128
|
-
"""Check server status."""
|
|
144
|
+
"""Check server status with manager integration info."""
|
|
129
145
|
if is_running():
|
|
130
146
|
with open(PID_FILE) as f:
|
|
131
147
|
pid = int(f.read().strip())
|
|
132
|
-
print(f"Socket.IO server is running (PID: {pid})")
|
|
148
|
+
print(f"Socket.IO daemon server is running (PID: {pid})")
|
|
149
|
+
print(f"PID file: {PID_FILE}")
|
|
133
150
|
|
|
134
151
|
# Check if port is listening
|
|
135
152
|
try:
|
|
@@ -138,13 +155,36 @@ def status_server():
|
|
|
138
155
|
result = sock.connect_ex(('localhost', 8765))
|
|
139
156
|
sock.close()
|
|
140
157
|
if result == 0:
|
|
141
|
-
print("Server is listening on port 8765")
|
|
158
|
+
print("✅ Server is listening on port 8765")
|
|
159
|
+
print("🔧 Management style: daemon")
|
|
142
160
|
else:
|
|
143
|
-
print("WARNING: Server process exists but port 8765 is not accessible")
|
|
161
|
+
print("⚠️ WARNING: Server process exists but port 8765 is not accessible")
|
|
162
|
+
except:
|
|
163
|
+
pass
|
|
164
|
+
|
|
165
|
+
# Show management commands
|
|
166
|
+
print("\n🔧 Management Commands:")
|
|
167
|
+
print(f" • Stop: {__file__} stop")
|
|
168
|
+
print(f" • Restart: {__file__} restart")
|
|
169
|
+
|
|
170
|
+
# Check for manager conflicts
|
|
171
|
+
try:
|
|
172
|
+
import requests
|
|
173
|
+
response = requests.get("http://localhost:8765/health", timeout=1.0)
|
|
174
|
+
if response.status_code == 200:
|
|
175
|
+
data = response.json()
|
|
176
|
+
if 'server_id' in data and data.get('server_id') != 'daemon-socketio':
|
|
177
|
+
print(f"\n⚠️ POTENTIAL CONFLICT: HTTP-managed server also detected")
|
|
178
|
+
print(f" Server ID: {data.get('server_id')}")
|
|
179
|
+
print(f" Use 'socketio_server_manager.py diagnose' to resolve")
|
|
144
180
|
except:
|
|
145
181
|
pass
|
|
182
|
+
|
|
146
183
|
else:
|
|
147
|
-
print("Socket.IO server is not running")
|
|
184
|
+
print("Socket.IO daemon server is not running")
|
|
185
|
+
print(f"\n🔧 Start Commands:")
|
|
186
|
+
print(f" • Daemon: {__file__} start")
|
|
187
|
+
print(f" • HTTP-managed: socketio_server_manager.py start")
|
|
148
188
|
|
|
149
189
|
def main():
|
|
150
190
|
"""Main entry point."""
|