Repository navigation
Expand file tree
/
Copy pathfix_formatting.py
More file actions
639 lines (522 loc) · 20.5 KB
/
Copy pathfix_formatting.py
File metadata and controls
639 lines (522 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#!/usr/bin/env python3
"""
Script to fix formatting issues in Python files.
"""
import os
import sys
import subprocess
from pathlib import Path
def fix_file(file_path):
"""Fix a Python file with formatting issues."""
# Get the file content
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
# Write the file with proper formatting
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
# Try to format with black
result = subprocess.run(["black", file_path], capture_output=True, text=True)
if result.returncode != 0:
print(f"Failed to format {file_path}")
print(result.stderr)
# If black fails, try to fix the file by completely rewriting it
if file_path.endswith("pattern_detector.py"):
rewrite_pattern_detector(file_path)
elif file_path.endswith("integrated_mcp_fabric.py"):
rewrite_integrated_mcp_fabric(file_path)
else:
print(f"Successfully formatted {file_path}")
def rewrite_pattern_detector(file_path):
"""Rewrite the pattern_detector.py file."""
content = """#!/usr/bin/env python3
\"\"\"
Pattern Detector for analyzing execution patterns and generating insights.
\"\"\"
import logging
import sqlite3
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional
logger = logging.getLogger(__name__)
class PatternDetector:
\"\"\"
Analyzes execution patterns and generates insights and recommendations.
\"\"\"
def __init__(self, db_path: str = "data/executor.db"):
self.db_path = db_path
async def detect_patterns(self) -> Dict[str, Any]:
\"\"\"
Detect patterns in execution history.
Returns:
Dict[str, Any]: Detected patterns
\"\"\"
try:
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Get execution history for the last 7 days
seven_days_ago = (datetime.utcnow() - timedelta(days=7)).isoformat()
# Detect failure patterns
cursor.execute(
\"\"\"
SELECT protocol_name, COUNT(*) as failure_count
FROM execution_history
WHERE success = 0 AND timestamp > ?
GROUP BY protocol_name
HAVING COUNT(*) > 1
ORDER BY failure_count DESC
\"\"\",
(seven_days_ago,),
)
repeated_failures = []
for row in cursor.fetchall():
protocol, count = row
severity = "high" if count > 3 else "medium"
repeated_failures.append(
{
"protocol": protocol,
"failure_count": count,
"severity": severity,
}
)
# Detect performance patterns
cursor.execute(
\"\"\"
SELECT protocol_name, AVG(duration) as avg_duration, COUNT(*) as exec_count
FROM execution_history
WHERE timestamp > ?
GROUP BY protocol_name
HAVING COUNT(*) > 2
ORDER BY avg_duration DESC
LIMIT 5
\"\"\",
(seven_days_ago,),
)
slow_protocols = []
for row in cursor.fetchall():
protocol, avg_duration, count = row
if avg_duration > 1.0: # More than 1 second
slow_protocols.append(
{
"protocol": protocol,
"avg_duration": avg_duration,
"execution_count": count,
}
)
# Detect usage patterns
cursor.execute(
\"\"\"
SELECT protocol_name, COUNT(*) as usage_count
FROM execution_history
WHERE timestamp > ?
GROUP BY protocol_name
ORDER BY usage_count DESC
LIMIT 5
\"\"\",
(seven_days_ago,),
)
top_protocols = []
for row in cursor.fetchall():
protocol, count = row
top_protocols.append(
{
"protocol": protocol,
"usage_count": count,
}
)
conn.close()
return {
"failure_patterns": {
"repeated_failures": repeated_failures,
},
"performance_patterns": {
"slow_protocols": slow_protocols,
},
"usage_patterns": {
"top_protocols": top_protocols,
},
}
except Exception as e:
logger.error(f"Error detecting patterns: {e}")
return {
"failure_patterns": {"repeated_failures": []},
"performance_patterns": {"slow_protocols": []},
"usage_patterns": {"top_protocols": []},
"error": str(e),
}
async def generate_insights(
self,
failure_patterns: Dict[str, Any],
performance_patterns: Dict[str, Any],
usage_patterns: Dict[str, Any],
) -> List[Dict[str, Any]]:
\"\"\"
Generate insights from detected patterns.
Args:
failure_patterns: Detected failure patterns
performance_patterns: Detected performance patterns
usage_patterns: Detected usage patterns
Returns:
List[Dict[str, Any]]: List of insights
\"\"\"
insights = []
# Failure insights
for repeated in failure_patterns["repeated_failures"]:
insights.append(
{
"type": "repeated_failure",
"severity": repeated["severity"],
"message": f"Protocol {repeated['protocol']} has failed {repeated['failure_count']} times",
}
)
# Performance insights
for slow in performance_patterns["slow_protocols"]:
insights.append(
{
"type": "performance_issue",
"severity": "medium",
"message": f"Protocol {slow['protocol']} averages {slow['avg_duration']:.2f}s execution time",
"recommendation": "Optimize algorithm or add caching",
"data": slow,
}
)
# Usage insights
if "top_protocols" in usage_patterns and usage_patterns["top_protocols"]:
top_protocol = usage_patterns["top_protocols"][0]
insights.append(
{
"type": "high_usage",
"message": f"Protocol {top_protocol['protocol']} is most used ({top_protocol['usage_count']} times)",
}
)
return insights
async def generate_mutation_recommendations(
self, insights: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
\"\"\"
Generate mutation recommendations based on insights.
Args:
insights: List of insights
Returns:
List[Dict[str, Any]]: List of mutation recommendations
\"\"\"
recommendations = []
for insight in insights:
if insight["type"] == "repeated_failure":
protocol = insight["message"].split()[1] # Extract protocol name
recommendations.append(
{
"protocol": protocol,
"mutation_type": "error_handling",
"priority": "high",
"suggested_changes": [
"Add retry logic with exponential backoff",
"Implement better error handling",
"Add input validation",
"Consider circuit breaker pattern",
],
"reason": insight["message"],
}
)
elif insight["type"] == "performance_issue":
protocol = insight["data"]["protocol"]
recommendations.append(
{
"protocol": protocol,
"mutation_type": "performance_optimization",
"priority": "medium",
"suggested_changes": [
"Add caching layer",
"Optimize database queries",
"Implement pagination",
],
"reason": insight["message"],
}
)
return recommendations
async def analyze(self) -> Dict[str, Any]:
\"\"\"
Analyze execution history and generate insights and recommendations.
Returns:
Dict[str, Any]: Analysis results
\"\"\"
try:
patterns = await self.detect_patterns()
insights = await self.generate_insights(
patterns["failure_patterns"],
patterns["performance_patterns"],
patterns["usage_patterns"],
)
recommendations = await self.generate_mutation_recommendations(insights)
return {
"success": True,
"patterns": patterns,
"insights": insights,
"recommendations": recommendations,
"timestamp": datetime.utcnow().isoformat(),
}
except Exception as e:
logger.error(f"Error in pattern analysis: {e}")
return {
"success": False,
"error": str(e),
"timestamp": datetime.utcnow().isoformat(),
}
"""
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
# Try to format with black again
result = subprocess.run(["black", file_path], capture_output=True, text=True)
if result.returncode == 0:
print(f"Successfully rewrote and formatted {file_path}")
else:
print(f"Failed to format {file_path} after rewriting")
print(result.stderr)
def rewrite_integrated_mcp_fabric(file_path):
"""Rewrite the integrated_mcp_fabric.py file."""
content = """#!/usr/bin/env python3
\"\"\"
Integrated MCP Fabric for managing MCP connections and state synchronization.
\"\"\"
import asyncio
import logging
import json
from typing import Dict, List, Any, Optional
from datetime import datetime
from fabric.state_continuity_core import StateContinuityManager
logger = logging.getLogger(__name__)
class MCPStateFabric:
\"\"\"
Integrated MCP Fabric for managing MCP connections and state synchronization.
\"\"\"
def __init__(self, fabric_id: str):
\"\"\"
Initialize the MCP State Fabric.
Args:
fabric_id: Unique identifier for this fabric instance
\"\"\"
self.fabric_id = fabric_id
self.mcp_clients = {}
self.state_fabric = StateContinuityManager(fabric_id)
self._initialized = False
logger.info(f"Created MCP State Fabric: {fabric_id}")
async def initialize(self, servers: List[Dict[str, str]]) -> bool:
\"\"\"
Initialize connections to MCP servers.
Args:
servers: List of server configurations with name and URL
Returns:
bool: True if initialization was successful
\"\"\"
if self._initialized:
logger.warning("Fabric already initialized")
return True
try:
for server in servers:
server_name = server.get("name")
server_url = server.get("url")
if not server_name or not server_url:
logger.error(f"Invalid server configuration: {server}")
continue
# Connect to MCP server
client = await self._connect_to_server(server_name, server_url)
if client:
self.mcp_clients[server_name] = client
logger.info(f"Connected to MCP server: {server_name} at {server_url}")
else:
logger.error(f"Failed to connect to MCP server: {server_name}")
# Initialize state fabric
await self.state_fabric.initialize()
self._initialized = len(self.mcp_clients) > 0
return self._initialized
except Exception as e:
logger.error(f"Error initializing MCP fabric: {e}")
return False
async def _connect_to_server(self, server_name: str, server_url: str) -> Optional[Any]:
\"\"\"
Connect to an MCP server.
Args:
server_name: Name of the server
server_url: URL of the server
Returns:
Optional[Any]: Client object or None if connection failed
\"\"\"
try:
# Simulate client connection
client = {
"name": server_name,
"url": server_url,
"connected": True,
"connection_time": datetime.utcnow().isoformat(),
}
# In a real implementation, this would create an actual client connection
return client
except Exception as e:
logger.error(f"Error connecting to server {server_name}: {e}")
return None
async def discover_capabilities(self) -> Dict[str, List[str]]:
\"\"\"
Discover capabilities of connected MCP servers.
Returns:
Dict[str, List[str]]: Map of server names to their capabilities
\"\"\"
if not self._initialized:
logger.error("Fabric not initialized")
return {}
capabilities = {}
for server_name, client in self.mcp_clients.items():
try:
# Simulate capability discovery
server_capabilities = [
"protocol_execution",
"state_management",
"error_handling",
]
# In a real implementation, this would query the server for capabilities
capabilities[server_name] = server_capabilities
logger.info(f"Discovered capabilities for {server_name}: {server_capabilities}")
except Exception as e:
logger.error(f"Error discovering capabilities for {server_name}: {e}")
capabilities[server_name] = []
return capabilities
async def execute_protocol(
self, server_name: str, protocol_name: str, params: Dict[str, Any]
) -> Dict[str, Any]:
\"\"\"
Execute a protocol on a specific MCP server.
Args:
server_name: Name of the server to execute on
protocol_name: Name of the protocol to execute
params: Parameters for the protocol
Returns:
Dict[str, Any]: Protocol execution results
\"\"\"
if not self._initialized:
logger.error("Fabric not initialized")
return {"success": False, "error": "Fabric not initialized"}
if server_name not in self.mcp_clients:
logger.error(f"Unknown server: {server_name}")
return {"success": False, "error": f"Unknown server: {server_name}"}
try:
client = self.mcp_clients[server_name]
# Simulate protocol execution
logger.info(f"Executing protocol {protocol_name} on {server_name}")
# In a real implementation, this would call the actual protocol
result = {
"success": True,
"protocol": protocol_name,
"server": server_name,
"timestamp": datetime.utcnow().isoformat(),
"result": {"message": f"Executed {protocol_name} successfully"},
}
# Update state with execution result
state_id = await self.state_fabric.update_state(
server_name, {"last_execution": result}
)
result["state_id"] = state_id
return result
except Exception as e:
logger.error(f"Error executing protocol {protocol_name} on {server_name}: {e}")
return {
"success": False,
"protocol": protocol_name,
"server": server_name,
"error": str(e),
"timestamp": datetime.utcnow().isoformat(),
}
async def sync_state(self, source_device: str, target_device: str) -> bool:
\"\"\"
Synchronize state between two devices.
Args:
source_device: Source device name
target_device: Target device name
Returns:
bool: True if synchronization was successful
\"\"\"
if not self._initialized:
logger.error("Fabric not initialized")
return False
try:
if source_device not in self.mcp_clients:
logger.error(f"Unknown source device: {source_device}")
return False
if target_device not in self.mcp_clients:
logger.error(f"Unknown target device: {target_device}")
return False
# Synchronize state
merged_state = await self.state_fabric.sync_devices(
source_device, target_device
)
logger.info(
f"Synced state from {source_device} to {target_device}: {merged_state.id}"
)
return True
except Exception as e:
logger.error(f"Error syncing state: {e}")
return False
async def shutdown(self):
\"\"\"Clean shutdown of all connections\"\"\"
for server_name, client in self.mcp_clients.items():
try:
# In a real implementation, this would close the client connection
logger.info(f"Closed connection to {server_name}")
except Exception as e:
logger.error(f"Error closing {server_name}: {e}")
self.mcp_clients.clear()
self._initialized = False
async def production_example():
\"\"\"
Production example showing:
1. Using mcp-use for MCP protocol
2. Adding our State Continuity value
3. Real error handling and logging
\"\"\"
fabric = MCPStateFabric("production_fabric")
servers = [
{"name": "local", "url": "http://localhost:8080"},
{"name": "remote", "url": "http://remote-server:8080"},
{"name": "backup", "url": "http://backup-server:8080"},
]
try:
initialized = await fabric.initialize(servers)
if not initialized:
logger.error("Failed to initialize fabric")
return
capabilities = await fabric.discover_capabilities()
logger.info(f"Available capabilities: {capabilities}")
if "local" in capabilities and capabilities["local"]:
result = await fabric.execute_protocol(
"local",
"system_health_check",
{"detailed": True, "timeout": 30},
)
if result["success"]:
logger.info(f"Health check successful: {result}")
else:
logger.error(f"Health check failed: {result}")
# Sync state between servers
await fabric.sync_state("local", "backup")
except Exception as e:
logger.error(f"Production example failed: {e}")
finally:
await fabric.shutdown()
if __name__ == "__main__":
# Run production example
asyncio.run(production_example())
"""
with open(file_path, "w", encoding="utf-8") as f:
f.write(content)
# Try to format with black again
result = subprocess.run(["black", file_path], capture_output=True, text=True)
if result.returncode == 0:
print(f"Successfully rewrote and formatted {file_path}")
else:
print(f"Failed to format {file_path} after rewriting")
print(result.stderr)
def main():
"""Main function."""
# Fix the problematic files
fix_file("/workspace/self-correcting-executor/analyzers/pattern_detector.py")
fix_file("/workspace/self-correcting-executor/fabric/integrated_mcp_fabric.py")
# Run black on all files
subprocess.run(["black", "."])
if __name__ == "__main__":
main()