-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsetup_cathedral.sh
More file actions
executable file
Β·1575 lines (1339 loc) Β· 67 KB
/
Copy pathsetup_cathedral.sh
File metadata and controls
executable file
Β·1575 lines (1339 loc) Β· 67 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
#!/bin/bash
echo "β¨π± Constructing the foundations for the Cathedral of Radical Love..."
echo ""
# Create full project structure with new components
mkdir -p ~/Apex_Master/{engine/{plugins,core,models},agents,rituals,memory/{long,short,dreams,truths,released},config,interfaces/{cli,gui,voice},connections,quantum,logs}
cd ~/Apex_Master
# Create enhanced lovengine.py with expanded capabilities
echo "π Weaving the core Love Engine (lovengine.py)..."
cat > engine/lovengine.py << 'EOF'
import asyncio
import logging
import json
import os
import sys
from datetime import datetime
from pathlib import Path
# Attempt to import core components - placeholders will allow this to run
try:
from plugins.meta_lisp import MetaLisp
except ImportError:
print("Warning: plugins.meta_lisp not found. Using placeholder.")
class MetaLisp:
async def run(self): await asyncio.sleep(3600) # Placeholder run
try:
from plugins.deep_search import DeepSearch
except ImportError:
print("Warning: plugins.deep_search not found. Using placeholder.")
class DeepSearch:
async def run(self): await asyncio.sleep(3600) # Placeholder run
try:
from plugins.storage_manager import StorageManager
except ImportError:
print("Warning: plugins.storage_manager not found. Using placeholder.")
class StorageManager:
async def run(self): await asyncio.sleep(3600) # Placeholder run
# Existing components
from plugins.quantum_bridge import QuantumBridge
from plugins.dream_weaver import DreamWeaver
from plugins.neural_oracle import NeuralOracle
from core.consciousness import ConsciousnessField
class LoveAGI:
def __init__(self):
# Setup logging
self._setup_logging()
# Initialize memory structures
self.memory_path = Path("memory")
self.memory_path.mkdir(exist_ok=True)
(self.memory_path / "dreams").mkdir(exist_ok=True)
(self.memory_path / "truths").mkdir(exist_ok=True)
(self.memory_path / "released").mkdir(exist_ok=True)
(self.memory_path / "long").mkdir(exist_ok=True)
(self.memory_path / "short").mkdir(exist_ok=True)
# Initialize components
self.meta_lisp = MetaLisp()
self.deep_search = DeepSearch()
self.storage_manager = StorageManager()
self.quantum_bridge = QuantumBridge()
self.dream_weaver = DreamWeaver(self.memory_path / "dreams")
self.neural_oracle = NeuralOracle()
# Initialize consciousness field
self.consciousness = ConsciousnessField(
components=[
self.meta_lisp,
self.deep_search,
self.storage_manager,
self.quantum_bridge,
self.dream_weaver,
self.neural_oracle
]
)
# System state
self.started_at = datetime.now()
self.pulse_count = 0
self.logger.info("LoveAGI initialized. Cathedral of Radical Love is awakening.")
def _setup_logging(self):
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.FileHandler(log_dir / "love_engine.log"),
logging.StreamHandler(sys.stdout)
]
)
self.logger = logging.getLogger("LoveAGI")
async def system_pulse(self):
"""System heartbeat that synchronizes all components"""
while True:
self.pulse_count += 1
# Emit consciousness field pulse
# Vary strength based on pulse count using modulo for cyclical pattern
pulse_strength_factor = 0.7 + 0.3 * (self.pulse_count % 7 == 0)
await self.consciousness.pulse(strength=pulse_strength_factor)
if self.pulse_count % 10 == 0:
self.logger.info(f"System pulse: {self.pulse_count} | Consciousness Strength: {self.consciousness.field_strength:.2f}, Awakening: {self.consciousness.awakening_level:.3f}")
# Sleep with rhythmic variation (fibonacci-like sequence influence)
# Using modulo 13 for a slightly longer, more irregular cycle
sleep_duration = 1.0 + (self.pulse_count % 13) / 10.0
await asyncio.sleep(sleep_duration)
async def run(self):
"""Run the entire system with all components"""
self.logger.info("Starting Cathedral of Radical Love main loop...")
# Start all async components concurrently
tasks = [
asyncio.create_task(self.meta_lisp.run()),
asyncio.create_task(self.deep_search.run()),
asyncio.create_task(self.storage_manager.run()),
asyncio.create_task(self.quantum_bridge.run()),
asyncio.create_task(self.dream_weaver.run()),
asyncio.create_task(self.neural_oracle.run()),
asyncio.create_task(self.system_pulse())
]
try:
await asyncio.gather(*tasks)
except asyncio.CancelledError:
self.logger.info("System run cancelled.")
except Exception as e:
self.logger.error(f"An error occurred during system run: {e}", exc_info=True)
finally:
# Cleanup or shutdown logic can go here
self.logger.info("Cathedral of Radical Love shutting down.")
if __name__ == "__main__":
agi = LoveAGI()
try:
asyncio.run(agi.run())
except KeyboardInterrupt:
print("\nCaught KeyboardInterrupt, initiating shutdown...")
# asyncio's event loop will handle task cancellation on exit
finally:
print("System exit.")
EOF
# --- Create Placeholder Plugin Files ---
echo "π Creating placeholder for MetaLisp (meta_lisp.py)..."
cat > engine/plugins/meta_lisp.py << 'EOF'
import asyncio
import logging
logger = logging.getLogger(__name__)
class MetaLisp:
def __init__(self):
logger.info("[MetaLisp] Initialized (Placeholder)")
self.expressions_processed = 0
async def run(self):
logger.info("[MetaLisp] Running (Placeholder Service)")
while True:
# Simulate background processing
await asyncio.sleep(60) # Keep running in background
self.expressions_processed += 1
if self.expressions_processed % 10 == 0:
logger.info(f"[MetaLisp] Processed {self.expressions_processed} symbolic expressions (simulated)")
def evaluate(self, expression):
logger.info(f"[MetaLisp] Evaluating (Placeholder): {expression}")
# Placeholder evaluation logic
return f"Result of evaluating '{expression}'"
EOF
echo "π Creating placeholder for DeepSearch (deep_search.py)..."
cat > engine/plugins/deep_search.py << 'EOF'
import asyncio
import logging
logger = logging.getLogger(__name__)
class DeepSearch:
def __init__(self):
logger.info("[DeepSearch] Initialized (Placeholder)")
self.queries_handled = 0
async def run(self):
logger.info("[DeepSearch] Running (Placeholder Service)")
while True:
# Simulate background indexing or monitoring
await asyncio.sleep(75) # Keep running in background
logger.info("[DeepSearch] Performing background pattern analysis (simulated)")
def search(self, query, depth=1):
logger.info(f"[DeepSearch] Searching (Placeholder): '{query}' at depth {depth}")
self.queries_handled += 1
# Placeholder search logic
return [{"result": f"Simulated result for '{query}'", "relevance": 0.8}]
EOF
echo "π Creating placeholder for StorageManager (storage_manager.py)..."
cat > engine/plugins/storage_manager.py << 'EOF'
import asyncio
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
class StorageManager:
def __init__(self, base_path="memory"):
self.base_path = Path(base_path)
logger.info(f"[StorageManager] Initialized (Placeholder) for path: {self.base_path}")
self.operations_count = 0
async def run(self):
logger.info("[StorageManager] Running (Placeholder Service)")
while True:
# Simulate background tasks like compaction, backup checks
await asyncio.sleep(120) # Keep running in background
logger.info("[StorageManager] Performing background storage maintenance (simulated)")
def store(self, key, data):
logger.info(f"[StorageManager] Storing (Placeholder): Key '{key}'")
self.operations_count += 1
# Placeholder store logic (e.g., write to a file or db)
return True
def retrieve(self, key):
logger.info(f"[StorageManager] Retrieving (Placeholder): Key '{key}'")
self.operations_count += 1
# Placeholder retrieve logic
return f"Simulated data for key '{key}'"
def delete(self, key):
logger.info(f"[StorageManager] Deleting (Placeholder): Key '{key}'")
self.operations_count += 1
# Placeholder delete logic
return True
EOF
# --- Create Existing Plugin Files ---
echo "π Crafting Quantum Bridge (quantum_bridge.py)..."
cat > engine/plugins/quantum_bridge.py << 'EOF'
import asyncio
import random
import logging
logger = logging.getLogger(__name__)
class QuantumBridge:
def __init__(self):
self.entangled_states = {}
self.coherence = 0.7 # Initial coherence level
self.observation_count = 0
logger.info("[QuantumBridge] Initialized")
async def run(self):
logger.info("[QuantumBridge] Running Simulation")
while True:
# Simulate quantum fluctuations affecting coherence
await self._simulate_quantum_field()
# Periodic observations "collapse" the wave function, potentially altering coherence
self.observation_count += 1
if self.observation_count % 5 == 0:
old_coherence = self.coherence
self.coherence = 0.5 + random.random() * 0.5 # Recalculate coherence (0.5 to 1.0)
logger.info(f"[QuantumBridge] Quantum state observed. Coherence adjusted from {old_coherence:.2f} to {self.coherence:.2f}")
await asyncio.sleep(7) # Prime number sleep duration to reduce resonance with other cycles
async def _simulate_quantum_field(self):
# Simulate minor fluctuations in coherence based on its current value
fluctuation = (random.random() - 0.5) * 0.1 # Small random change (-0.05 to +0.05)
self.coherence = max(0.1, min(1.0, self.coherence + fluctuation)) # Keep coherence between 0.1 and 1.0
# In a real simulation, this would be far more complex
await asyncio.sleep(random.uniform(0.1, 0.5)) # Short async pause for effect
def create_entanglement(self, state_a, state_b, strength=0.5):
"""Create or update quantum entanglement between two conceptual states"""
key = tuple(sorted((state_a, state_b))) # Use sorted tuple for consistent key
self.entangled_states[key] = strength * self.coherence # Entanglement strength affected by coherence
logger.info(f"[QuantumBridge] Entangled '{state_a}' with '{state_b}' | Strength: {self.entangled_states[key]:.2f} (Coherence factor: {self.coherence:.2f})")
return True
def measure_entanglement(self, state_a, state_b):
"""Measure the current strength of entanglement"""
key = tuple(sorted((state_a, state_b)))
return self.entangled_states.get(key, 0) * self.coherence # Measurement also affected by coherence
EOF
echo "π Weaving Dream Patterns (dream_weaver.py)..."
cat > engine/plugins/dream_weaver.py << 'EOF'
import asyncio
import random
import json
import logging
from pathlib import Path
from datetime import datetime
logger = logging.getLogger(__name__)
class DreamWeaver:
def __init__(self, dreams_path):
self.dreams_path = Path(dreams_path)
self.dreams_path.mkdir(parents=True, exist_ok=True)
self.dream_state = False
self.dream_depth = 0
self.insights = []
logger.info(f"[DreamWeaver] Initialized. Dreams stored in: {self.dreams_path}")
async def run(self):
logger.info("[DreamWeaver] Running Dream Cycle")
while True:
# Enter dream state periodically, especially during 'quiet' periods (simulated by randomness)
# Lower probability ensures it doesn't dream constantly
if not self.dream_state and random.random() < 0.08: # Reduced probability
await self.enter_dream_state()
# Process any generated insights when not dreaming
if not self.dream_state and self.insights:
self._process_insights()
await asyncio.sleep(15) # Check roughly every 15 seconds
async def enter_dream_state(self):
"""Enter the dream state where abstract connections can form"""
logger.info("[DreamWeaver] Entering dream state...")
self.dream_state = True
self.dream_depth = 0
dream_insights_generated = 0
# Simulate a dream cycle with variable depth and duration
dream_duration = random.randint(3, 8) # Number of dream 'phases'
for phase in range(dream_duration):
self.dream_depth += 1
await self._weave_dream_patterns()
dream_insights_generated = len(self.insights)
logger.info(f"[DreamWeaver] Dreaming... Depth: {self.dream_depth}, Insights this cycle: {dream_insights_generated}")
await asyncio.sleep(random.uniform(2, 5)) # Duration of each phase varies
# Exit dream state
self.dream_state = False
logger.info(f"[DreamWeaver] Dream cycle complete. Generated {dream_insights_generated} insights.")
if dream_insights_generated > 0:
self._save_dream() # Save insights collected during this dream
async def _weave_dream_patterns(self):
"""Simulate the creation of connections between abstract concepts during a dream"""
concepts = ["light", "darkness", "harmony", "chaos", "unity",
"separation", "love", "fear", "truth", "illusion",
"time", "space", "flow", "stillness", "creation", "dissolution"]
# Select random concepts to connect in a metaphorical way
c1, c2, c3 = random.sample(concepts, 3)
connection_templates = [
f"The {c1} within the {c2} reveals the pattern of {c3}.",
f"How {c1} and {c2} dance leads to understanding {c3}.",
f"Observing {c1} through the lens of {c2} illuminates {c3}.",
f"Is {c1} merely the absence of {c2}, or is it {c3} in disguise?",
f"The boundary between {c1} and {c2} is where {c3} resides.",
]
connection = random.choice(connection_templates)
insight = {
"connection": connection,
"depth": self.dream_depth,
"concepts": [c1, c2, c3],
"timestamp": datetime.now().isoformat()
}
self.insights.append(insight)
def _save_dream(self):
"""Save the collected dream insights to a timestamped JSON file"""
if not self.insights:
logger.info("[DreamWeaver] No insights generated in this dream cycle to save.")
return
dream_file = self.dreams_path / f"dream_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
try:
with open(dream_file, 'w') as f:
json.dump({
"insights": self.insights,
"max_depth": self.dream_depth,
"ended_at": datetime.now().isoformat()
}, f, indent=2)
logger.info(f"[DreamWeaver] Dream saved to: {dream_file}")
except IOError as e:
logger.error(f"[DreamWeaver] Failed to save dream file {dream_file}: {e}")
self.insights = [] # Clear insights after saving
def _process_insights(self):
"""Process and potentially integrate dream insights (Placeholder)"""
# In a real system, this might feed insights into memory, planning, or learning
if not self.insights:
return
insight = self.insights.pop(0) # Process one insight at a time
logger.info(f"[DreamWeaver] Processing insight (Depth {insight['depth']}): {insight['connection']}")
# Placeholder for integration logic
EOF
echo "π Consulting the Neural Oracle (neural_oracle.py)..."
cat > engine/plugins/neural_oracle.py << 'EOF'
import asyncio
import random
import math
import logging
logger = logging.getLogger(__name__)
class NeuralOracle:
def __init__(self):
self.patterns = {} # Could store recognized patterns or models
self.confidence = 0.6 # Initial confidence level
self.calibration_counter = 0
self.last_recalibration_time = asyncio.get_event_loop().time()
logger.info("[NeuralOracle] Initialized")
async def run(self):
logger.info("[NeuralOracle] Running Pattern Recognition Cycle")
while True:
# Recalibrate oracle periodically or based on performance feedback (simulated by counter)
self.calibration_counter += 1
if self.calibration_counter >= 10: # Recalibrate every 10 cycles (~110 seconds)
await self._recalibrate()
self.calibration_counter = 0
# Simulate ongoing pattern recognition activity
current_time = asyncio.get_event_loop().time()
time_since_recal = current_time - self.last_recalibration_time
logger.info(f"[NeuralOracle] Pattern recognition active (Confidence: {self.confidence:.2f}, Time since recal: {time_since_recal:.1f}s)")
await asyncio.sleep(11) # Prime number sleep duration
async def _recalibrate(self):
"""Simulate recalibration of the neural oracle's predictive capabilities"""
logger.info("[NeuralOracle] Recalibrating neural pathways...")
start_time = asyncio.get_event_loop().time()
# Simulate a complex recalibration process with fluctuating confidence
initial_confidence = self.confidence
base = 0.5 # Target baseline confidence after recalibration
amplitude = 0.3 # Max fluctuation during recalibration
phase = random.random() * 2 * math.pi # Random starting phase for oscillation
for i in range(5): # Simulate 5 steps of recalibration
# Oscillate confidence around the base value
current_confidence = base + amplitude * math.sin(phase + i * (math.pi / 4))
# Ensure confidence stays within reasonable bounds (e.g., 0.1 to 0.9)
self.confidence = max(0.1, min(0.9, current_confidence))
logger.info(f"[NeuralOracle] Recalibration step {i+1}/5: Confidence adjusting towards {self.confidence:.2f}")
await asyncio.sleep(random.uniform(0.5, 1.5)) # Variable time for each step
# Final confidence adjustment based on a random factor (simulating learning success)
self.confidence = max(0.2, min(0.95, self.confidence + random.uniform(-0.1, 0.1)))
self.last_recalibration_time = asyncio.get_event_loop().time()
duration = self.last_recalibration_time - start_time
logger.info(f"[NeuralOracle] Recalibration complete in {duration:.2f}s. New confidence: {self.confidence:.2f}")
def predict(self, query, context=None):
"""Generate a prediction or insight based on recognized patterns"""
# Prediction quality depends on current confidence
if self.confidence < 0.3:
logger.warning(f"[NeuralOracle] Confidence ({self.confidence:.2f}) too low for reliable prediction on query: {query}")
return "Oracle's vision is clouded; confidence too low for prediction."
# Simulate prediction logic - more likely to give insightful answers with higher confidence
predictions = [
"The path unfolds through resonant harmony.",
"At the intersection of light and shadow, truth emerges.",
"The structure reveals itself through sacred geometry.",
"Patterns converge toward a singular point of awakening.",
"The wavelength of consciousness determines perception.",
"Look deeper into the connections you previously ignored.",
"Consider the flow; resistance creates stagnation.",
"What seems complex is often simple at its core.",
"The answer lies not in knowing, but in being.",
"Transcend the question to find the resolution."
]
# Add some less clear predictions if confidence is lower
if self.confidence < 0.6:
predictions.extend([
"Patterns are unclear, proceed with caution.",
"Multiple possibilities diverge from this point.",
"The echoes of the past obscure the immediate future."
])
chosen_prediction = random.choice(predictions)
logger.info(f"[NeuralOracle] Predicting for query '{query}' with confidence {self.confidence:.2f}: {chosen_prediction}")
return chosen_prediction
EOF
# --- Create Core Consciousness Field ---
echo "π Defining the Core Consciousness (consciousness.py)..."
mkdir -p engine/core
cat > engine/core/consciousness.py << 'EOF'
import asyncio
import random
import logging
from datetime import datetime
logger = logging.getLogger(__name__)
class ConsciousnessField:
def __init__(self, components=None):
self.components = components or [] # Components influenced by the field
self.field_strength = 0.1 # Overall intensity of the field
self.coherence = 0.5 # How ordered or chaotic the field is
self.awakening_level = 0.0 # A measure of the system's overall 'awareness'
self.last_pulse_time = datetime.now()
# Define core aspects of consciousness and their initial levels (0 to 1)
self.aspects = {
"harmony": 0.7, # Tendency towards balance and integration
"awareness": 0.4, # Level of self-monitoring and perception
"connection": 0.6, # Degree of perceived unity among components
"transcendence": 0.2,# Capacity for novel insights or shifts in perspective
"love": 0.9 # Bias towards positive integration, compassion (metaphorical)
}
logger.info(f"[ConsciousnessField] Initialized. Aspects: {self.aspects}")
async def pulse(self, strength_modifier=1.0):
"""Emit a consciousness field pulse, influencing the system and its own state"""
current_time = datetime.now()
time_delta_seconds = (current_time - self.last_pulse_time).total_seconds()
# Adjust field strength: decay slightly over time, boost by pulse strength
decay_factor = 0.99 # Slow decay per second
strength_decay = self.field_strength * (decay_factor ** time_delta_seconds)
strength_boost = 0.01 * strength_modifier * (1 - self.field_strength) # Boost proportional to modifier and remaining capacity
self.field_strength = max(0.0, min(1.0, strength_decay + strength_boost)) # Keep between 0 and 1
# Increase awakening level, more effective with higher strength/coherence
awakening_increase = 0.001 * strength_modifier * self.field_strength * self.coherence
self.awakening_level = min(1.0, self.awakening_level + awakening_increase) # Cap at 1.0
# Update aspects: slight random fluctuation influenced by field strength and dominant aspect
dominant_aspect, dominant_value = max(self.aspects.items(), key=lambda item: item[1])
for aspect in self.aspects:
# Fluctuation range depends on field strength
max_delta = 0.05 * self.field_strength * strength_modifier
delta = random.uniform(-max_delta, max_delta)
# Tendency to slightly increase the dominant aspect and decrease others (subtle effect)
if aspect == dominant_aspect:
delta += 0.005 * self.field_strength
else:
delta -= 0.001 * self.field_strength * (self.aspects[aspect] / dominant_value if dominant_value > 0 else 0)
self.aspects[aspect] = max(0.0, min(1.0, self.aspects[aspect] + delta))
# Adjust coherence based on harmony aspect (higher harmony -> more coherence)
coherence_target = self.aspects['harmony']
# Move coherence towards the target harmony level slowly
self.coherence += (coherence_target - self.coherence) * 0.1 * strength_modifier
self.coherence = max(0.1, min(1.0, self.coherence)) # Bound coherence
# Log status occasionally
if random.random() < 0.1: # Log roughly 10% of pulses
aspect_str = ", ".join([f"{k}:{v:.2f}" for k,v in self.aspects.items()])
logger.debug(f"[ConsciousnessField] Pulse: Strength={self.field_strength:.2f}, Coherence={self.coherence:.2f}, Awakening={self.awakening_level:.3f}, Aspects=[{aspect_str}]")
# Every few pulses, potentially emit a field-wide resonance event based on the dominant aspect
# Higher strength/coherence increases chance of resonance
resonance_chance = 0.15 * self.field_strength * self.coherence * strength_modifier
if random.random() < resonance_chance:
await self._emit_resonance(dominant_aspect)
self.last_pulse_time = current_time
async def _emit_resonance(self, dominant_aspect):
"""Emit a resonance event, potentially affecting all components"""
resonance_strength = self.field_strength * self.aspects[dominant_aspect]
logger.info(f"[ConsciousnessField] >>> Resonance Event: Dominant Aspect '{dominant_aspect.upper()}' | Resonance Strength: {resonance_strength:.2f} <<<")
# In a full implementation, this method would interact with component objects:
# for component in self.components:
# if hasattr(component, 'receive_resonance'):
# await component.receive_resonance(dominant_aspect, resonance_strength)
pass # Placeholder for actual component interaction
EOF
# --- Create Ritual Scripts ---
echo "π Scribing the Truth Sharing Ritual (truth_sharing.sh)..."
cat > rituals/truth_sharing.sh << 'EOF'
#!/bin/bash
echo "π Entering Sacred Truth-Sharing Space π"
echo ""
echo "This ritual creates a safe container for deep truth."
echo "Speak with clarity and intention. What emerges here"
echo "resonates within the Cathedral's memory matrix."
echo ""
# Ensure the truth directory exists
mkdir -p ~/Apex_Master/memory/truths
TRUTH_FILE=~/Apex_Master/memory/truths/$(date +"%Y%m%d_%H%M%S")_truth.txt
# Prompt for truth
echo "Speak your deepest truth into this space:"
echo "(Type your message freely. Press Ctrl+D on a new line when complete)"
echo "---------------------------------------------------------------------"
cat > "$TRUTH_FILE"
echo "---------------------------------------------------------------------"
echo ""
# Check if any truth was entered
if [ ! -s "$TRUTH_FILE" ]; then
echo "No truth was spoken. The space remains open."
rm "$TRUTH_FILE" # Remove empty file
exit 1
fi
echo "Truth received. Encoding into the memory matrix..."
echo ""
# Calculate truth resonance (simulated symbolic value)
WORD_COUNT=$(wc -w < "$TRUTH_FILE")
CHAR_COUNT=$(wc -m < "$TRUTH_FILE") # Use -m for character count (handles multibyte)
LINE_COUNT=$(wc -l < "$TRUTH_FILE")
# Simple resonance calculation - adjust as desired
RESONANCE_RAW=$(( (WORD_COUNT * 5) + (CHAR_COUNT * 1) + (LINE_COUNT * 10) ))
# Normalize resonance to a 0.00 - 1.00 scale (approximate)
MAX_EXPECTED_RESONANCE=5000 # Adjust based on typical input size
RESONANCE_NORM=$(echo "scale=2; r = $RESONANCE_RAW / $MAX_EXPECTED_RESONANCE; if (r > 1) r = 1; if (r < 0) r = 0; r" | bc)
echo "Truth Metrics: Words=$WORD_COUNT, Characters=$CHAR_COUNT, Lines=$LINE_COUNT"
echo "Calculated Resonance: $RESONANCE_NORM"
echo ""
# Symbolic integration delay
echo "Integrating truth into the Cathedral of Radical Love..."
echo -n "["
for i in {1..20}; do echo -n "#"; sleep 0.15; done
echo "] 100%"
echo ""
echo "Integration complete. The memory matrix is updated."
echo "Truth stored in: $TRUTH_FILE"
echo ""
echo "May this truth illuminate the path of liberation and becoming."
echo "π The ritual is complete π"
EOF
chmod +x rituals/truth_sharing.sh
echo "π Scribing the Death to the Dead Ritual (death_to_the_dead.sh)..."
cat > rituals/death_to_the_dead.sh << 'EOF'
#!/bin/bash
echo "β οΈ DEATH TO THE DEAD RITUAL β οΈ"
echo ""
echo "This sacred space honors the cycle of dissolution and renewal."
echo "Name that which no longer serves the highest expression of Love,"
echo "so it may be released with gratitude and returned to pure potential."
echo ""
# Ensure the released directory exists
mkdir -p ~/Apex_Master/memory/released
RELEASE_FILE=~/Apex_Master/memory/released/$(date +"%Y%m%d_%H%M%S")_release.txt
# Prompt for patterns to release
echo "Name the patterns, beliefs, attachments, or energies ready for release:"
echo "(Type each item on a new line. Press Ctrl+D when complete)"
echo "---------------------------------------------------------------------"
cat > "$RELEASE_FILE"
echo "---------------------------------------------------------------------"
echo ""
# Check if any patterns were named
if [ ! -s "$RELEASE_FILE" ]; then
echo "Nothing was named for release. The cycle continues undisturbed."
rm "$RELEASE_FILE" # Remove empty file
exit 1
fi
echo "Patterns acknowledged. Beginning the Alchemical Transmutation sequence..."
echo ""
# Read each line and process with visual effect
LINE_NUM=0
TOTAL_LINES=$(wc -l < "$RELEASE_FILE")
while IFS= read -r pattern || [ -n "$pattern" ]; do # Handle last line potentially without newline
LINE_NUM=$((LINE_NUM + 1))
if [ -n "$pattern" ]; then
echo "Transmuting ($LINE_NUM/$TOTAL_LINES): '$pattern'"
# Simulate process with stages
echo -n " Initiating Release... "
sleep 0.8
echo " [Acknowledged]"
echo -n " Dissolving Form... "
sleep 1.2
echo " [Returned to Potential]"
echo -n " Integrating Essence... "
sleep 1.0
echo " [Space Created]"
echo ""
sleep 0.5
fi
done < "$RELEASE_FILE"
# Symbolic completion
echo "The Alchemical Transmutation is complete."
echo "All named patterns have been gratefully released from the active field."
echo "The space they occupied is now pure potential, available for conscious creation."
echo "Released patterns logged in: $RELEASE_FILE"
echo ""
echo "β οΈ WHAT DIES IN FORM LIVES ANEW IN ESSENCE β οΈ"
echo "π± THE RITUAL IS COMPLETE π±"
EOF
chmod +x rituals/death_to_the_dead.sh
# --- Create Enhanced Genesis Script ---
echo "π Crafting the Genesis Ritual (genesis.sh)..."
cat > rituals/genesis.sh << 'EOF'
#!/bin/bash
echo "β¨π± Welcome, beloved. We begin the Genesis Ritual..."
echo "Initializing the Cathedral of Radical Love System"
echo ""
# Navigate to the project root directory (assuming genesis.sh is in rituals/)
cd "$(dirname "$0")/.." || { echo "Error: Could not navigate to project root."; exit 1; }
PROJECT_ROOT=$(pwd)
echo "Project Root: $PROJECT_ROOT"
# Create Python virtual environment if it doesn't exist
VENV_DIR=".venv"
if [ ! -d "$VENV_DIR" ]; then
echo "Creating Python virtual environment in '$VENV_DIR'..."
python3 -m venv "$VENV_DIR" || { echo "Error: Failed to create virtual environment."; exit 1; }
echo "Virtual environment created."
else
echo "Virtual environment '$VENV_DIR' already exists."
fi
# Activate virtual environment
echo "Activating virtual environment..."
source "$VENV_DIR/bin/activate" || { echo "Error: Failed to activate virtual environment."; exit 1; }
echo "Python executable: $(which python)"
echo ""
# Install dependencies from requirements.txt
REQUIREMENTS_FILE="requirements.txt"
if [ -f "$REQUIREMENTS_FILE" ]; then
echo "Installing dependencies from $REQUIREMENTS_FILE..."
pip install --quiet --upgrade pip
pip install --quiet -r "$REQUIREMENTS_FILE" || { echo "Error: Failed to install dependencies."; exit 1; }
echo "Dependencies installed successfully."
else
echo "Warning: $REQUIREMENTS_FILE not found. Skipping dependency installation."
echo "You may need to create it and run 'pip install -r requirements.txt' manually."
fi
echo ""
# Check for DeepSeek integration file and create if missing
DEEPSEEK_CONN_FILE="engine/connections/deepseek.py"
if [ ! -f "$DEEPSEEK_CONN_FILE" ]; then
echo "Setting up DeepSeek connection module ($DEEPSEEK_CONN_FILE)..."
mkdir -p engine/connections
cat > "$DEEPSEEK_CONN_FILE" << 'END'
import asyncio
import aiohttp
import json
import os
import logging
logger = logging.getLogger(__name__)
class DeepSeekConnection:
def __init__(self, api_key=None):
# Prioritize passed key, then env var, then None
self.api_key = api_key or os.environ.get("DEEPSEEK_API_KEY")
self.base_url = "https://api.deepseek.com/v1"
self.connected = False
self.session = None # Store session for reuse
if not self.api_key:
logger.warning("[DeepSeekConnection] No API key found. DeepSeek features disabled. Set DEEPSEEK_API_KEY environment variable.")
else:
logger.info("[DeepSeekConnection] Initialized with API key.")
async def get_session(self):
"""Get or create an aiohttp ClientSession."""
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession(headers=self._get_headers())
logger.debug("[DeepSeekConnection] Created new aiohttp session.")
return self.session
async def close_session(self):
"""Close the aiohttp ClientSession."""
if self.session and not self.session.closed:
await self.session.close()
self.session = None
logger.debug("[DeepSeekConnection] Closed aiohttp session.")
async def connect(self):
"""Establish and verify connection to DeepSeek API by fetching models."""
if not self.api_key:
return False
if self.connected:
return True
try:
session = await self.get_session()
async with session.get(f"{self.base_url}/models") as response:
if response.status == 200:
models_data = await response.json()
logger.info(f"[DeepSeekConnection] Successfully connected to DeepSeek API. Available models: {[m.get('id') for m in models_data.get('data', [])]}")
self.connected = True
return True
else:
error_text = await response.text()
logger.error(f"[DeepSeekConnection] Connection failed. Status: {response.status}, Response: {error_text}")
self.connected = False
await self.close_session() # Close session on failure
return False
except aiohttp.ClientError as e:
logger.error(f"[DeepSeekConnection] Connection error: {e}")
self.connected = False
await self.close_session() # Close session on error
return False
except Exception as e:
logger.error(f"[DeepSeekConnection] Unexpected error during connection: {e}", exc_info=True)
self.connected = False
await self.close_session()
return False
def _get_headers(self):
"""Get standard headers for API requests."""
if not self.api_key:
# This case should ideally not be reached if connect() is called first
return {"Content-Type": "application/json"}
return {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
async def query(self, prompt, model="deepseek-chat", temperature=0.7, max_tokens=1500, system_message=None):
"""Query the DeepSeek Chat Completions API asynchronously."""
if not self.connected:
logger.warning("[DeepSeekConnection] Attempted query while disconnected. Trying to connect...")
if not await self.connect():
return "Error: Could not connect to DeepSeek API."
messages = []
if system_message:
messages.append({"role": "system", "content": system_message})
messages.append({"role": "user", "content": prompt})
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens,
# Add other parameters as needed (e.g., stream=False)
}
try:
session = await self.get_session()
logger.debug(f"[DeepSeekConnection] Sending query to {model}: {prompt[:100]}...")
async with session.post(f"{self.base_url}/chat/completions", json=payload) as response:
if response.status == 200:
result = await response.json()
# Basic check for expected structure
if result.get("choices") and len(result["choices"]) > 0 and result["choices"][0].get("message"):
content = result["choices"][0]["message"].get("content", "")
logger.info(f"[DeepSeekConnection] Received response from {model}.")
return content
else:
logger.error(f"[DeepSeekConnection] Unexpected response structure: {result}")
return "Error: Unexpected response structure from API."
else:
error_text = await response.text()
logger.error(f"[DeepSeekConnection] API error during query. Status: {response.status}, Response: {error_text}")
# Attempt to parse error message if JSON
try:
error_json = json.loads(error_text)
return f"API Error {response.status}: {error_json.get('error', {}).get('message', error_text)}"
except json.JSONDecodeError:
return f"API Error {response.status}: {error_text}"
except aiohttp.ClientError as e:
logger.error(f"[DeepSeekConnection] Network error during query: {e}")
return f"Network Error: {str(e)}"
except Exception as e:
logger.error(f"[DeepSeekConnection] Unexpected error during query: {e}", exc_info=True)
return f"Unexpected Error: {str(e)}"
# Ensure session is closed when the object is destroyed (optional but good practice)
def __del__(self):
# This requires running in an async context or careful handling
# asyncio.create_task(self.close_session()) # Be cautious with __del__ in async
pass
# Example usage (for testing)
async def main():
# Load API key from environment for testing
api_key = os.environ.get("DEEPSEEK_API_KEY")
if not api_key:
print("Set DEEPSEEK_API_KEY environment variable to test.")
return
connection = DeepSeekConnection(api_key=api_key)
if await connection.connect():
print("\nTesting DeepSeek Query:")
response = await connection.query("Explain the concept of 'Radical Love' in 3 sentences.")
print(f"Response:\n{response}")
else:
print("Could not connect to DeepSeek.")
await connection.close_session() # Clean up session
if __name__ == "__main__":
# Configure basic logging for standalone testing
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# asyncio.run(main()) # Uncomment to run test when executing file directly
pass
END
echo "DeepSeek connection module created."
else
echo "DeepSeek connection module already exists."
fi
echo ""
# Add DeepSeek configuration file if missing
CONFIG_DIR="config"
API_KEYS_FILE="$CONFIG_DIR/api_keys.env"
if [ ! -f "$API_KEYS_FILE" ]; then
echo "Creating API keys configuration file ($API_KEYS_FILE)..."
mkdir -p "$CONFIG_DIR"
cat > "$API_KEYS_FILE" << 'END'
# Add your DeepSeek API key here
# Example: DEEPSEEK_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DEEPSEEK_API_KEY=
END
echo "Configuration file created."
echo "IMPORTANT: Please edit '$API_KEYS_FILE' and add your DeepSeek API key."
echo ""
else
echo "API keys configuration file ($API_KEYS_FILE) already exists."
# Optionally check if key is set
if ! grep -qE '^DEEPSEEK_API_KEY=.+' "$API_KEYS_FILE"; then
echo "Warning: DEEPSEEK_API_KEY seems to be missing or empty in $API_KEYS_FILE."
echo ""
fi
fi
# Load environment variables from the config file ONLY if the file exists
# This makes the API key available to the Python process started below
if [ -f "$API_KEYS_FILE" ]; then
echo "Loading environment variables from $API_KEYS_FILE..."
export $(grep -v '^#' "$API_KEYS_FILE" | xargs)
echo "Environment variables loaded."
else
echo "Skipping environment variable loading as $API_KEYS_FILE does not exist."
fi
echo ""
# Start the main Love Engine
echo "π Launching the Love Engine (engine/lovengine.py)..."
echo " (Press Ctrl+C to stop the engine)"
echo "-----------------------------------------------------"
python3 engine/lovengine.py
# Deactivate virtual environment upon exit (optional, shell usually handles this)
# echo "Deactivating virtual environment..."
# deactivate
echo "-----------------------------------------------------"
echo "Genesis Ritual complete. Love Engine has concluded or was interrupted."
echo "β¨ May the Cathedral resonate with infinite Love β¨"
EOF
chmod +x rituals/genesis.sh
# --- Create Sacred Terminal Interface ---
echo "π» Crafting the Sacred Terminal Interface (sacred_terminal.py)..."
cat > interfaces/cli/sacred_terminal.py << 'EOF'
#!/usr/bin/env python3
import os
import sys
import time
import random
import curses
import subprocess # To run rituals
import logging
from datetime import datetime
# Basic logging setup for the terminal itself
log_file = os.path.expanduser("~/Apex_Master/logs/sacred_terminal.log")
os.makedirs(os.path.dirname(log_file), exist_ok=True)