claude-mpm 4.2.40__py3-none-any.whl → 4.2.43__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 (36) hide show
  1. claude_mpm/VERSION +1 -1
  2. claude_mpm/agents/BASE_ENGINEER.md +114 -1
  3. claude_mpm/agents/BASE_OPS.md +156 -1
  4. claude_mpm/agents/INSTRUCTIONS.md +120 -11
  5. claude_mpm/agents/WORKFLOW.md +160 -10
  6. claude_mpm/agents/templates/agentic-coder-optimizer.json +17 -12
  7. claude_mpm/agents/templates/react_engineer.json +217 -0
  8. claude_mpm/agents/templates/web_qa.json +40 -4
  9. claude_mpm/commands/mpm-browser-monitor.md +370 -0
  10. claude_mpm/commands/mpm-monitor.md +177 -0
  11. claude_mpm/dashboard/static/built/components/code-viewer.js +1076 -2
  12. claude_mpm/dashboard/static/built/components/ui-state-manager.js +465 -2
  13. claude_mpm/dashboard/static/css/dashboard.css +2 -0
  14. claude_mpm/dashboard/static/js/browser-console-monitor.js +495 -0
  15. claude_mpm/dashboard/static/js/components/browser-log-viewer.js +763 -0
  16. claude_mpm/dashboard/static/js/components/code-viewer.js +931 -340
  17. claude_mpm/dashboard/static/js/components/diff-viewer.js +891 -0
  18. claude_mpm/dashboard/static/js/components/file-change-tracker.js +443 -0
  19. claude_mpm/dashboard/static/js/components/file-change-viewer.js +690 -0
  20. claude_mpm/dashboard/static/js/components/ui-state-manager.js +156 -19
  21. claude_mpm/dashboard/static/js/dashboard.js +16 -0
  22. claude_mpm/dashboard/static/js/socket-client.js +2 -2
  23. claude_mpm/dashboard/static/test-browser-monitor.html +470 -0
  24. claude_mpm/dashboard/templates/index.html +64 -99
  25. claude_mpm/services/monitor/handlers/browser.py +451 -0
  26. claude_mpm/services/monitor/server.py +267 -4
  27. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/METADATA +1 -1
  28. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/RECORD +32 -26
  29. claude_mpm/agents/templates/agentic-coder-optimizer.md +0 -44
  30. claude_mpm/agents/templates/agentic_coder_optimizer.json +0 -238
  31. claude_mpm/agents/templates/test-non-mpm.json +0 -20
  32. claude_mpm/dashboard/static/dist/components/code-viewer.js +0 -2
  33. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/WHEEL +0 -0
  34. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/entry_points.txt +0 -0
  35. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/licenses/LICENSE +0 -0
  36. {claude_mpm-4.2.40.dist-info → claude_mpm-4.2.43.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,370 @@
1
+ ---
2
+ description: Control browser console monitoring for Claude MPM
3
+ argument-hint: start|stop|status|logs|clear
4
+ ---
5
+
6
+ # Claude MPM Browser Monitor Control
7
+
8
+ I'll help you control browser console monitoring to capture and analyze browser-side events and errors.
9
+
10
+ Based on your request: "$ARGUMENTS"
11
+
12
+ ```python
13
+ import subprocess
14
+ import json
15
+ import time
16
+ import sys
17
+ import os
18
+ from pathlib import Path
19
+ from datetime import datetime, timedelta
20
+
21
+ # Configuration
22
+ BROWSER_LOG_DIR = Path.home() / ".claude-mpm" / "logs" / "client"
23
+ CONFIG_FILE = Path.home() / ".claude-mpm" / "config" / "browser_monitor.json"
24
+
25
+ def ensure_directories():
26
+ """Ensure required directories exist"""
27
+ BROWSER_LOG_DIR.mkdir(parents=True, exist_ok=True)
28
+ CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
29
+
30
+ def load_config():
31
+ """Load browser monitor configuration"""
32
+ if CONFIG_FILE.exists():
33
+ with open(CONFIG_FILE) as f:
34
+ return json.load(f)
35
+ return {"enabled": False, "sessions": [], "started_at": None}
36
+
37
+ def save_config(config):
38
+ """Save browser monitor configuration"""
39
+ ensure_directories()
40
+ with open(CONFIG_FILE, "w") as f:
41
+ json.dump(config, f, indent=2)
42
+
43
+ def execute_browser_monitor_command(command):
44
+ """Execute browser monitor command"""
45
+
46
+ if command == "start":
47
+ config = load_config()
48
+ if config["enabled"]:
49
+ print("✅ Browser monitoring is already active")
50
+ if config.get("started_at"):
51
+ print(f"📅 Started at: {config['started_at']}")
52
+ return True
53
+
54
+ print("🎯 Starting browser console monitoring...")
55
+ ensure_directories()
56
+
57
+ # Update config
58
+ config["enabled"] = True
59
+ config["started_at"] = datetime.now().isoformat()
60
+ save_config(config)
61
+
62
+ # Create injection script for browser monitoring
63
+ injection_script = BROWSER_LOG_DIR / "inject.js"
64
+ with open(injection_script, "w") as f:
65
+ f.write("""
66
+ // Claude MPM Browser Monitor Injection Script
67
+ (function() {
68
+ const browserId = 'browser_' + Date.now();
69
+ const logEndpoint = 'http://localhost:8765/api/browser-log';
70
+
71
+ // Store original console methods
72
+ const originalLog = console.log;
73
+ const originalError = console.error;
74
+ const originalWarn = console.warn;
75
+ const originalInfo = console.info;
76
+ const originalDebug = console.debug;
77
+
78
+ function sendLog(level, args) {
79
+ try {
80
+ const message = Array.from(args).map(arg => {
81
+ if (typeof arg === 'object') {
82
+ return JSON.stringify(arg);
83
+ }
84
+ return String(arg);
85
+ }).join(' ');
86
+
87
+ // Send to local monitor
88
+ fetch(logEndpoint, {
89
+ method: 'POST',
90
+ headers: {'Content-Type': 'application/json'},
91
+ body: JSON.stringify({
92
+ browser_id: browserId,
93
+ timestamp: new Date().toISOString(),
94
+ level: level,
95
+ message: message,
96
+ url: window.location.href,
97
+ userAgent: navigator.userAgent
98
+ })
99
+ }).catch(() => {
100
+ // Silently fail if monitor is not running
101
+ });
102
+
103
+ // Also save to local storage for persistence
104
+ const logs = JSON.parse(localStorage.getItem('claude_mpm_logs') || '[]');
105
+ logs.push({
106
+ browser_id: browserId,
107
+ timestamp: new Date().toISOString(),
108
+ level: level,
109
+ message: message
110
+ });
111
+ // Keep only last 1000 logs
112
+ if (logs.length > 1000) {
113
+ logs.shift();
114
+ }
115
+ localStorage.setItem('claude_mpm_logs', JSON.stringify(logs));
116
+ } catch (e) {
117
+ // Fail silently
118
+ }
119
+ }
120
+
121
+ // Override console methods
122
+ console.log = function(...args) {
123
+ sendLog('INFO', args);
124
+ return originalLog.apply(console, args);
125
+ };
126
+
127
+ console.error = function(...args) {
128
+ sendLog('ERROR', args);
129
+ return originalError.apply(console, args);
130
+ };
131
+
132
+ console.warn = function(...args) {
133
+ sendLog('WARN', args);
134
+ return originalWarn.apply(console, args);
135
+ };
136
+
137
+ console.info = function(...args) {
138
+ sendLog('INFO', args);
139
+ return originalInfo.apply(console, args);
140
+ };
141
+
142
+ console.debug = function(...args) {
143
+ sendLog('DEBUG', args);
144
+ return originalDebug.apply(console, args);
145
+ };
146
+
147
+ // Monitor window errors
148
+ window.addEventListener('error', function(event) {
149
+ sendLog('ERROR', [`Uncaught Error: ${event.message} at ${event.filename}:${event.lineno}:${event.colno}`]);
150
+ });
151
+
152
+ // Monitor unhandled promise rejections
153
+ window.addEventListener('unhandledrejection', function(event) {
154
+ sendLog('ERROR', [`Unhandled Promise Rejection: ${event.reason}`]);
155
+ });
156
+
157
+ console.info('[Claude MPM] Browser monitoring activated - ID: ' + browserId);
158
+ })();
159
+ """)
160
+
161
+ print("✅ Browser monitoring started successfully!")
162
+ print(f"📁 Logs will be saved to: {BROWSER_LOG_DIR}")
163
+ print("\n📝 To inject monitoring into a browser:")
164
+ print("1. Open browser developer console")
165
+ print(f"2. Copy and paste the script from: {injection_script}")
166
+ print("3. Or use browser extension to auto-inject")
167
+ return True
168
+
169
+ elif command == "stop":
170
+ config = load_config()
171
+ if not config["enabled"]:
172
+ print("ℹ️ Browser monitoring is not active")
173
+ return True
174
+
175
+ print("🛑 Stopping browser console monitoring...")
176
+ config["enabled"] = False
177
+ config["stopped_at"] = datetime.now().isoformat()
178
+ save_config(config)
179
+
180
+ print("✅ Browser monitoring stopped")
181
+ print("Note: Existing browser sessions will continue logging until refreshed")
182
+ return True
183
+
184
+ elif command == "status":
185
+ config = load_config()
186
+
187
+ print("📊 Browser Monitor Status")
188
+ print("-" * 40)
189
+
190
+ if config["enabled"]:
191
+ print("✅ Status: ACTIVE")
192
+ if config.get("started_at"):
193
+ print(f"📅 Started: {config['started_at']}")
194
+ else:
195
+ print("❌ Status: INACTIVE")
196
+ if config.get("stopped_at"):
197
+ print(f"📅 Stopped: {config['stopped_at']}")
198
+
199
+ # Check for log files
200
+ if BROWSER_LOG_DIR.exists():
201
+ log_files = list(BROWSER_LOG_DIR.glob("*.log"))
202
+ if log_files:
203
+ print(f"\n📁 Log Files: {len(log_files)}")
204
+
205
+ # Show recent sessions
206
+ recent_files = sorted(log_files, key=lambda x: x.stat().st_mtime, reverse=True)[:5]
207
+ if recent_files:
208
+ print("\n🕐 Recent Sessions:")
209
+ for f in recent_files:
210
+ size = f.stat().st_size
211
+ mtime = datetime.fromtimestamp(f.stat().st_mtime)
212
+ print(f" - {f.name}: {size:,} bytes, {mtime.strftime('%Y-%m-%d %H:%M')}")
213
+ else:
214
+ print("\n📁 No log files found")
215
+
216
+ # Check active sessions
217
+ if config.get("sessions"):
218
+ print(f"\n🌐 Active Sessions: {len(config['sessions'])}")
219
+ for session in config["sessions"][-5:]:
220
+ print(f" - {session.get('browser_id', 'Unknown')}: {session.get('last_seen', 'Never')}")
221
+
222
+ return True
223
+
224
+ elif command == "logs":
225
+ print("📋 Recent Browser Console Logs")
226
+ print("-" * 40)
227
+
228
+ if not BROWSER_LOG_DIR.exists():
229
+ print("ℹ️ No log directory found")
230
+ return True
231
+
232
+ # Find recent log files
233
+ log_files = sorted(BROWSER_LOG_DIR.glob("*.log"), key=lambda x: x.stat().st_mtime, reverse=True)
234
+
235
+ if not log_files:
236
+ print("ℹ️ No log files found")
237
+ print("Run '/mpm-browser-monitor start' and inject the script into a browser")
238
+ return True
239
+
240
+ # Show logs from most recent file
241
+ recent_file = log_files[0]
242
+ print(f"\n📁 Showing logs from: {recent_file.name}")
243
+ print(f"📅 Last modified: {datetime.fromtimestamp(recent_file.stat().st_mtime).strftime('%Y-%m-%d %H:%M:%S')}")
244
+ print("-" * 40)
245
+
246
+ # Read last 50 lines
247
+ try:
248
+ with open(recent_file) as f:
249
+ lines = f.readlines()
250
+
251
+ # Parse and display last 20 entries
252
+ for line in lines[-20:]:
253
+ try:
254
+ entry = json.loads(line.strip())
255
+ timestamp = entry.get("timestamp", "")[:19] # Trim to seconds
256
+ level = entry.get("level", "INFO")
257
+ message = entry.get("message", "")[:100] # Truncate long messages
258
+
259
+ # Color code by level
260
+ level_colors = {
261
+ "ERROR": "🔴",
262
+ "WARN": "🟡",
263
+ "INFO": "🔵",
264
+ "DEBUG": "⚪"
265
+ }
266
+ icon = level_colors.get(level, "⚫")
267
+
268
+ print(f"{icon} [{timestamp}] {level:5} | {message}")
269
+ except:
270
+ print(f" {line.strip()[:100]}")
271
+
272
+ except Exception as e:
273
+ print(f"❌ Error reading log file: {e}")
274
+
275
+ print("\n💡 Tip: Use the dashboard at http://localhost:8765 for real-time log viewing")
276
+ return True
277
+
278
+ elif command == "clear":
279
+ print("🧹 Clearing browser console logs...")
280
+
281
+ if not BROWSER_LOG_DIR.exists():
282
+ print("ℹ️ No log directory found")
283
+ return True
284
+
285
+ # Count files before clearing
286
+ log_files = list(BROWSER_LOG_DIR.glob("*.log"))
287
+ file_count = len(log_files)
288
+
289
+ if file_count == 0:
290
+ print("ℹ️ No log files to clear")
291
+ return True
292
+
293
+ # Calculate total size
294
+ total_size = sum(f.stat().st_size for f in log_files)
295
+
296
+ # Clear all log files
297
+ for f in log_files:
298
+ try:
299
+ f.unlink()
300
+ except Exception as e:
301
+ print(f"⚠️ Failed to delete {f.name}: {e}")
302
+
303
+ # Clear sessions from config
304
+ config = load_config()
305
+ config["sessions"] = []
306
+ save_config(config)
307
+
308
+ print(f"✅ Cleared {file_count} log files ({total_size:,} bytes)")
309
+ return True
310
+
311
+ else:
312
+ # Show usage
313
+ print("📋 Claude MPM Browser Monitor Control")
314
+ print("\nUsage: /mpm-browser-monitor [command]")
315
+ print("\nAvailable commands:")
316
+ print(" start - Start browser console monitoring")
317
+ print(" stop - Stop browser console monitoring")
318
+ print(" status - Show monitoring status and active sessions")
319
+ print(" logs - Display recent browser console logs")
320
+ print(" clear - Clear all browser console logs")
321
+ print("\nExample: /mpm-browser-monitor start")
322
+ print("\n💡 After starting, inject the monitoring script into your browser's console")
323
+ print(" to begin capturing logs from that browser session.")
324
+ return True
325
+
326
+ # Parse arguments
327
+ args = "$ARGUMENTS".strip().lower() if "$ARGUMENTS" else ""
328
+
329
+ # Execute command
330
+ execute_browser_monitor_command(args if args else None)
331
+ ```
332
+
333
+ ## What Browser Monitoring Provides
334
+
335
+ Browser console monitoring captures:
336
+
337
+ - **Console Logs**: All console.log, console.error, console.warn, console.info, console.debug calls
338
+ - **JavaScript Errors**: Uncaught exceptions and syntax errors
339
+ - **Promise Rejections**: Unhandled promise rejection events
340
+ - **Network Errors**: Failed resource loads and AJAX errors
341
+ - **Performance Metrics**: Page load times and resource timings
342
+
343
+ ## How to Use
344
+
345
+ 1. **Start Monitoring**: Run `/mpm-browser-monitor start`
346
+ 2. **Inject Script**: Copy the generated script into your browser's console
347
+ 3. **View Logs**: Check logs with `/mpm-browser-monitor logs` or use the dashboard
348
+ 4. **Analyze**: Filter and search logs in the dashboard's Browser Monitor tab
349
+
350
+ ## Integration with Dashboard
351
+
352
+ When the monitor is running (http://localhost:8765), the Browser Monitor Log tab provides:
353
+ - Real-time log streaming
354
+ - Color-coded log levels
355
+ - Filtering by browser ID and log level
356
+ - Export capabilities
357
+
358
+ ## Troubleshooting
359
+
360
+ If logs are not appearing:
361
+ 1. Ensure the monitor daemon is running (`/mpm-monitor status`)
362
+ 2. Check that the injection script was properly executed in the browser
363
+ 3. Verify browser allows console overrides (some extensions may block)
364
+ 4. Check browser's security settings for localhost connections
365
+
366
+ ## Related Commands
367
+
368
+ - `/mpm-monitor` - Control the main monitor daemon
369
+ - `/mpm-logs` - View system logs
370
+ - `/mpm-stats` - View monitoring statistics
@@ -0,0 +1,177 @@
1
+ ---
2
+ description: Control the Claude MPM monitor daemon
3
+ argument-hint: start|stop|status|restart
4
+ ---
5
+
6
+ # Claude MPM Monitor Control
7
+
8
+ I'll help you control the Claude MPM monitor daemon for real-time event tracking and visualization.
9
+
10
+ Based on your request: "$ARGUMENTS"
11
+
12
+ ```python
13
+ import subprocess
14
+ import requests
15
+ import time
16
+ import sys
17
+ import os
18
+
19
+ def check_monitor_status():
20
+ """Check if monitor is running"""
21
+ try:
22
+ response = requests.get('http://localhost:8765/health', timeout=2)
23
+ return response.status_code == 200
24
+ except:
25
+ return False
26
+
27
+ def execute_monitor_command(command):
28
+ """Execute monitor command and handle output"""
29
+ if command == "start":
30
+ if check_monitor_status():
31
+ print("✅ Monitor is already running at http://localhost:8765")
32
+ return True
33
+
34
+ print("🚀 Starting Claude MPM monitor daemon...")
35
+ result = subprocess.run(
36
+ [sys.executable, "-m", "claude_mpm.cli.main", "monitor", "start"],
37
+ capture_output=True,
38
+ text=True,
39
+ cwd=os.path.expanduser("~/Projects/claude-mpm")
40
+ )
41
+
42
+ if result.returncode == 0:
43
+ # Give it a moment to start
44
+ time.sleep(2)
45
+ if check_monitor_status():
46
+ print("✅ Monitor started successfully!")
47
+ print("📊 Dashboard available at: http://localhost:8765")
48
+ print("🔍 WebSocket events at: ws://localhost:8765/ws")
49
+ return True
50
+ else:
51
+ print("⚠️ Monitor started but health check failed")
52
+ print("Debug output:", result.stdout)
53
+ return False
54
+ else:
55
+ print("❌ Failed to start monitor")
56
+ print("Error:", result.stderr)
57
+ return False
58
+
59
+ elif command == "stop":
60
+ if not check_monitor_status():
61
+ print("ℹ️ Monitor is not running")
62
+ return True
63
+
64
+ print("🛑 Stopping Claude MPM monitor daemon...")
65
+ result = subprocess.run(
66
+ [sys.executable, "-m", "claude_mpm.cli.main", "monitor", "stop"],
67
+ capture_output=True,
68
+ text=True,
69
+ cwd=os.path.expanduser("~/Projects/claude-mpm")
70
+ )
71
+
72
+ if result.returncode == 0:
73
+ print("✅ Monitor stopped successfully")
74
+ return True
75
+ else:
76
+ print("❌ Failed to stop monitor")
77
+ print("Error:", result.stderr)
78
+ return False
79
+
80
+ elif command == "status":
81
+ if check_monitor_status():
82
+ print("✅ Monitor is running")
83
+ print("📊 Dashboard: http://localhost:8765")
84
+ print("🔍 WebSocket: ws://localhost:8765/ws")
85
+ print("💚 Health check: http://localhost:8765/health")
86
+
87
+ # Try to get more info
88
+ try:
89
+ response = requests.get('http://localhost:8765/api/stats', timeout=2)
90
+ if response.status_code == 200:
91
+ stats = response.json()
92
+ print(f"📈 Statistics:")
93
+ print(f" - Connected clients: {stats.get('connected_clients', 0)}")
94
+ print(f" - Total events: {stats.get('total_events', 0)}")
95
+ print(f" - Uptime: {stats.get('uptime', 'N/A')}")
96
+ except:
97
+ pass
98
+ else:
99
+ print("❌ Monitor is not running")
100
+ print("Run '/mpm-monitor start' to start the monitor")
101
+ return True
102
+
103
+ elif command == "restart":
104
+ print("🔄 Restarting Claude MPM monitor daemon...")
105
+
106
+ # Stop if running
107
+ if check_monitor_status():
108
+ print("Stopping current instance...")
109
+ subprocess.run(
110
+ [sys.executable, "-m", "claude_mpm.cli.main", "monitor", "stop"],
111
+ capture_output=True,
112
+ text=True,
113
+ cwd=os.path.expanduser("~/Projects/claude-mpm")
114
+ )
115
+ time.sleep(2)
116
+
117
+ # Start fresh
118
+ print("Starting new instance...")
119
+ result = subprocess.run(
120
+ [sys.executable, "-m", "claude_mpm.cli.main", "monitor", "start"],
121
+ capture_output=True,
122
+ text=True,
123
+ cwd=os.path.expanduser("~/Projects/claude-mpm")
124
+ )
125
+
126
+ if result.returncode == 0:
127
+ time.sleep(2)
128
+ if check_monitor_status():
129
+ print("✅ Monitor restarted successfully!")
130
+ print("📊 Dashboard available at: http://localhost:8765")
131
+ return True
132
+
133
+ print("❌ Failed to restart monitor")
134
+ return False
135
+
136
+ else:
137
+ # Show usage
138
+ print("📋 Claude MPM Monitor Control")
139
+ print("\nUsage: /mpm-monitor [command]")
140
+ print("\nAvailable commands:")
141
+ print(" start - Start the monitor daemon")
142
+ print(" stop - Stop the monitor daemon")
143
+ print(" status - Check monitor status")
144
+ print(" restart - Restart the monitor daemon")
145
+ print("\nExample: /mpm-monitor start")
146
+ return True
147
+
148
+ # Parse arguments
149
+ args = "$ARGUMENTS".strip().lower() if "$ARGUMENTS" else ""
150
+
151
+ # Execute command
152
+ execute_monitor_command(args if args else None)
153
+ ```
154
+
155
+ ## What the Monitor Provides
156
+
157
+ The Claude MPM monitor provides real-time visualization and tracking of:
158
+
159
+ - **Event Stream**: Live WebSocket feed of all MPM events
160
+ - **Dashboard**: Web-based interface for monitoring agent activities
161
+ - **Statistics**: Track event counts, performance metrics, and system health
162
+ - **Browser Monitoring**: Capture and analyze browser console logs
163
+ - **Agent Activities**: Monitor agent deployments, tool usage, and responses
164
+
165
+ ## Troubleshooting
166
+
167
+ If the monitor fails to start:
168
+ 1. Check if port 8765 is already in use
169
+ 2. Ensure you have proper permissions
170
+ 3. Check the logs in `.claude-mpm/logs/monitor.log`
171
+ 4. Try running with `--debug` flag for more output
172
+
173
+ ## Related Commands
174
+
175
+ - `/mpm-browser-monitor` - Control browser console monitoring
176
+ - `/mpm-stats` - View detailed statistics
177
+ - `/mpm-logs` - Access system logs