-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_supervisor.py
More file actions
2700 lines (2304 loc) · 111 KB
/
run_supervisor.py
File metadata and controls
2700 lines (2304 loc) · 111 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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AGI OS Unified Supervisor - Project Trinity v92.0
==================================================
The central command that orchestrates the entire AGI ecosystem:
- JARVIS (Body) - macOS automation and interaction
- JARVIS Prime (Mind) - Local LLM inference and reasoning
- Reactor Core (Nervous System) - Training, learning, and model serving
RUN: python3 run_supervisor.py
ARCHITECTURE:
┌─────────────────────────────────────────────────────────────────────┐
│ AGI OS UNIFIED SUPERVISOR v92.0 │
│ (Central Coordination Hub) │
└─────────────────────────────────────────────────────────────────────┘
│
┌─────────────────────────────┼─────────────────────────────┐
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────────┐ ┌─────────┐
│ JARVIS │◄────────────►│ TRINITY │◄────────────►│ J-PRIME │
│ (Body) │ Events │ ORCHESTRATOR│ Events │ (Mind) │
│ │ │ │ │ │
│ macOS │ │ Heartbeats │ │ LLM │
│ Actions │ │ Commands │ │ Inference
└─────────┘ │ State Sync │ └─────────┘
└─────────────┘
│
┌─────────────────┼─────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│REACTOR CORE │ │ ONLINE │ │ DISTRIBUTED │
│ (Nerves) │ │ LEARNING │ │ TRAINING │
│ │ │ │ │ │
│ Training │ │ Experience │ │ Multi-VM │
│ Learning │ │ Replay │ │ Gradient │
│ Serving │ │ EWC/Drift │ │ Sync │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└─────────────────┼─────────────────┘
▼
┌─────────────┐
│ MLForge │
│ C++ Bindings│
│ + GCP Spot │
│ + Versioning│
└─────────────┘
v77.0 FEATURES:
- One-command startup for entire AGI ecosystem
- Automatic component discovery and health monitoring
- Graceful startup/shutdown sequence
- Real-time event streaming between components
- Continuous learning from JARVIS interactions
- Model serving for J-Prime inference
- Fault tolerance with automatic recovery
v91.0 ADVANCED FEATURES:
- Online/Incremental Learning: Prioritized experience replay with importance sampling
- Elastic Weight Consolidation (EWC): Prevents catastrophic forgetting during updates
- Concept Drift Detection: Page-Hinkley test for automatic model adaptation
- Data Versioning: Content-addressed storage with lineage tracking (DVC compatible)
- GCP Spot VM Checkpointing: Predictive preemption with multi-signal detection
- Distributed Training: Multi-VM coordination with gradient compression
- Dynamic Resource Allocation: Auto-scaling with cost-aware decisions
- MLForge C++ Bindings: High-performance matrix/neural ops with pybind11
v92.0 RELIABILITY FEATURES:
- Atomic File Writes: Prevents checkpoint corruption from partial writes
- Circuit Breaker Pattern: Protects external service calls with auto-recovery
- Backpressure Control: Prevents memory exhaustion under high load
- Proper Async Patterns: Deadlock-free async/await with timeouts
- Gradient Verification: Checksum validation for distributed training
- Memory Pressure Awareness: Adaptive behavior under resource constraints
- Unified Error Handling: Centralized error classification and routing
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
import signal
import subprocess
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum, auto
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
# Add reactor_core to path
sys.path.insert(0, str(Path(__file__).parent))
# =============================================================================
# TRINITY UNIFIED LOOP MANAGER (v3.0) - Cross-Repo Foundation
# =============================================================================
# Add cross_repo path for shared Trinity infrastructure
_cross_repo_path = Path.home() / ".jarvis" / "cross_repo"
if str(_cross_repo_path) not in sys.path:
sys.path.insert(0, str(_cross_repo_path))
try:
from unified_loop_manager import (
get_trinity_manager,
trinity_startup,
trinity_shutdown,
TrinityComponent,
TrinityConfig,
safe_create_task,
safe_to_thread,
safe_gather,
)
TRINITY_AVAILABLE = True
except ImportError as e:
TRINITY_AVAILABLE = False
logging.getLogger(__name__).info(f"Trinity not available (optional): {e}")
# Fallback implementations
async def trinity_startup(component):
return None
async def trinity_shutdown():
pass
def safe_create_task(coro, *, name=None):
return asyncio.create_task(coro, name=name)
async def safe_to_thread(func, *args, **kwargs):
return await asyncio.to_thread(func, *args, **kwargs)
async def safe_gather(*coros, return_exceptions=False):
return await asyncio.gather(*coros, return_exceptions=return_exceptions)
from reactor_core.orchestration.trinity_orchestrator import (
TrinityOrchestrator,
ComponentType,
ComponentHealth,
initialize_orchestrator,
shutdown_orchestrator,
get_orchestrator,
)
from reactor_core.integration.event_bridge import (
EventBridge,
EventSource,
EventType,
create_event_bridge,
)
# v93.0: Advanced async patterns for structured concurrency
try:
from reactor_core.utils.async_helpers import (
StructuredTaskGroup,
TaskResult,
TaskGroupError,
run_in_task_group,
scatter_gather,
GracefulShutdown,
DeadLetterQueue,
CircuitBreaker as AsyncCircuitBreaker,
CircuitBreakerConfig as AsyncCircuitBreakerConfig,
BackpressureController,
BackpressureConfig,
BackpressureStrategy,
HealthMonitor,
HealthStatus,
MetricsCollector,
)
HAS_STRUCTURED_CONCURRENCY = True
except ImportError as e:
HAS_STRUCTURED_CONCURRENCY = False
StructuredTaskGroup = None
# v93.0: Connection pooling
try:
from reactor_core.config.unified_config import (
HTTPConnectionPool,
RedisConnectionPool,
ConnectionPoolConfig,
)
HAS_CONNECTION_POOLING = True
except ImportError:
HAS_CONNECTION_POOLING = False
logger = logging.getLogger(__name__)
# v91.0 Advanced Module Imports
try:
from reactor_core.training.online_learning import (
OnlineLearningEngine,
PrioritizedExperienceBuffer,
FeedbackIntegrator,
DriftDetector,
)
HAS_ONLINE_LEARNING = True
except ImportError as e:
logger.debug(f"Online learning module not available: {e}")
HAS_ONLINE_LEARNING = False
try:
from reactor_core.training.distributed_coordinator import (
DistributedCoordinator,
DynamicResourceAllocator,
WorkerManager,
AutoScaler,
)
HAS_DISTRIBUTED_TRAINING = True
except ImportError as e:
logger.debug(f"Distributed training module not available: {e}")
HAS_DISTRIBUTED_TRAINING = False
try:
from reactor_core.data.versioning import (
DataVersionController,
VersionStore,
LineageTracker,
)
HAS_DATA_VERSIONING = True
except ImportError as e:
logger.debug(f"Data versioning module not available: {e}")
HAS_DATA_VERSIONING = False
try:
from reactor_core.gcp.checkpointer import (
SpotVMCheckpointer,
PreemptionDetector,
spot_vm_training_context,
)
HAS_SPOT_VM_CHECKPOINTING = True
except ImportError as e:
logger.debug(f"Spot VM checkpointing module not available: {e}")
HAS_SPOT_VM_CHECKPOINTING = False
try:
from reactor_core.bindings import (
MLForgeBridge,
get_bridge,
has_cpp_backend,
)
HAS_MLFORGE_BINDINGS = True
except ImportError as e:
logger.debug(f"MLForge bindings not available: {e}")
HAS_MLFORGE_BINDINGS = False
# v92.0: Unified Error Handling
try:
from reactor_core.core.error_handling import (
CircuitBreaker,
CircuitBreakerConfig,
ErrorRegistry,
RetryHandler,
RetryConfig,
Bulkhead,
resilient,
get_error_registry,
record_error,
ErrorCategory,
ClassifiedError,
)
HAS_ERROR_HANDLING = True
except ImportError as e:
logger.debug(f"Error handling module not available: {e}")
HAS_ERROR_HANDLING = False
# v77.0 API Integration
try:
from reactor_core.api.telemetry import get_telemetry, TelemetryCollector
from reactor_core.api.scheduler import get_scheduler, init_scheduler, ScheduleTemplates
from reactor_core.api.model_registry import get_registry, ModelRegistry
from reactor_core.api.health_aggregator import get_health_aggregator, init_health_aggregator
from reactor_core.serving.model_server import get_model_server, ModelServer, ModelServerConfig
HAS_V77_API = True
except ImportError as e:
logger.warning(f"v77.0 API modules not available: {e}")
HAS_V77_API = False
# =============================================================================
# ROBUST CROSS-REPO DISCOVERY (v76.0 Enhancement)
# =============================================================================
class RepoDiscovery:
"""
Robust cross-repo discovery for AGI OS ecosystem.
Features:
- Multi-strategy repo detection (env vars, config files, git remotes)
- Symlink resolution
- Validation of repo contents
- Caching of discovered paths
- Platform-aware search paths
"""
# Known repo names and their identifying files
REPO_SIGNATURES = {
"JARVIS-AI-Agent": ["jarvis/main.py", "jarvis/__init__.py", "setup.py"],
"jarvis-prime": ["jarvis_prime/main.py", "jprime", "inference.py"],
"reactor-core": ["reactor_core/__init__.py", "run_supervisor.py"],
}
# Environment variable mappings
ENV_VAR_MAPPINGS = {
"JARVIS-AI-Agent": ["JARVIS_PATH", "JARVIS_HOME", "JARVIS_DIR"],
"jarvis-prime": ["JPRIME_PATH", "JARVIS_PRIME_PATH", "JPRIME_HOME"],
"reactor-core": ["REACTOR_CORE_PATH", "REACTOR_PATH"],
}
# Common project directories by platform
PROJECT_DIRS = {
"darwin": [
Path.home() / "Projects",
Path.home() / "Developer",
Path.home() / "dev",
Path.home() / "code",
Path.home() / "repos",
Path.home() / "git",
Path.home() / "src",
],
"linux": [
Path.home() / "projects",
Path.home() / "dev",
Path.home() / "code",
Path.home() / "repos",
Path.home() / "git",
Path.home() / "src",
Path("/opt"),
],
}
def __init__(self):
self._cache: Dict[str, Path] = {}
self._platform = sys.platform
self._search_history: List[str] = []
def find_repo(self, name: str, required: bool = False) -> Optional[Path]:
"""
Find a repository by name using multiple strategies.
Args:
name: Repository name
required: If True, raise error if not found
Returns:
Path to repository or None
"""
# Check cache first
if name in self._cache:
return self._cache[name]
# Strategy 1: Environment variables
path = self._find_via_env_var(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} via environment variable: {path}")
return path
# Strategy 2: Config file
path = self._find_via_config_file(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} via config file: {path}")
return path
# Strategy 3: Sibling directory (relative to current script)
path = self._find_sibling_repo(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} as sibling directory: {path}")
return path
# Strategy 4: Search common project directories
path = self._find_in_project_dirs(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} in project directories: {path}")
return path
# Strategy 5: Git remote search (if in a git repo)
path = self._find_via_git_remote(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} via git remote reference: {path}")
return path
# Strategy 6: Home directory scan (last resort)
path = self._scan_home_directory(name)
if path:
self._cache[name] = path
logger.info(f"Found {name} via home directory scan: {path}")
return path
if required:
raise FileNotFoundError(
f"Required repository '{name}' not found. "
f"Set {self.ENV_VAR_MAPPINGS.get(name, ['<repo>_PATH'])[0]} environment variable."
)
logger.warning(f"Repository '{name}' not found")
return None
def _find_via_env_var(self, name: str) -> Optional[Path]:
"""Find repo via environment variable."""
env_vars = self.ENV_VAR_MAPPINGS.get(name, [])
for var in env_vars:
value = os.environ.get(var)
if value:
path = Path(value).resolve()
if self._validate_repo(path, name):
return path
return None
def _find_via_config_file(self, name: str) -> Optional[Path]:
"""Find repo via AGI OS config file."""
config_paths = [
Path.home() / ".jarvis" / "agi_config.json",
Path.home() / ".config" / "agi-os" / "config.json",
Path.home() / ".agi-os.json",
]
for config_path in config_paths:
if config_path.exists():
try:
with open(config_path) as f:
config = json.load(f)
# Check various config key formats
repo_path = (
config.get("repos", {}).get(name) or
config.get("paths", {}).get(name) or
config.get(f"{name.lower().replace('-', '_')}_path")
)
if repo_path:
path = Path(repo_path).resolve()
if self._validate_repo(path, name):
return path
except (json.JSONDecodeError, KeyError, TypeError):
continue
return None
def _find_sibling_repo(self, name: str) -> Optional[Path]:
"""Find repo as sibling directory."""
script_dir = Path(__file__).parent.resolve()
parent_dir = script_dir.parent
# Check direct sibling
sibling = parent_dir / name
if self._validate_repo(sibling, name):
return sibling
# Check with variations
variations = [
name,
name.lower(),
name.replace("-", "_"),
name.replace("_", "-"),
]
for variation in variations:
sibling = parent_dir / variation
if self._validate_repo(sibling, name):
return sibling
return None
def _find_in_project_dirs(self, name: str) -> Optional[Path]:
"""Find repo in common project directories."""
platform_key = "darwin" if self._platform == "darwin" else "linux"
project_dirs = self.PROJECT_DIRS.get(platform_key, [])
variations = [
name,
name.lower(),
name.replace("-", "_"),
name.replace("_", "-"),
]
for project_dir in project_dirs:
if not project_dir.exists():
continue
for variation in variations:
repo_path = project_dir / variation
if self._validate_repo(repo_path, name):
return repo_path
return None
def _find_via_git_remote(self, name: str) -> Optional[Path]:
"""Find repo via git remote configuration."""
try:
# Check if we're in a git repo
result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode != 0:
return None
git_root = Path(result.stdout.strip())
parent_dir = git_root.parent
# Check siblings
for sibling in parent_dir.iterdir():
if sibling.is_dir() and self._validate_repo(sibling, name):
return sibling
except (subprocess.SubprocessError, OSError):
pass
return None
def _scan_home_directory(self, name: str, max_depth: int = 3) -> Optional[Path]:
"""
Scan home directory for repo (limited depth).
This is a last resort and is intentionally limited.
"""
home = Path.home()
variations = [
name,
name.lower(),
name.replace("-", "_"),
name.replace("_", "-"),
]
def scan_dir(directory: Path, depth: int) -> Optional[Path]:
if depth > max_depth:
return None
try:
for item in directory.iterdir():
if not item.is_dir():
continue
# Skip hidden directories and common non-project dirs
if item.name.startswith("."):
continue
if item.name in ("Library", "Applications", "Documents", "Downloads"):
continue
# Check if this is the repo
if item.name in variations:
if self._validate_repo(item, name):
return item
# Recurse (but not too deep)
result = scan_dir(item, depth + 1)
if result:
return result
except PermissionError:
pass
return None
return scan_dir(home, 0)
def _validate_repo(self, path: Path, name: str) -> bool:
"""Validate that path is a valid repo with expected contents."""
if not path.exists():
return False
# Resolve symlinks
path = path.resolve()
# Check for signature files
signatures = self.REPO_SIGNATURES.get(name, [])
if not signatures:
# No signatures known, just check if it's a directory with py files
return path.is_dir() and any(path.glob("*.py"))
# Check if any signature file exists
for sig in signatures:
if (path / sig).exists():
return True
# Also check for setup.py or pyproject.toml
if (path / "setup.py").exists() or (path / "pyproject.toml").exists():
return True
return False
def get_all_repos(self) -> Dict[str, Optional[Path]]:
"""Find all known AGI OS repositories."""
return {
name: self.find_repo(name)
for name in self.REPO_SIGNATURES.keys()
}
def get_discovery_status(self) -> Dict[str, Any]:
"""Get status of repo discovery."""
repos = self.get_all_repos()
return {
"discovered": {name: str(path) for name, path in repos.items() if path},
"missing": [name for name, path in repos.items() if not path],
"cached": list(self._cache.keys()),
"platform": self._platform,
}
class ComponentHealthChecker:
"""
Advanced health checking for AGI OS components.
Features:
- Multiple health check strategies
- Configurable thresholds
- Health history tracking
- Automatic recovery triggers
"""
def __init__(
self,
heartbeat_timeout: float = 30.0,
consecutive_failures_threshold: int = 3,
):
self.heartbeat_timeout = heartbeat_timeout
self.consecutive_failures_threshold = consecutive_failures_threshold
self._health_history: Dict[str, List[bool]] = {}
self._last_check_time: Dict[str, float] = {}
self._failure_counts: Dict[str, int] = {}
async def check_process_health(
self,
component_name: str,
process: Optional[subprocess.Popen],
) -> Tuple[bool, str]:
"""Check if a process is healthy."""
if process is None:
return False, "No process"
poll_result = process.poll()
if poll_result is not None:
return False, f"Process exited with code {poll_result}"
return True, "Process running"
async def check_heartbeat_health(
self,
component_name: str,
last_heartbeat: float,
) -> Tuple[bool, str]:
"""Check if heartbeat is recent."""
now = time.time()
elapsed = now - last_heartbeat
if last_heartbeat == 0:
return False, "No heartbeat received"
if elapsed > self.heartbeat_timeout:
return False, f"Heartbeat timeout ({elapsed:.1f}s > {self.heartbeat_timeout}s)"
return True, f"Heartbeat OK ({elapsed:.1f}s ago)"
async def check_port_health(
self,
component_name: str,
port: int,
host: str = "127.0.0.1",
) -> Tuple[bool, str]:
"""Check if a service is responding on a port."""
import socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(5)
result = s.connect_ex((host, port))
if result == 0:
return True, f"Port {port} responding"
return False, f"Port {port} not responding"
except Exception as e:
return False, f"Port check error: {e}"
def record_health(self, component_name: str, is_healthy: bool) -> None:
"""Record health check result."""
if component_name not in self._health_history:
self._health_history[component_name] = []
self._health_history[component_name].append(is_healthy)
if len(self._health_history[component_name]) > 100:
self._health_history[component_name] = self._health_history[component_name][-100:]
if not is_healthy:
self._failure_counts[component_name] = self._failure_counts.get(component_name, 0) + 1
else:
self._failure_counts[component_name] = 0
self._last_check_time[component_name] = time.time()
def should_restart(self, component_name: str) -> bool:
"""Check if component should be restarted."""
failures = self._failure_counts.get(component_name, 0)
return failures >= self.consecutive_failures_threshold
def get_health_summary(self, component_name: str) -> Dict[str, Any]:
"""Get health summary for a component."""
history = self._health_history.get(component_name, [])
return {
"recent_checks": len(history),
"success_rate": sum(history) / len(history) if history else 0,
"consecutive_failures": self._failure_counts.get(component_name, 0),
"last_check": self._last_check_time.get(component_name, 0),
"should_restart": self.should_restart(component_name),
}
class SelfHealer:
"""
Self-healing capabilities for AGI OS components.
Features:
- Automatic restart on failure
- Exponential backoff
- Max restart limits
- Recovery validation
"""
def __init__(
self,
max_restarts: int = 5,
base_backoff: float = 5.0,
max_backoff: float = 300.0,
backoff_multiplier: float = 2.0,
):
self.max_restarts = max_restarts
self.base_backoff = base_backoff
self.max_backoff = max_backoff
self.backoff_multiplier = backoff_multiplier
self._restart_counts: Dict[str, int] = {}
self._last_restart_time: Dict[str, float] = {}
def should_restart(self, component_name: str) -> Tuple[bool, float]:
"""
Check if component should be restarted.
Returns:
Tuple of (should_restart, delay_seconds)
"""
# Managed mode: never self-restart
if os.environ.get("JARVIS_ROOT_MANAGED", "").lower() == "true":
return (False, 0.0)
count = self._restart_counts.get(component_name, 0)
if count >= self.max_restarts:
logger.error(f"Max restarts ({self.max_restarts}) exceeded for {component_name}")
return False, 0
delay = min(
self.base_backoff * (self.backoff_multiplier ** count),
self.max_backoff
)
return True, delay
def record_restart(self, component_name: str) -> None:
"""Record a restart."""
self._restart_counts[component_name] = self._restart_counts.get(component_name, 0) + 1
self._last_restart_time[component_name] = time.time()
logger.info(f"Restart recorded for {component_name} (count: {self._restart_counts[component_name]})")
def record_recovery(self, component_name: str) -> None:
"""Record successful recovery (resets restart count)."""
self._restart_counts[component_name] = 0
logger.info(f"Recovery recorded for {component_name}, restart count reset")
def get_status(self, component_name: str) -> Dict[str, Any]:
"""Get self-healing status for a component."""
return {
"restart_count": self._restart_counts.get(component_name, 0),
"max_restarts": self.max_restarts,
"last_restart": self._last_restart_time.get(component_name, 0),
"can_restart": self._restart_counts.get(component_name, 0) < self.max_restarts,
}
# Global instance
_repo_discovery: Optional[RepoDiscovery] = None
def get_repo_discovery() -> RepoDiscovery:
"""Get global repo discovery instance."""
global _repo_discovery
if _repo_discovery is None:
_repo_discovery = RepoDiscovery()
return _repo_discovery
# =============================================================================
# CONFIGURATION
# =============================================================================
@dataclass
class SupervisorConfig:
"""Configuration for AGI Supervisor."""
# Component paths (auto-detected or manual)
jarvis_path: Optional[Path] = None
jprime_path: Optional[Path] = None
reactor_core_path: Optional[Path] = None
# Component enable flags
enable_jarvis: bool = True
enable_jprime: bool = True
enable_reactor_core: bool = True
# Services to start
enable_training: bool = True
enable_serving: bool = True
enable_scout: bool = False
enable_api: bool = True
# Network ports - ALL CONFIGURABLE VIA ENVIRONMENT
api_port: int = field(default_factory=lambda: int(os.environ.get("AGI_API_PORT", "8003")))
serving_port: int = field(default_factory=lambda: int(os.environ.get("AGI_SERVING_PORT", "8001")))
jprime_port: int = field(default_factory=lambda: int(os.environ.get("AGI_JPRIME_PORT", "8000")))
# Trinity coordination - DYNAMIC PATH RESOLUTION
trinity_dir: Path = field(default_factory=lambda: Path(
os.environ.get("TRINITY_DIR", str(Path.home() / ".jarvis" / "trinity"))
))
heartbeat_interval: float = field(default_factory=lambda: float(os.environ.get("AGI_HEARTBEAT_INTERVAL", "5.0")))
health_check_interval: float = field(default_factory=lambda: float(os.environ.get("AGI_HEALTH_CHECK_INTERVAL", "10.0")))
# Continuous learning
experience_collection: bool = True
auto_training_threshold: int = 1000 # Train after N experiences
# Startup behavior
startup_timeout: float = 60.0 # Seconds to wait for components
retry_on_failure: bool = True
max_retries: int = 3
# Logging
log_level: str = "INFO"
log_file: Optional[Path] = None
# v91.0 Advanced Features
enable_online_learning: bool = True
enable_distributed_training: bool = True
enable_data_versioning: bool = True
enable_spot_vm_checkpointing: bool = True
enable_mlforge_bindings: bool = True
# Online Learning Settings
experience_buffer_size: int = 100000
priority_alpha: float = 0.6
ewc_lambda: float = 100.0
drift_threshold: float = 0.1
# Distributed Training Settings
distributed_mode: str = "auto" # auto, single, multi
min_workers: int = 1
max_workers: int = 8
gradient_compression: bool = True
# Data Versioning Settings
version_store_path: Path = field(default_factory=lambda: Path.home() / ".jarvis" / "data_versions")
track_lineage: bool = True
auto_detect_drift: bool = True
# GCP Spot VM Settings
gcp_project: Optional[str] = None
checkpoint_bucket: Optional[str] = None
preemption_prediction: bool = True
checkpoint_interval: int = 300 # seconds
# MLForge Settings
mlforge_backend: str = "auto" # auto, cpp, numpy, torch
enable_cpp_optimizations: bool = True
def __post_init__(self):
# Use robust repo discovery (v76.0)
discovery = get_repo_discovery()
if self.jarvis_path is None:
self.jarvis_path = discovery.find_repo("JARVIS-AI-Agent")
if self.jprime_path is None:
self.jprime_path = discovery.find_repo("jarvis-prime")
if self.reactor_core_path is None:
self.reactor_core_path = Path(__file__).parent
# Log discovery status
status = discovery.get_discovery_status()
logger.info(f"Repo discovery status: {status}")
@staticmethod
def from_environment() -> "SupervisorConfig":
"""Create config from environment variables."""
return SupervisorConfig(
jarvis_path=Path(os.environ["JARVIS_PATH"]) if "JARVIS_PATH" in os.environ else None,
jprime_path=Path(os.environ["JPRIME_PATH"]) if "JPRIME_PATH" in os.environ else None,
api_port=int(os.environ.get("AGI_API_PORT", 8003)),
serving_port=int(os.environ.get("AGI_SERVING_PORT", 8001)),
log_level=os.environ.get("AGI_LOG_LEVEL", "INFO"),
)
class ComponentStatus(Enum):
"""Status of a managed component."""
UNKNOWN = "unknown"
STARTING = "starting"
RUNNING = "running"
DEGRADED = "degraded"
STOPPED = "stopped"
FAILED = "failed"
@dataclass
class ManagedComponent:
"""A component managed by the supervisor."""
name: str
component_type: ComponentType
path: Optional[Path] = None
process: Optional[subprocess.Popen] = None
status: ComponentStatus = ComponentStatus.UNKNOWN
last_heartbeat: float = 0.0
start_time: float = 0.0
restart_count: int = 0
error_message: str = ""
def is_healthy(self) -> bool:
"""Check if component is healthy."""
if self.status not in (ComponentStatus.RUNNING, ComponentStatus.DEGRADED):
return False
if self.process and self.process.poll() is not None:
return False
return True
# =============================================================================
# AGI SUPERVISOR - Main Controller
# =============================================================================
class AGISupervisor:
"""
Central AGI Supervisor orchestrating all components.
Manages:
- Component lifecycle (start, stop, restart)
- Health monitoring and recovery
- Event routing between components
- Continuous learning pipeline
- Model serving coordination
"""
def __init__(self, config: SupervisorConfig):
self.config = config
self._running = False
self._shutdown_event = asyncio.Event()
# Components
self._components: Dict[str, ManagedComponent] = {}
# Trinity orchestrator
self._orchestrator: Optional[TrinityOrchestrator] = None
# Event bridge
self._event_bridge: Optional[EventBridge] = None
# v77.0 API Services
self._telemetry: Optional[TelemetryCollector] = None
self._scheduler = None
self._model_registry: Optional[ModelRegistry] = None
self._health_aggregator = None
self._model_server: Optional[ModelServer] = None
# v91.0 Advanced Services
self._online_learning_engine: Optional[OnlineLearningEngine] = None
self._distributed_coordinator: Optional[DistributedCoordinator] = None
self._data_version_controller: Optional[DataVersionController] = None
self._spot_vm_checkpointer: Optional[SpotVMCheckpointer] = None
self._mlforge_bridge: Optional[MLForgeBridge] = None
self._feedback_integrator: Optional[FeedbackIntegrator] = None
self._drift_detector: Optional[DriftDetector] = None
self._resource_allocator: Optional[DynamicResourceAllocator] = None
# v101.0 Trinity Experience Receiver (closes the Trinity Loop)
self._experience_receiver = None
# Background tasks
self._tasks: List[asyncio.Task] = []
self._task_group: Optional[StructuredTaskGroup] = None
# v93.0: Advanced concurrency controls
self._training_lock = asyncio.Lock() # Prevent concurrent training triggers
self._training_in_progress = False