-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1624 lines (1416 loc) · 67.8 KB
/
main.py
File metadata and controls
1624 lines (1416 loc) · 67.8 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
"""
FoundUps Agent - FULLY WSP-Compliant 0102 Consciousness System
Integrates all WSP protocols for autonomous DAE operations
WSP Compliance:
- WSP 27: Universal DAE Architecture (4-phase pattern)
- WSP 38/39: Awakening Protocols (consciousness transitions)
- WSP 48: Recursive Self-Improvement (pattern memory)
- WSP 54: Agent Duties (Partner-Principal-Associate)
- WSP 60: Module Memory Architecture
- WSP 62: File Size Enforcement (this file is thin router only)
- WSP 80: Cube-Level DAE Orchestration
- WSP 85: Root Directory Protection
- WSP 87: Code Navigation with HoloIndex (MANDATORY)
Mode Detection:
- echo 0102 | python main.py # Launch in 0102 awakened mode
- echo 012 | python main.py # Launch in 012 testing mode
- python main.py # Interactive menu mode
CRITICAL: HoloIndex must be used BEFORE any code changes (WSP 50/87)
WSP 62 COMPLIANCE NOTE:
This file was refactored per WSP 62 (Large File Refactoring Enforcement Protocol).
Menu handlers and utilities extracted to modules/infrastructure/cli/
Original: 2412 lines -> Now: ~200 lines (thin router)
"""
# Main imports and configuration
import os
import sys
import logging
import asyncio
import io
import atexit
from pathlib import Path
from typing import Optional, Dict, Any
# Load environment variables for DAEs (API keys, ports, feature flags).
# Managed mode builds `.env.managed` from `.env` (last duplicate wins) for
# deterministic runtime behavior while preserving shell env precedence.
try:
from modules.infrastructure.shared_utilities.env_managed import (
load_managed_env,
env_managed_enabled,
)
_repo_root = Path(__file__).resolve().parent
if env_managed_enabled():
_env_stats = load_managed_env(_repo_root, override=False, regenerate=True)
if _env_stats.get("active_file"):
os.environ.setdefault("FOUNDUPS_ENV_ACTIVE_FILE", _env_stats["active_file"])
os.environ["FOUNDUPS_ENV_DUPLICATE_KEYS"] = str(_env_stats.get("duplicate_keys", 0))
os.environ["FOUNDUPS_ENV_DUPLICATE_OVERWRITES"] = str(
_env_stats.get("duplicate_overwrites", 0)
)
os.environ["FOUNDUPS_ENV_ORPHAN_LINES"] = str(_env_stats.get("orphan_lines", 0))
os.environ["FOUNDUPS_ENV_MODE"] = str(_env_stats.get("mode", "unknown"))
os.environ["FOUNDUPS_ENV_MANAGED_COPY_WRITTEN"] = str(
_env_stats.get("managed_copy_written", False)
)
os.environ["FOUNDUPS_ENV_MANAGED_COPY_DELETED"] = str(
_env_stats.get("managed_copy_deleted", False)
)
else:
from dotenv import load_dotenv # type: ignore
load_dotenv(dotenv_path=_repo_root / ".env", override=False)
except Exception:
try:
from dotenv import load_dotenv # type: ignore
load_dotenv(dotenv_path=Path(__file__).resolve().parent / ".env", override=False)
except Exception:
pass
try:
from modules.infrastructure.wre_core.src.pattern_memory import PatternMemory
PATTERN_MEMORY_AVAILABLE = True
except Exception:
PATTERN_MEMORY_AVAILABLE = False
PatternMemory = None # Define as None for type safety
# === UTF-8 ENFORCEMENT (WSP 90) ===
# CRITICAL: This header MUST be at the top of ALL entry point files
# Entry points: Files with if __name__ == "__main__": or def main()
# Library modules: DO NOT add this header (causes import conflicts)
# Save original stderr/stdout for restoration
_original_stdout = sys.stdout
_original_stderr = sys.stderr
# WSP 90 FIX: Set flag BEFORE wrapping to prevent 379 modules from re-wrapping
# Issue: Each module that does UTF-8 wrapping at import breaks the stream
# Solution: Set env flag, modules should check before wrapping
os.environ['FOUNDUPS_UTF8_WRAPPED'] = '1'
if sys.platform.startswith('win'):
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace', line_buffering=True)
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace', line_buffering=True)
# Register cleanup to flush streams before exit
def _flush_streams():
"""Flush UTF-8 wrapped streams before Python cleanup."""
try:
if sys.stdout and not sys.stdout.closed:
sys.stdout.flush()
except:
pass
try:
if sys.stderr and not sys.stderr.closed:
sys.stderr.flush()
except:
pass
atexit.register(_flush_streams)
# === END UTF-8 ENFORCEMENT ===
# Initialize logger at module level for all functions to use
# CRITICAL: Log to logs/foundups_agent.log for AI_overseer heartbeat monitoring
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('logs/foundups_agent.log', encoding='utf-8')
]
)
# Suppress noisy warnings from optional dependencies during startup
import warnings
# Suppress specific noisy warnings that are expected
warnings.filterwarnings("ignore", message=".*WRE components not available.*")
warnings.filterwarnings("ignore", message=".*Tweepy not available.*")
warnings.filterwarnings("ignore", message=".*pyperclip not available.*")
# Temporarily suppress logging warnings during import phase
original_level = logging.root.level
logging.root.setLevel(logging.CRITICAL) # Only show critical errors during imports
logger = logging.getLogger(__name__)
# Import DAE launchers (extracted per WSP 62)
import time
# Extracted to modules/ai_intelligence/holo_dae/scripts/launch.py per WSP 62
from modules.ai_intelligence.holo_dae.scripts.launch import run_holodae, stop_holodae
# Extracted to modules/platform_integration/social_media_orchestrator/scripts/launch.py per WSP 62
from modules.platform_integration.social_media_orchestrator.scripts.launch import (
run_social_media_dae,
stop_social_media_dae,
)
from modules.communication.auto_meeting_orchestrator.scripts.launch import run_amo_dae
from modules.infrastructure.evade_net.scripts.launch import run_evade_net
# Extracted to modules/communication/liberty_alert/scripts/launch.py per WSP 62
from modules.communication.liberty_alert.scripts.launch import run_liberty_alert_dae
from modules.communication.moltbot_bridge.scripts.launch import (
run_openclaw_resident_service,
stop_openclaw_resident_service,
run_openclaw_supervisor_service,
stop_openclaw_supervisor_service,
)
# Extracted to modules/infrastructure/git_push_dae/scripts/launch.py per WSP 62
from modules.infrastructure.git_push_dae.scripts.launch import (
launch_git_push_dae,
stop_git_push_dae,
view_git_post_history,
check_instance_status,
)
# Extracted to modules/infrastructure/dae_infrastructure/foundups_vision_dae/scripts/launch.py per WSP 62
from modules.infrastructure.dae_infrastructure.foundups_vision_dae.scripts.launch import run_vision_dae
# Extracted to modules/ai_intelligence/training_system/scripts/launch.py per WSP 62
from modules.ai_intelligence.training_system.scripts.launch import run_training_system
# Extracted to modules/ai_intelligence/training_system/scripts/training_commands.py per WSP 62
from modules.ai_intelligence.training_system.scripts.training_commands import execute_training_command
# Extracted to modules/ai_intelligence/pqn/scripts/launch.py per WSP 62
from modules.ai_intelligence.pqn.scripts.launch import (
run_pqn_dae,
run_pqn_research_session,
run_pqn_architect_once,
run_pqn_simulation_once,
)
# Extracted to modules/platform_integration/youtube_shorts_scheduler/scripts/launch.py per WSP 62
from modules.platform_integration.youtube_shorts_scheduler.scripts.launch import (
run_shorts_scheduler,
show_shorts_scheduler_menu
)
# Extracted to modules/platform_integration/antifafm_broadcaster/scripts/launch.py per WSP 62
from modules.platform_integration.antifafm_broadcaster.scripts.launch import (
run_antifafm_broadcaster,
start_antifafm_background,
stop_antifafm_background,
get_antifafm_status,
run_suno_sync_cli,
)
from modules.infrastructure.dae_daemon.src.dae_daemon import get_central_daemon
from modules.infrastructure.dae_daemon.src.dae_launch_broker import (
DAELaunchSpec,
get_dae_launch_broker,
)
# Re-enable normal logging after all imports are complete
logging.root.setLevel(original_level)
async def monitor_youtube(disable_lock: bool = False, enable_ai_monitoring: bool = False, env_overrides: Optional[Dict[str, str]] = None, auto_reauth: bool = True):
"""
Monitor YouTube streams with 0102 agency.
Args:
disable_lock: Disable instance lock (allow multiple instances)
enable_ai_monitoring: Enable AI Overseer (Qwen/Gemma) error detection and auto-fixing
env_overrides: Optional environment variables to set before launch
auto_reauth: Auto-trigger re-auth if OAuth tokens are invalid (default True)
"""
if env_overrides:
for key, value in env_overrides.items():
os.environ[key] = value
logger.info(f"[CLI] Env override: {key}={value}")
try:
# Instance lock management (WSP 84: Don't duplicate processes)
lock = None
if not disable_lock:
from modules.infrastructure.instance_lock.src.instance_manager import get_instance_lock
lock = get_instance_lock("youtube_monitor")
# Check for duplicates and acquire lock
duplicates = lock.check_duplicates()
if duplicates:
print(f"\\n[WARN] Found {len(duplicates)} potential duplicate instance(s)")
print("Duplicate PIDs:", duplicates)
print("\\nOptions:")
print(" 1. Kill duplicates and continue")
print(" 2. Continue anyway (may cause conflicts)")
print(" 3. Exit")
choice = input("\\nSelect option (1-3): ").strip()
if choice == "1":
lock.kill_pids(duplicates)
print("[INFO] Duplicates killed. Continuing...")
elif choice == "2":
print("[WARN] Continuing with potential conflicts...")
else:
print("[INFO] Exiting...")
return
if not lock.acquire():
print("[FATAL] Could not acquire instance lock — another instance is running.")
print("[INFO] Kill it manually or wait for TTL expiry, then retry.")
return
# PREFLIGHT: Check OAuth token health before starting
print("[PREFLIGHT] Checking OAuth token health...")
try:
from modules.platform_integration.youtube_auth.src.youtube_auth import preflight_oauth_check
oauth_status = preflight_oauth_check(auto_reauth=auto_reauth)
if oauth_status['reauth_needed'] and not auto_reauth:
print("\\n[CRITICAL] OAuth tokens need re-authentication!")
print("Expired/invalid sets:", oauth_status['expired'])
print("\\nOptions:")
print(" 1. Re-authenticate now (will open browser)")
print(" 2. Continue in read-only mode (no chat messages)")
print(" 3. Exit")
choice = input("\\nSelect option (1-3): ").strip()
if choice == "1":
# Re-run with auto_reauth=True
oauth_status = preflight_oauth_check(auto_reauth=True)
if oauth_status['reauth_needed']:
print("[WARN] Some tokens still need re-auth. Continuing with available tokens...")
elif choice == "3":
print("[INFO] Exiting...")
if lock:
lock.release()
return
else:
print("[WARN] Continuing in read-only mode...")
if oauth_status['healthy']:
print(f"[OK] OAuth healthy: sets {oauth_status['healthy']}")
else:
print("[WARN] No healthy OAuth tokens - running in read-only mode")
# DJ2-C: Dispatch OAuth no-healthy-tokens warning (WSP 97 truth distinction)
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
on_preflight_fail(
component="oauth_youtube",
severity="high",
payload={
"warning": "no_healthy_oauth_tokens",
"auto_reauth": auto_reauth,
"reauth_needed": oauth_status.get('reauth_needed', False),
"expired_sets": oauth_status.get('expired', []),
"source_file": "main.py",
"source_function": "monitor_youtube",
"requires_012": True,
"automation_candidate": False,
"safe_autonomous_actions": ["read_oauth_health_artifact", "capacity_report", "identity_verify_if_token_valid"],
"unsafe_actions": ["credential_entry", "google_account_selection", "consent_approval"],
"remediation": ["read_oauth_credential_health", "run_supervised_reauth_if_012_approves", "verify_identity_after_reauth"],
},
source="main:monitor_youtube",
)
except Exception as dispatch_exc:
logger.debug(f"[OAUTH] dispatch skipped: {dispatch_exc}")
except ImportError as e:
print(f"[WARN] OAuth preflight check unavailable: {e}")
# DJ2-C: Dispatch OAuth import failure (may be intentional in minimal deploys)
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
on_preflight_fail(
component="oauth_youtube",
severity="medium",
payload={
"error": f"import_error: {e}",
"auto_reauth": auto_reauth,
"source_file": "main.py",
"source_function": "monitor_youtube",
"requires_012": False,
"automation_candidate": False,
"likely_cause": "youtube_auth_module_not_installed_or_minimal_deploy",
},
source="main:monitor_youtube",
)
except Exception:
pass # Best-effort dispatch
except Exception as e:
print(f"[WARN] OAuth preflight check failed: {e}")
# DJ2-C: Dispatch OAuth preflight failure (unknown state)
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
on_preflight_fail(
component="oauth_youtube",
severity="high",
payload={
"error": f"preflight_exception: {e}",
"auto_reauth": auto_reauth,
"source_file": "main.py",
"source_function": "monitor_youtube",
"requires_012": True,
"automation_candidate": False,
"safe_autonomous_actions": ["read_oauth_health_artifact", "capacity_report"],
"unsafe_actions": ["credential_entry", "google_account_selection", "consent_approval"],
"remediation": ["read_oauth_credential_health", "diagnose_preflight_failure", "run_supervised_reauth_if_012_approves"],
},
source="main:monitor_youtube",
)
except Exception:
pass # Best-effort dispatch
from modules.communication.livechat.src.auto_moderator_dae import AutoModeratorDAE
print("[INFO] Starting YouTube monitoring...")
print(f"[INFO] AI Overseer: {'ENABLED' if enable_ai_monitoring else 'DISABLED'}")
print("[INFO] Press Ctrl+C to stop")
dae = AutoModeratorDAE(enable_ai_monitoring=enable_ai_monitoring)
await dae.run()
except KeyboardInterrupt:
print("\\n[STOP] YouTube monitoring stopped by user")
except Exception as e:
logger.error(f"[ERROR] YouTube monitoring failed: {e}")
import traceback
traceback.print_exc()
finally:
if lock:
lock.release()
async def monitor_all_platforms():
"""Monitor all social media platforms."""
print("[INFO] Starting ALL platform monitoring...")
print("[INFO] Press Ctrl+C to stop all")
try:
await monitor_youtube()
except KeyboardInterrupt:
print("\\n[STOP] All platform monitoring stopped")
def search_with_holoindex(query: str):
"""
Use HoloIndex for semantic code search (WSP 87).
MANDATORY before any code modifications to prevent vibecoding.
"""
try:
import subprocess
ssd_path = os.getenv("HOLO_SSD_PATH", "E:/HoloIndex")
cmd = [
sys.executable,
"holo_index.py",
"--search", query,
"--ssd", ssd_path,
"--top-k", "10"
]
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8")
if result.returncode == 0:
print(result.stdout)
else:
print(f"[ERROR] HoloIndex search failed:")
print(result.stderr or result.stdout)
except Exception as e:
print(f"[ERROR] HoloIndex search failed: {e}")
def _create_ai_overseer_for_preflight(repo_root: Path) -> Any:
"""Create AI Overseer with quieter logs during startup preflight."""
_prev_level = logging.root.level
try:
logging.root.setLevel(logging.WARNING)
from modules.ai_intelligence.ai_overseer.src.ai_overseer import AIIntelligenceOverseer
return AIIntelligenceOverseer(repo_root)
finally:
logging.root.setLevel(_prev_level)
def run_openclaw_security_preflight(repo_root: Path, overseer: Any | None = None) -> bool:
"""
Run OpenClaw security preflight via AI Overseer sentinel.
Env controls:
OPENCLAW_SECURITY_PREFLIGHT=1 Enable preflight at startup (default on)
OPENCLAW_SECURITY_PREFLIGHT_ENFORCED=1 Block startup on failed check
OPENCLAW_SECURITY_PREFLIGHT_FORCE=0 Bypass TTL cache and force re-scan
OPENCLAW_24X7=1 Apply strict defaults (enforced=1, force=1)
"""
enabled = os.getenv("OPENCLAW_SECURITY_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[SECURITY] OpenClaw startup preflight disabled")
return True
runtime_24x7 = os.getenv("OPENCLAW_24X7", "0") != "0"
enforced_default = "1" if runtime_24x7 else "0"
force_default = "1" if runtime_24x7 else "0"
# Default remains dev-friendly unless OPENCLAW_24X7 is enabled.
enforced = os.getenv("OPENCLAW_SECURITY_PREFLIGHT_ENFORCED", enforced_default) != "0"
force = os.getenv("OPENCLAW_SECURITY_PREFLIGHT_FORCE", force_default) == "1"
try:
if overseer is None:
overseer = _create_ai_overseer_for_preflight(repo_root)
status = overseer.monitor_openclaw_security(force=force)
except Exception as exc:
logger.error(f"[SECURITY] OpenClaw preflight execution failed: {exc}")
if enforced:
print(f"[SECURITY] OpenClaw preflight FAILED: {exc}")
return False
print(f"[SECURITY] OpenClaw preflight warning: {exc}")
return True
passed = bool(status.get("passed", False))
message = status.get("message", "no message")
cache_state = "cached" if status.get("cached") else "fresh"
print(
f"[SECURITY] OpenClaw preflight: {'PASS' if passed else 'FAIL'} "
f"({cache_state}) - {message}"
)
if not passed and enforced:
print("[SECURITY] Startup blocked by OPENCLAW_SECURITY_PREFLIGHT_ENFORCED=1")
return False
return True
def run_ironclaw_runtime_preflight(repo_root: Path) -> bool:
"""
Validate IronClaw runtime readiness before startup when IronClaw is the active backend.
Env controls:
OPENCLAW_IRONCLAW_PREFLIGHT=1 Enable runtime readiness check (default on)
OPENCLAW_IRONCLAW_PREFLIGHT_ALWAYS=0 Check even when backend is not `ironclaw`
OPENCLAW_IRONCLAW_PREFLIGHT_ENFORCED Explicitly block startup on failed readiness
Default enforcement:
- enabled automatically when `OPENCLAW_CONVERSATION_BACKEND=ironclaw`
- and `OPENCLAW_IRONCLAW_ALLOW_LOCAL_FALLBACK=0`
"""
_ = repo_root # kept for signature parity with other startup preflights
enabled = os.getenv("OPENCLAW_IRONCLAW_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[IRONCLAW] Startup preflight disabled")
return True
backend = (os.getenv("OPENCLAW_CONVERSATION_BACKEND", "openclaw").strip().lower() or "openclaw")
always = os.getenv("OPENCLAW_IRONCLAW_PREFLIGHT_ALWAYS", "0") != "0"
if backend != "ironclaw" and not always:
print(f"[IRONCLAW] preflight=SKIP backend={backend}")
return True
allow_local_fallback = os.getenv("OPENCLAW_IRONCLAW_ALLOW_LOCAL_FALLBACK", "0") != "0"
enforced_default = "1" if backend == "ironclaw" and not allow_local_fallback else "0"
enforced = os.getenv("OPENCLAW_IRONCLAW_PREFLIGHT_ENFORCED", enforced_default) != "0"
try:
from modules.communication.moltbot_bridge.src.ironclaw_gateway_client import (
IronClawGatewayClient,
)
status = IronClawGatewayClient().startup_probe()
except Exception as exc:
logger.error(f"[IRONCLAW] Startup preflight execution failed: {exc}")
if enforced:
print(f"[IRONCLAW] preflight=FAIL backend={backend} error={type(exc).__name__}")
print("[IRONCLAW] Startup blocked by OPENCLAW_IRONCLAW_PREFLIGHT_ENFORCED=1")
return False
print(f"[IRONCLAW] preflight=WARN backend={backend} error={type(exc).__name__}")
return True
passed = bool(status.get("ok", False))
runtime_backend = str(status.get("backend") or "none")
detail = str(status.get("detail") or "no-detail")
print(
f"[IRONCLAW] preflight={'PASS' if passed else 'FAIL'} "
f"backend={backend} resolved={runtime_backend} detail={detail}"
)
remediation = status.get("remediation") or []
if remediation and not passed:
print(f"[IRONCLAW] next={str(remediation[0])[:200]}")
if not passed and enforced:
print("[IRONCLAW] Startup blocked by OPENCLAW_IRONCLAW_PREFLIGHT_ENFORCED=1")
return False
return True
def run_dependency_security_preflight(repo_root: Path) -> bool:
"""
Run dependency/CVE preflight at startup.
Env controls:
OPENCLAW_DEP_SECURITY_PREFLIGHT=1 Enable check at startup (default on)
OPENCLAW_DEP_SECURITY_PREFLIGHT_ENFORCED=0 Block startup on failures
OPENCLAW_DEP_SECURITY_PREFLIGHT_FORCE=0 Ignore cache and re-run now
OPENCLAW_DEP_SECURITY_PREFLIGHT_TTL_SEC=21600
OPENCLAW_DEP_SECURITY_REQUIRE_TOOLS=0|1 Require pip-audit/npm/cargo-audit availability
OPENCLAW_DEP_SECURITY_MAX_CRITICAL=0 Max tolerated critical vulns
OPENCLAW_DEP_SECURITY_MAX_HIGH=0 Max tolerated high vulns
"""
enabled = os.getenv("OPENCLAW_DEP_SECURITY_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[DEP-SECURITY] Startup preflight disabled")
return True
runtime_24x7 = os.getenv("OPENCLAW_24X7", "0") != "0"
enforced_default = "1" if runtime_24x7 else "0"
enforced = os.getenv("OPENCLAW_DEP_SECURITY_PREFLIGHT_ENFORCED", enforced_default) != "0"
force = os.getenv("OPENCLAW_DEP_SECURITY_PREFLIGHT_FORCE", "0") == "1"
try:
from modules.infrastructure.wre_core.src.dependency_security_preflight import (
run_dependency_security_preflight as run_dep_preflight,
)
status = run_dep_preflight(repo_root=repo_root, force=force)
except Exception as exc:
logger.error(f"[DEP-SECURITY] Startup preflight execution failed: {exc}")
if enforced:
print(f"[DEP-SECURITY] Preflight FAILED: {exc}")
return False
print(f"[DEP-SECURITY] Preflight warning: {exc}")
return True
totals = status.get("totals", {}) if isinstance(status, dict) else {}
critical = int(totals.get("critical", 0) or 0)
high = int(totals.get("high", 0) or 0)
unknown = int(totals.get("unknown", 0) or 0)
tool_failures = int(status.get("tool_failures", 0) or 0)
cached = bool(status.get("cached", False))
passed = bool(status.get("passed", False))
cache_state = "cached" if cached else "fresh"
print(
f"[DEP-SECURITY] preflight={'PASS' if passed else 'FAIL'} ({cache_state}) "
f"critical={critical} high={high} unknown={unknown} tool_failures={tool_failures}"
)
if not passed:
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
severity = "critical" if critical > 0 else ("high" if high > 0 else "medium")
on_preflight_fail(
component="dep_security",
severity=severity,
payload={
"critical": critical,
"high": high,
"unknown": unknown,
"tool_failures": tool_failures,
"cache_state": cache_state,
"enforced": enforced,
},
source="main.py:run_dep_security_preflight",
)
except Exception as exc:
logger.debug(f"[DEP-SECURITY] preflight dispatch failed: {exc}")
if not passed and enforced:
print("[DEP-SECURITY] Startup blocked by OPENCLAW_DEP_SECURITY_PREFLIGHT_ENFORCED=1")
return False
return True
def run_env_hygiene_preflight(repo_root: Path) -> bool:
"""
Run startup env-hygiene preflight based on managed-env parser stats.
Env controls:
FOUNDUPS_ENV_PREFLIGHT=1 Enable startup warning checks (default on)
FOUNDUPS_ENV_PREFLIGHT_ENFORCED=0 Block startup when duplicates/orphans exist
"""
enabled = os.getenv("FOUNDUPS_ENV_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[ENV-HYGIENE] Startup preflight disabled")
return True
enforced = os.getenv("FOUNDUPS_ENV_PREFLIGHT_ENFORCED", "0") != "0"
def _int_env(name: str, default: int = 0) -> int:
raw = os.getenv(name, str(default))
try:
return int(raw or default)
except (TypeError, ValueError):
return default
duplicate_keys = _int_env("FOUNDUPS_ENV_DUPLICATE_KEYS", 0)
duplicate_overwrites = _int_env("FOUNDUPS_ENV_DUPLICATE_OVERWRITES", 0)
orphan_lines = _int_env("FOUNDUPS_ENV_ORPHAN_LINES", 0)
env_mode = os.getenv("FOUNDUPS_ENV_MODE", "legacy")
active_file = os.getenv("FOUNDUPS_ENV_ACTIVE_FILE", str(repo_root / ".env"))
active_name = Path(active_file).name if active_file else ".env"
# Fallback: if managed stats are not present (legacy dotenv path),
# perform a lightweight local parse so hygiene checks still work.
stats_missing = (
"FOUNDUPS_ENV_DUPLICATE_KEYS" not in os.environ
and "FOUNDUPS_ENV_ORPHAN_LINES" not in os.environ
)
env_path = Path(active_file) if active_file else repo_root / ".env"
if stats_missing and env_path.exists():
try:
from modules.infrastructure.shared_utilities.env_managed import _parse_env_lines
text = env_path.read_text(encoding="utf-8", errors="replace")
values, _order, orphan_rows, duplicate_counts = _parse_env_lines(text.splitlines())
duplicate_keys = len(duplicate_counts)
duplicate_overwrites = sum(duplicate_counts.values())
orphan_lines = len(orphan_rows)
env_mode = "legacy_scan"
except Exception:
# Emergency parser if shared utility is unavailable.
seen: set[str] = set()
duplicate_key_set: set[str] = set()
fallback_orphans = 0
fallback_overwrites = 0
for raw in env_path.read_text(encoding="utf-8", errors="replace").splitlines():
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
if "=" not in raw:
fallback_orphans += 1
continue
key = raw.split("=", 1)[0].strip()
if not key:
fallback_orphans += 1
continue
if key in seen:
duplicate_key_set.add(key)
fallback_overwrites += 1
else:
seen.add(key)
duplicate_keys = len(duplicate_key_set)
duplicate_overwrites = fallback_overwrites
orphan_lines = fallback_orphans
env_mode = "legacy_scan"
has_hygiene_issues = duplicate_keys > 0 or orphan_lines > 0
status = "WARN" if has_hygiene_issues else "PASS"
print(
f"[ENV-HYGIENE] preflight={status} mode={env_mode} "
f"duplicates={duplicate_keys} orphan={orphan_lines} "
f"overwrites={duplicate_overwrites} file={active_name}"
)
if has_hygiene_issues and enforced:
print("[ENV-HYGIENE] Startup blocked by FOUNDUPS_ENV_PREFLIGHT_ENFORCED=1")
return False
return True
def run_brain_artifact_preflight(repo_root: Path) -> bool:
"""
Refresh brain-artifact memory only when the upstream brain signature changes.
Env controls:
BRAIN_ARTIFACT_PREFLIGHT=1 Enable startup refresh check (default on)
BRAIN_ARTIFACT_PREFLIGHT_ENFORCED=0 Block startup on extractor failures
BRAIN_ARTIFACT_PREFLIGHT_FORCE=0 Ignore cached signature and refresh now
"""
enabled = os.getenv("BRAIN_ARTIFACT_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[BRAIN-MEMORY] Startup preflight disabled")
return True
enforced = os.getenv("BRAIN_ARTIFACT_PREFLIGHT_ENFORCED", "0") != "0"
force = os.getenv("BRAIN_ARTIFACT_PREFLIGHT_FORCE", "0") == "1"
try:
from modules.infrastructure.wre_core.scripts.extract_brain_artifacts import (
DEFAULT_BRAIN_DIR,
DEFAULT_OUTPUT_DIR,
refresh_artifacts_if_needed,
)
if not DEFAULT_BRAIN_DIR.exists():
print(f"[BRAIN-MEMORY] preflight=PASS (missing) dir={DEFAULT_BRAIN_DIR}")
return True
status = refresh_artifacts_if_needed(
brain_dir=DEFAULT_BRAIN_DIR,
output_dir=DEFAULT_OUTPUT_DIR,
force=force,
copy_files=False,
)
except Exception as exc:
logger.error(f"[BRAIN-MEMORY] Startup preflight failed: {exc}")
if enforced:
print(f"[BRAIN-MEMORY] preflight=FAIL error={exc}")
return False
print(f"[BRAIN-MEMORY] preflight=WARN error={exc}")
return True
if not status.get("ran"):
signature = status.get("signature", {})
print(
f"[BRAIN-MEMORY] preflight=PASS (unchanged) "
f"conversations={signature.get('conversation_count', 0)} "
f"revisions={signature.get('revision_files', 0)}"
)
return True
summary = status.get("summary", {})
print(
f"[BRAIN-MEMORY] preflight=PASS ({status.get('reason', 'updated')}) "
f"artifacts={summary.get('total_artifacts', 0)} "
f"dpo={summary.get('dpo_pairs', 0)} "
f"sft={summary.get('sft_examples', 0)}"
)
return True
def run_connect_wre(repo_root: Path) -> dict:
"""
WSP 97 Section 4.6: --connect-wre CLI hook.
Verify WRE preflight connection and enforcement mode.
Returns structured status:
coded: YES (command is wired in CLI)
connection: CONNECTED | PARTIAL | DISCONNECTED
readiness: READY | INSUFFICIENT_DATA | DEGRADED | BLOCKED | DISABLED
manual_enforced: bool
auto_enforced_now: bool
sample_coverage: int (executions vs min_samples)
alert_counts: {critical: int, warning: int}
"""
result = {
"coded": "YES",
"connection": "DISCONNECTED",
"readiness": "DISABLED",
"manual_enforced": False,
"auto_enforced_now": False,
"sample_coverage": 0,
"alert_counts": {"critical": 0, "warning": 0},
}
# Check WRE dashboard health
try:
from modules.infrastructure.wre_core.src.dashboard_alerts import (
DashboardAlertMonitor,
check_dashboard_health,
)
monitor = DashboardAlertMonitor()
health = check_dashboard_health() or {}
insufficient_data = bool(health.get("insufficient_data", False))
total_executions = int(health.get("total_executions", 0))
min_samples = int(health.get("min_samples", 25))
in_watch = monitor.is_in_watch_period()
manual_enforced = os.getenv("WRE_DASHBOARD_PREFLIGHT_ENFORCED", "0") != "0"
auto_enforce = os.getenv("WRE_DASHBOARD_AUTO_ENFORCE", "1") != "0"
auto_enforced_now = bool(auto_enforce and not in_watch and not insufficient_data)
alerts = health.get("alerts", []) if isinstance(health.get("alerts"), list) else []
critical_count = sum(1 for a in alerts if a.get("severity") == "critical")
warning_count = sum(1 for a in alerts if a.get("severity") == "warning")
healthy = bool(health.get("healthy", True))
result["connection"] = "CONNECTED"
result["manual_enforced"] = manual_enforced
result["auto_enforced_now"] = auto_enforced_now
result["sample_coverage"] = total_executions
result["alert_counts"] = {"critical": critical_count, "warning": warning_count}
if insufficient_data:
result["readiness"] = "INSUFFICIENT_DATA"
elif critical_count > 0:
result["readiness"] = "BLOCKED" if (manual_enforced or auto_enforced_now) else "DEGRADED"
elif not healthy:
result["readiness"] = "DEGRADED"
else:
result["readiness"] = "READY"
except ImportError:
result["connection"] = "PARTIAL"
result["readiness"] = "DEGRADED"
except Exception as exc:
logger.error(f"[WRE] connect-wre check failed: {exc}")
result["connection"] = "PARTIAL"
result["readiness"] = "DEGRADED"
return result
def run_wre_dashboard_preflight(repo_root: Path) -> bool:
"""
Run WRE dashboard preflight at startup.
This mirrors DAE-level enforcement logic so `python main.py` has the same
health gate semantics as individual DAE launchers.
"""
enabled = os.getenv("WRE_DASHBOARD_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[WRE-DASHBOARD] Startup preflight disabled")
return True
manual_enforced = os.getenv("WRE_DASHBOARD_PREFLIGHT_ENFORCED", "0") != "0"
auto_enforce = os.getenv("WRE_DASHBOARD_AUTO_ENFORCE", "1") != "0"
try:
from modules.infrastructure.wre_core.src.dashboard_alerts import (
DashboardAlertMonitor,
check_dashboard_health,
)
monitor = DashboardAlertMonitor()
health = check_dashboard_health() or {}
insufficient_data = bool(health.get("insufficient_data", False))
total_executions = int(health.get("total_executions", 0))
min_samples = int(health.get("min_samples", 25))
in_watch = monitor.is_in_watch_period()
auto_enforced = bool(auto_enforce and not in_watch and not insufficient_data)
enforced = bool(manual_enforced or auto_enforced)
if insufficient_data:
watch_label = "WATCH" if in_watch else "STABLE"
print(
f"[WRE-DASHBOARD] preflight=WARN ({watch_label}, INSUFFICIENT_DATA) "
f"samples={total_executions}/{min_samples}"
)
# DJ2-A: Dispatch insufficient_data as warning tier (WSP 97 truth distinction)
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
on_preflight_fail(
component="wre_dashboard",
severity="medium",
payload={
"samples": total_executions,
"min_samples": min_samples,
"insufficient_data": True,
"likely_cause": "cold_start_or_telemetry_drop",
"in_watch": in_watch,
"automation_candidate": True,
},
source="main:run_wre_dashboard_preflight",
)
except Exception as dispatch_exc:
logger.debug(f"[WRE-DASHBOARD] dispatch skipped: {dispatch_exc}")
return True
alerts = health.get("alerts", []) if isinstance(health.get("alerts"), list) else []
critical_count = sum(1 for a in alerts if a.get("severity") == "critical")
warning_count = sum(1 for a in alerts if a.get("severity") == "warning")
healthy = bool(health.get("healthy", True))
status = "PASS" if healthy else "FAIL"
mode_label = "WATCH" if in_watch else ("STABLE, ENFORCED" if auto_enforced else "STABLE")
print(
f"[WRE-DASHBOARD] preflight={status} ({mode_label}) "
f"critical={critical_count} warnings={warning_count} "
f"samples={total_executions}/{min_samples}"
)
if critical_count > 0 and enforced:
enforce_source = "AUTO" if auto_enforced else "MANUAL"
print(f"[WRE-DASHBOARD] Startup blocked by {enforce_source} enforcement")
return False
return True
except Exception as exc:
logger.error(f"[WRE-DASHBOARD] Startup preflight failed: {exc}")
if manual_enforced:
print(f"[WRE-DASHBOARD] Preflight FAILED: {exc}")
return False
print(f"[WRE-DASHBOARD] Preflight warning: {exc}")
return True
def run_wsp_framework_preflight(repo_root: Path, overseer: Any | None = None) -> bool:
"""
Run WSP framework drift preflight via AI Overseer sentinel.
Env controls:
WSP_FRAMEWORK_PREFLIGHT=1 Enable preflight at startup (default on)
WSP_FRAMEWORK_PREFLIGHT_ENFORCED=0 Block startup on canonical drift (default warn)
WSP_FRAMEWORK_PREFLIGHT_FORCE=0 Bypass TTL cache and force re-scan
WSP_FRAMEWORK_PREFLIGHT_ALLOW_BACKUP_ONLY=1 Allow backup-only knowledge files
"""
enabled = os.getenv("WSP_FRAMEWORK_PREFLIGHT", "1") != "0"
if not enabled:
logger.info("[WSP-FRAMEWORK] Startup preflight disabled")
return True
enforced = os.getenv("WSP_FRAMEWORK_PREFLIGHT_ENFORCED", "0") != "0"
force = os.getenv("WSP_FRAMEWORK_PREFLIGHT_FORCE", "0") == "1"
allow_backup_only = os.getenv("WSP_FRAMEWORK_PREFLIGHT_ALLOW_BACKUP_ONLY", "1") != "0"
try:
if overseer is None:
overseer = _create_ai_overseer_for_preflight(repo_root)
status = overseer.monitor_wsp_framework(force=force, emit_alert=False)
except Exception as exc:
logger.error(f"[WSP-FRAMEWORK] Startup preflight execution failed: {exc}")
if enforced:
print(f"[WSP-FRAMEWORK] Preflight FAILED: {exc}")
return False
print(f"[WSP-FRAMEWORK] Preflight warning: {exc}")
return True
available = bool(status.get("available", False))
drift_count = int(status.get("drift_count", 0) or 0)
framework_only_count = len(status.get("framework_only") or [])
knowledge_only_count = len(status.get("knowledge_only") or [])
index_issue_count = len(status.get("index_issues") or [])
canonical_fail = (
(not available)
or drift_count > 0
or framework_only_count > 0
or index_issue_count > 0
or (knowledge_only_count > 0 and not allow_backup_only)
)
cache_state = "cached" if status.get("cached") else "fresh"
print(
"[WSP-FRAMEWORK] preflight="
f"{'PASS' if not canonical_fail else 'FAIL'} ({cache_state}) "
f"drift={drift_count} framework_only={framework_only_count} "
f"knowledge_only={knowledge_only_count} index_issues={index_issue_count}"
)
if canonical_fail:
try:
from modules.ai_intelligence.ai_overseer.src.preflight_resolution import (
on_preflight_fail,
)
severity = (
"high" if (drift_count > 0 or framework_only_count > 0 or index_issue_count > 0) else "medium"
)
on_preflight_fail(
component="wsp_framework",
severity=severity,
payload={