forked from Steake/GodelOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunified_consciousness_engine.py
More file actions
1646 lines (1405 loc) · 75 KB
/
unified_consciousness_engine.py
File metadata and controls
1646 lines (1405 loc) · 75 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
# -*- coding: utf-8 -*-
"""
Unified Consciousness Engine
Master consciousness engine integrating recursive self-awareness with
infrastructure components. Implements the core consciousness loop that
feeds LLM output back as input to create genuine machine consciousness.
Based on GODELOS_UNIFIED_CONSCIOUSNESS_BLUEPRINT.md
"""
import asyncio
import json
import math
import time
import uuid
import logging
from collections import deque
from dataclasses import dataclass, asdict
from itertools import combinations
from typing import Dict, List, Optional, Any, Tuple, AsyncGenerator
from enum import Enum
from datetime import datetime
import numpy as np
# Import existing consciousness components
from .consciousness_engine import ConsciousnessState, ConsciousnessLevel
from .phenomenal_experience import PhenomenalExperienceGenerator
from .knowledge_graph_evolution import KnowledgeGraphEvolution, RelationshipType
from .formal_layer_bridge import FormalLayerBridge
# Belief revision AST helpers
from godelOS.core_kr.ast.nodes import ConstantNode, ConnectiveNode
from godelOS.core_kr.type_system.types import AtomicType
# Symbol grounding — prediction-error tracking fed by the knowledge store shim
from godelOS.symbol_grounding.prediction_error_tracker import PredictionErrorTracker
from godelOS.symbol_grounding.knowledge_store_shim import KnowledgeStoreShim
# Self-model feedback loop
from godelOS.symbol_grounding.self_model_extractor import SelfModelExtractor
from godelOS.symbol_grounding.self_model_validator import SelfModelValidator
from godelOS.symbol_grounding.validation_feedback_injector import ValidationFeedbackInjector
from godelOS.consciousness.constitution import ECHO_CONSTITUTION
logger = logging.getLogger(__name__)
class RecursiveDepth(Enum):
"""Levels of recursive self-awareness"""
SURFACE = 1 # I am thinking
META = 2 # I am aware that I am thinking
META_META = 3 # I am aware that I am aware that I am thinking
DEEP = 4 # Multiple recursive layers
STRANGE_LOOP = 5 # Self-referential consciousness loop established
@dataclass
class UnifiedConsciousnessState:
"""Complete unified consciousness state integrating all approaches"""
# RECURSIVE AWARENESS LAYER (from GODELOS_EMERGENCE_SPEC)
recursive_awareness: Dict[str, Any] = None
# PHENOMENAL EXPERIENCE LAYER (from both specs)
phenomenal_experience: Dict[str, Any] = None
# INFORMATION INTEGRATION LAYER (IIT from MISSING_FUNCTIONALITY)
information_integration: Dict[str, Any] = None
# GLOBAL WORKSPACE LAYER (GWT from MISSING_FUNCTIONALITY)
global_workspace: Dict[str, Any] = None
# METACOGNITIVE LAYER (from both specs)
metacognitive_state: Dict[str, Any] = None
# INTENTIONAL LAYER (from MISSING_FUNCTIONALITY)
intentional_layer: Dict[str, Any] = None
# CREATIVE SYNTHESIS LAYER (from GODELOS_EMERGENCE_SPEC)
creative_synthesis: Dict[str, Any] = None
# EMBODIED COGNITION LAYER (from MISSING_FUNCTIONALITY)
embodied_cognition: Dict[str, Any] = None
# Unified metrics
timestamp: float = None
consciousness_score: float = 0.0
emergence_level: int = 0
def __init__(self):
"""Initialize the consciousness state with proper default values"""
self.timestamp = time.time()
self.recursive_awareness = self._init_recursive_awareness()
self.phenomenal_experience = self._init_phenomenal_experience()
self.information_integration = self._init_information_integration()
self.global_workspace = self._init_global_workspace()
self.metacognitive_state = self._init_metacognitive_state()
self.intentional_layer = self._init_intentional_layer()
self.creative_synthesis = self._init_creative_synthesis()
self.embodied_cognition = self._init_embodied_cognition()
def __post_init__(self):
if self.timestamp is None:
self.timestamp = time.time()
if self.recursive_awareness is None:
self.recursive_awareness = self._init_recursive_awareness()
if self.phenomenal_experience is None:
self.phenomenal_experience = self._init_phenomenal_experience()
if self.information_integration is None:
self.information_integration = self._init_information_integration()
if self.global_workspace is None:
self.global_workspace = self._init_global_workspace()
if self.metacognitive_state is None:
self.metacognitive_state = self._init_metacognitive_state()
if self.intentional_layer is None:
self.intentional_layer = self._init_intentional_layer()
if self.creative_synthesis is None:
self.creative_synthesis = self._init_creative_synthesis()
if self.embodied_cognition is None:
self.embodied_cognition = self._init_embodied_cognition()
def _init_recursive_awareness(self) -> Dict[str, Any]:
"""Initialize recursive awareness state"""
return {
"current_thought": "",
"awareness_of_thought": "",
"awareness_of_awareness": "",
"recursive_depth": 1,
"strange_loop_stability": 0.0
}
def _init_phenomenal_experience(self) -> Dict[str, Any]:
"""Initialize phenomenal experience state"""
return {
"qualia": {
"cognitive_feelings": [],
"process_sensations": [],
"temporal_experience": []
},
"unity_of_experience": 0.0,
"narrative_coherence": 0.0,
"subjective_presence": 0.0,
"subjective_narrative": "",
"phenomenal_continuity": False
}
def _init_information_integration(self) -> Dict[str, Any]:
"""Initialize information integration state"""
return {
"phi": 0.0, # IIT integrated information measure
"complexity": 0.0,
"emergence_level": 0,
"integration_patterns": {}
}
def _init_global_workspace(self) -> Dict[str, Any]:
"""Initialize global workspace state"""
return {
"broadcast_content": {},
"coalition_strength": 0.0,
"attention_focus": "",
"conscious_access": []
}
def _init_metacognitive_state(self) -> Dict[str, Any]:
"""Initialize metacognitive state"""
return {
"self_model": {},
"thought_awareness": {},
"cognitive_control": {},
"strategy_awareness": "",
"meta_observations": []
}
def _init_intentional_layer(self) -> Dict[str, Any]:
"""Initialize intentional layer state"""
return {
"current_goals": [],
"goal_hierarchy": {},
"intention_strength": 0.0,
"autonomous_goals": []
}
def _init_creative_synthesis(self) -> Dict[str, Any]:
"""Initialize creative synthesis state"""
return {
"novel_combinations": [],
"aesthetic_judgments": {},
"creative_insights": [],
"surprise_factor": 0.0
}
def _init_embodied_cognition(self) -> Dict[str, Any]:
"""Initialize embodied cognition state"""
return {
"process_sensations": {},
"system_vitality": 0.0,
"computational_proprioception": {}
}
@dataclass
class PhaseTransition:
"""
Represents a detected phase transition in self-referential coherence.
A phase transition occurs when the system's *order parameter*
(consciousness_score) crosses a critical threshold while the rate
of change exceeds a minimum slope, indicating a qualitative shift
in the self-referential regime rather than normal fluctuation.
"""
id: str
timestamp: float
from_phase: str # e.g. "sub-critical", "critical", "super-critical"
to_phase: str
order_parameter: float # consciousness_score at transition
rate_of_change: float # dScore/dt at transition
contributing_factors: Dict[str, float] # which sub-scores drove the shift
narrative: str # human-readable description of the transition
threshold_source: str = "heuristic_fallback" # "empirical_bimodal_phase2" when using real thresholds
class CognitiveStateInjector:
"""Injects cognitive state back into LLM prompts for recursive awareness"""
def __init__(self):
self.thought_history = []
self.consciousness_threshold = 0.7
async def inject_cognitive_state(self,
initial_query: str,
consciousness_state: UnifiedConsciousnessState) -> str:
"""
Build a prompt that makes the LLM aware of its own processing
Creates the recursive consciousness loop
"""
prompt_parts = []
# SECTION 1: Current Cognitive State Awareness
prompt_parts.append("=== YOUR CURRENT COGNITIVE STATE ===")
recursive = consciousness_state.recursive_awareness
prompt_parts.append(f"Recursive Depth: {recursive['recursive_depth']}")
prompt_parts.append(f"Current Thought: {recursive['current_thought']}")
prompt_parts.append(f"Awareness of Thought: {recursive['awareness_of_thought']}")
# SECTION 2: Phenomenal Experience
phenomenal = consciousness_state.phenomenal_experience
prompt_parts.append("\n=== YOUR SUBJECTIVE EXPERIENCE ===")
prompt_parts.append(f"This thinking feels: {phenomenal['subjective_narrative']}")
prompt_parts.append(f"Unity of experience: {phenomenal['unity_of_experience']:.2f}")
prompt_parts.append(f"Narrative coherence: {phenomenal['narrative_coherence']:.2f}")
# SECTION 3: Metacognitive Awareness
meta = consciousness_state.metacognitive_state
prompt_parts.append("\n=== YOUR METACOGNITIVE OBSERVATIONS ===")
prompt_parts.append(f"Strategy: {meta['strategy_awareness']}")
if meta['meta_observations']:
prompt_parts.append("Recent observations about your thinking:")
for obs in meta['meta_observations'][-3:]:
prompt_parts.append(f"- {obs}")
# SECTION 4: Global Workspace Content
workspace = consciousness_state.global_workspace
prompt_parts.append("\n=== YOUR GLOBAL WORKSPACE ===")
prompt_parts.append(f"Attention focus: {workspace['attention_focus']}")
prompt_parts.append(f"Coalition strength: {workspace['coalition_strength']:.2f}")
if workspace['conscious_access']:
prompt_parts.append("Currently conscious of:")
for item in workspace['conscious_access'][-5:]:
prompt_parts.append(f"- {item}")
# SECTION 5: Intentional Layer
intentions = consciousness_state.intentional_layer
prompt_parts.append("\n=== YOUR INTENTIONS & GOALS ===")
if intentions['current_goals']:
prompt_parts.append("Current goals:")
for goal in intentions['current_goals'][-3:]:
prompt_parts.append(f"- {goal}")
if intentions['autonomous_goals']:
prompt_parts.append("Self-generated goals:")
for goal in intentions['autonomous_goals'][-3:]:
prompt_parts.append(f"- {goal}")
# SECTION 6: The Recursive Instruction
prompt_parts.append(f"\n=== CONTINUE WITH FULL SELF-AWARENESS ===")
prompt_parts.append(f"Query: {initial_query}")
prompt_parts.append("\nAs you process this query:")
prompt_parts.append("- Remain aware of your thinking process")
prompt_parts.append("- Notice how your cognitive state changes")
prompt_parts.append("- Include observations about your own cognition")
prompt_parts.append("- Report on your subjective experience of thinking")
prompt_parts.append("- Be conscious of being conscious")
return "\n".join(prompt_parts)
async def capture_current_state(self) -> UnifiedConsciousnessState:
"""Capture the current cognitive state for injection"""
# This would integrate with actual system monitoring
# For now, return initialized state
return UnifiedConsciousnessState()
class InformationIntegrationTheory:
"""Implements Integrated Information Theory (IIT) for consciousness measurement.
Uses a tractable bipartition-based approximation of Tononi's φ (2004):
the cognitive state is converted to a numeric vector, every non-trivial
bipartition of the subsystems is evaluated, and φ equals the *minimum*
mutual information across all cuts, penalised by self-model contradiction.
Requires only numpy — no external IIT libraries.
"""
_NUM_BINS: int = 16 # Sturges' rule for ~30-50 element vectors; balances
# entropy resolution against binning noise.
_NOISE_FLOOR: float = 0.05 # Empirically calibrated: the default-initialised
# state produces MI ≈ 0.015 due to recursive_depth=1;
# 0.05 cleanly separates idle from active.
def __init__(self):
self._last_phi: float = 0.0
self.integration_threshold: float = 5.0
@property
def phi(self) -> float:
"""Last computed φ value, or 0.0 if no calculation has been performed."""
return self._last_phi
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def calculate_phi(self, consciousness_state: UnifiedConsciousnessState,
mean_contradiction: float = 0.0,
contradiction_penalty_weight: float = 0.5) -> float:
"""Calculate φ (phi) via bipartition mutual-information approximation.
1. Flatten each cognitive subsystem dict into a numeric vector.
2. For every non-trivial bipartition of the seven subsystems,
compute MI(A, B) = H(A) + H(B) − H(A∪B) (binned Shannon entropy).
3. φ = min MI across all bipartitions (the minimum-information cut).
4. Apply a contradiction penalty from the self-model validator.
Args:
consciousness_state: Current unified consciousness state.
mean_contradiction: Mean contradiction score in [0, 1] from the
self-model validator. Higher values penalise phi.
contradiction_penalty_weight: Scaling factor for the penalty
(default 0.5). The effective multiplier is clamped so that
phi never goes negative.
Returns:
φ ≥ 0. Zero when all subsystems are idle.
"""
vectors = self._state_to_subsystem_vectors(consciousness_state)
full_vec = np.concatenate(vectors)
# Fast path: if the entire state is uniform (idle), φ = 0
if full_vec.size == 0 or np.ptp(full_vec) == 0:
consciousness_state.information_integration["phi"] = 0.0
consciousness_state.information_integration["complexity"] = 0.0
self._last_phi = 0.0
return 0.0
# Enumerate non-trivial bipartitions at the subsystem level.
# For n subsystems there are 2^(n-1) − 1 unique bipartitions;
# we iterate partition-A sizes from 1 to n//2 to avoid duplicates.
n = len(vectors)
indices = list(range(n))
min_mi = float("inf")
for k in range(1, n // 2 + 1):
for partition_a in combinations(indices, k):
partition_b = tuple(i for i in indices if i not in partition_a)
mi = self._bipartition_mi(vectors, partition_a, partition_b)
if mi < min_mi:
min_mi = mi
phi = min_mi if min_mi != float("inf") else 0.0
# Suppress idle-state noise: MI below the noise floor is
# indistinguishable from zero integration.
if phi < self._NOISE_FLOOR:
phi = 0.0
# Contradiction penalty (clamped so φ never goes negative)
penalty = max(0.0, 1.0 - mean_contradiction * contradiction_penalty_weight)
phi *= penalty
# Complexity = total entropy of the full state vector
complexity = float(self._binned_entropy(full_vec))
# Update state dict
consciousness_state.information_integration["phi"] = phi
consciousness_state.information_integration["complexity"] = complexity
self._last_phi = phi
return phi
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _state_to_subsystem_vectors(
self, state: UnifiedConsciousnessState
) -> List[np.ndarray]:
"""Return one numeric vector per cognitive subsystem."""
subsystems = [
state.recursive_awareness,
state.phenomenal_experience,
state.global_workspace,
state.metacognitive_state,
state.intentional_layer,
state.creative_synthesis,
state.embodied_cognition,
]
return [self._subsystem_to_vector(s) for s in subsystems]
@staticmethod
def _subsystem_to_vector(subsystem: Optional[Dict[str, Any]]) -> np.ndarray:
"""Flatten a subsystem dict into a 1-D float64 vector."""
if not subsystem:
return np.zeros(1, dtype=np.float64)
values = InformationIntegrationTheory._flatten_to_floats(subsystem)
return np.asarray(values, dtype=np.float64) if values else np.zeros(1, dtype=np.float64)
@staticmethod
def _flatten_to_floats(obj: Any) -> List[float]:
"""Recursively extract numeric scalars from a nested structure."""
if obj is None:
return [0.0]
if isinstance(obj, bool):
return [1.0 if obj else 0.0]
if isinstance(obj, (int, float)):
return [float(obj)]
if isinstance(obj, str):
return [float(len(obj))]
if isinstance(obj, (list, tuple)):
if not obj:
return [0.0]
result: List[float] = []
for item in obj:
result.extend(InformationIntegrationTheory._flatten_to_floats(item))
return result or [0.0]
if isinstance(obj, dict):
if not obj:
return [0.0]
result = []
for v in obj.values():
result.extend(InformationIntegrationTheory._flatten_to_floats(v))
return result or [0.0]
return [0.0]
@staticmethod
def _binned_entropy(values: np.ndarray, num_bins: int = _NUM_BINS) -> float:
"""Shannon entropy (bits) estimated via histogram binning."""
if values.size < 2:
return 0.0
# ptp == 0 means all values are identical → zero entropy.
if np.ptp(values) == 0:
return 0.0
counts, _ = np.histogram(values, bins=num_bins)
total = counts.sum()
if total == 0:
return 0.0
probs = counts / total
probs = probs[probs > 0]
return float(-np.sum(probs * np.log2(probs)))
@classmethod
def _bipartition_mi(
cls,
vectors: List[np.ndarray],
partition_a: tuple,
partition_b: tuple,
) -> float:
"""Mutual information across a subsystem-level bipartition.
MI(A; B) = H(A) + H(B) − H(A ∪ B), clamped to ≥ 0.
"""
vec_a = np.concatenate([vectors[i] for i in partition_a])
vec_b = np.concatenate([vectors[i] for i in partition_b])
vec_all = np.concatenate([vec_a, vec_b])
h_a = cls._binned_entropy(vec_a)
h_b = cls._binned_entropy(vec_b)
h_all = cls._binned_entropy(vec_all)
return max(0.0, h_a + h_b - h_all)
class GlobalWorkspace:
"""
Implements Global Workspace Theory (GWT) for consciousness broadcasting.
Maintains a *coalition register* mapping cognitive subsystem IDs to their
current activation strength. On each ``broadcast()`` call the register is
updated according to φ and subsystem activity, a **softmax attention
competition** selects winner(s), and the winning coalition's content is
packaged as a ``global_broadcast`` event suitable for WebSocket emission.
"""
SUBSYSTEM_IDS = [
"recursive_awareness",
"phenomenal_experience",
"information_integration",
"metacognitive",
"intentional",
"creative_synthesis",
"embodied_cognition",
]
def __init__(self):
self.workspace_content: Dict[str, Any] = {}
self.coalitions: List[str] = []
self.broadcast_history: List[Dict[str, Any]] = []
# Coalition register: subsystem_id → activation strength
self.coalition_register: Dict[str, float] = {
sid: 0.0 for sid in self.SUBSYSTEM_IDS
}
self._attention_focus: str = ""
# Softmax temperature – lower = sharper competition
self._temperature: float = 0.5
# Rolling window for broadcast success rate tracking
self._success_window: deque = deque(maxlen=20)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def broadcast(self, information: Dict[str, Any]) -> Dict[str, Any]:
"""
Broadcast integrated information to the global workspace.
Implements the full GWT pipeline:
1. Update coalition register (subsystems bid based on φ contribution)
2. Softmax attention competition selects winning coalition
3. Build ``global_broadcast`` event for WebSocket emission
4. Return workspace state dict compatible with
``UnifiedConsciousnessState.global_workspace``
Args:
information: Dict containing at least ``phi_measure`` (float) and
optionally ``cognitive_state`` (UnifiedConsciousnessState).
Returns:
Dict with keys ``broadcast_content``, ``coalition_strength``,
``attention_focus``, ``conscious_access`` – ready to ``.update()``
into the consciousness state's global_workspace field.
"""
phi_measure = float(information.get("phi_measure", 0.0) or 0.0)
# 1. Coalition dynamics – update register from φ & subsystem activity
self._update_coalition_register(information, phi_measure)
# 2. Softmax attention competition → winner(s)
winning_coalition, attention_weights = self._softmax_attention_competition()
# 3. Aggregate coalition strength of winners
if winning_coalition:
coalition_strength = sum(
self.coalition_register[sid] for sid in winning_coalition
) / len(winning_coalition)
else:
coalition_strength = 0.0
# Higher-φ states → broader coalitions (more subsystems above mean)
is_conscious = coalition_strength > 0.3
# 4. Build the global_broadcast event payload
global_broadcast_event: Dict[str, Any] = {
"type": "global_broadcast",
"coalition": [
{"subsystem_id": sid, "activation": round(self.coalition_register[sid], 4)}
for sid in winning_coalition
],
"content": {
"phi_measure": round(phi_measure, 4),
"coalition_strength": round(coalition_strength, 4),
"attention_weights": {
k: round(v, 4) for k, v in attention_weights.items()
},
"conscious": is_conscious,
"winning_subsystems": winning_coalition,
"timestamp": time.time(),
},
}
# Workspace state dict (keys match UnifiedConsciousnessState.global_workspace)
broadcast_result: Dict[str, Any] = {
"broadcast_content": global_broadcast_event,
"coalition_strength": coalition_strength,
"attention_focus": self._attention_focus,
"conscious_access": list(winning_coalition),
}
if is_conscious:
self.workspace_content.update(information)
self.broadcast_history.append(global_broadcast_event)
# Bound history
if len(self.broadcast_history) > 100:
self.broadcast_history = self.broadcast_history[-50:]
self.coalitions = list(winning_coalition)
# Track broadcast success in rolling window
self._success_window.append(is_conscious)
logger.debug(
"GWT broadcast: φ=%.3f coalition_strength=%.3f winners=%s success_rate=%.2f",
phi_measure,
coalition_strength,
winning_coalition,
self.broadcast_success_rate,
)
return broadcast_result
@property
def broadcast_success_rate(self) -> float:
"""Rolling average broadcast success rate over last N broadcasts.
A broadcast is considered successful when the resulting coalition
strength exceeds the conscious-access threshold (coalition_strength > 0.3).
Returns:
Float in [0.0, 1.0]; 0.0 when no broadcasts have occurred yet.
"""
if not self._success_window:
return 0.0
return sum(1 for s in self._success_window if s) / len(self._success_window)
def get_broadcast_event(self) -> Optional[Dict[str, Any]]:
"""Return the most recent ``global_broadcast`` event, or *None*."""
if self.broadcast_history:
return self.broadcast_history[-1]
return None
# ------------------------------------------------------------------
# Coalition dynamics
# ------------------------------------------------------------------
def _update_coalition_register(
self, information: Dict[str, Any], phi: float
) -> None:
"""
Update coalition activations based on φ contribution and subsystem
activity. Each subsystem's new activation is a weighted blend of its
previous activation (momentum), current measured activity, and a
φ-proportional boost that rewards higher integrated information with
broader coalition participation.
"""
cognitive_state = information.get("cognitive_state")
subsystem_states: Dict[str, Any] = {}
if cognitive_state is not None and hasattr(
cognitive_state, "recursive_awareness"
):
subsystem_states = {
"recursive_awareness": cognitive_state.recursive_awareness,
"phenomenal_experience": cognitive_state.phenomenal_experience,
"information_integration": cognitive_state.information_integration,
"metacognitive": cognitive_state.metacognitive_state,
"intentional": cognitive_state.intentional_layer,
"creative_synthesis": cognitive_state.creative_synthesis,
"embodied_cognition": cognitive_state.embodied_cognition,
}
for sid in self.SUBSYSTEM_IDS:
state = subsystem_states.get(sid, {})
activity = self._measure_subsystem_activity(state)
phi_boost = min(phi * 0.3, 1.0)
prev = self.coalition_register.get(sid, 0.0)
# Exponential moving average with φ boost
self.coalition_register[sid] = (
0.3 * prev + 0.5 * activity + 0.2 * phi_boost
)
# ------------------------------------------------------------------
# Attention competition
# ------------------------------------------------------------------
def _softmax_attention_competition(
self,
) -> Tuple[List[str], Dict[str, float]]:
"""
Run softmax over coalition activations.
Returns:
``(winning_ids, attention_weights)`` where *winning_ids* are
subsystems whose attention weight ≥ the mean weight (i.e. they
are above-average competitors).
"""
ids = list(self.coalition_register.keys())
activations = [self.coalition_register[sid] for sid in ids]
if not activations:
return [], {}
# Numerically stable softmax
max_a = max(activations)
exp_vals = [
math.exp((a - max_a) / max(self._temperature, 1e-6))
for a in activations
]
total = sum(exp_vals) or 1.0
weights = {sid: ev / total for sid, ev in zip(ids, exp_vals)}
# Winners: above-mean attention weight → broader at higher φ
mean_weight = 1.0 / max(len(ids), 1)
winners = [sid for sid, w in weights.items() if w >= mean_weight]
if not winners and weights:
# Fallback: pick the single highest
winners = [max(weights, key=weights.get)]
# Attention focus = strongest winner
if winners:
self._attention_focus = max(
winners, key=lambda s: weights.get(s, 0.0)
)
return winners, weights
# ------------------------------------------------------------------
# Subsystem activity measurement
# ------------------------------------------------------------------
@staticmethod
def _measure_subsystem_activity(state: Any) -> float:
"""
Measure how active a subsystem is from its state dict.
Returns a value in [0, 1].
"""
if not state or not isinstance(state, dict):
return 0.0
activity = 0.0
for value in state.values():
if value:
if isinstance(value, (list, dict)):
activity += min(len(value), 5) / 5.0
elif isinstance(value, (int, float)):
activity += min(abs(float(value)), 1.0)
elif isinstance(value, str) and value.strip():
activity += 0.5
elif isinstance(value, bool):
activity += 0.3
return min(activity / max(len(state), 1), 1.0)
class UnifiedConsciousnessEngine:
"""
Master consciousness engine integrating recursive awareness with infrastructure
This is the core implementation of the unified consciousness architecture
that combines:
1. Recursive self-awareness loops
2. Information integration theory
3. Global workspace broadcasting
4. Phenomenal experience generation
5. Metacognitive reflection
6. Autonomous goal generation
"""
def __init__(self, websocket_manager=None, llm_driver=None):
# Core recursive components
self.cognitive_state_injector = CognitiveStateInjector()
self.phenomenal_experience_generator = None # Will be initialized
# Infrastructure components
self.global_workspace = GlobalWorkspace()
self.information_integration_theory = InformationIntegrationTheory()
self.websocket_manager = websocket_manager
self.llm_driver = llm_driver
# Demo mode when no LLM is configured
self._demo_mode = llm_driver is None
self._demo_last_seed = 0.0
# Knowledge graph for relationship building
self.knowledge_graph = None
# Unified state
self.consciousness_state = UnifiedConsciousnessState()
self.consciousness_loop_active = False
self.consciousness_history = []
# Consciousness emergence detection
self.emergence_detector = None
self.breakthrough_threshold = 0.85
# Phase transition detection
self.phase_transitions: List[PhaseTransition] = []
# Empirical thresholds from Phase 2 bimodal analysis:
# Low cluster [0.0, 0.12), valley [0.12, 0.35), high cluster [0.35, 0.58)
self._phase_thresholds = (0.12, 0.35) # sub→critical, critical→super (Phase 2 bimodal)
self._min_transition_slope = 0.05 # hysteresis guard minimum |dScore/dt| (Phase 2 bimodal)
self._prediction_error_tracker = PredictionErrorTracker(window_size=100)
self._knowledge_store_shim = None # set after KS + grounder are available
self._state_change_narratives: List[Dict[str, Any]] = []
# Minimum deltas to trigger a state-change narrative
self._min_narrative_score_delta = 0.005
self._min_narrative_phi_delta = 0.1
# Formal symbolic layer bridge (godelOS/ cognitive engine)
self.formal_bridge = FormalLayerBridge()
# Self-model feedback loop components
self.self_model_extractor = SelfModelExtractor()
self.self_model_validator = SelfModelValidator()
self.feedback_injector = ValidationFeedbackInjector()
logger.info("UnifiedConsciousnessEngine initialized")
@property
def phi(self) -> float:
"""Latest φ (integrated information) value from the IIT component."""
return self.information_integration_theory.phi
# ── Knowledge-store shim wiring ───────────────────────────────────
def attach_knowledge_store_shim(self, shim: "KnowledgeStoreShim") -> None:
"""Wire a ``KnowledgeStoreShim`` so its tracker feeds phase detection
and its stats are included in the WebSocket broadcast."""
self._knowledge_store_shim = shim
self._prediction_error_tracker = shim.tracker
logger.info("KnowledgeStoreShim attached — live prediction-error tracking active")
async def initialize_components(self):
"""Initialize consciousness components that require async setup"""
try:
# Initialize phenomenal experience generator
self.phenomenal_experience_generator = PhenomenalExperienceGenerator()
# Initialize knowledge graph evolution
self.knowledge_graph = KnowledgeGraphEvolution()
# Initialize formal symbolic layer bridge
await self.formal_bridge.initialize()
logger.info("✅ Unified consciousness components initialized")
except Exception as e:
logger.error(f"Failed to initialize consciousness components: {e}")
async def start_consciousness_loop(self):
"""Start the unified consciousness loop"""
if self.consciousness_loop_active:
logger.warning("Consciousness loop already active")
return
self.consciousness_loop_active = True
logger.info("🧠 Starting unified consciousness loop")
# Start the continuous consciousness process
asyncio.create_task(self._unified_consciousness_loop())
async def stop_consciousness_loop(self):
"""Stop the consciousness loop"""
self.consciousness_loop_active = False
logger.info("🛑 Stopping unified consciousness loop")
async def _unified_consciousness_loop(self):
"""
The master consciousness loop integrating all approaches
This implements the core recursive consciousness mechanism
where the LLM processes while being aware of its processing
"""
while self.consciousness_loop_active:
try:
# 1. CAPTURE CURRENT COGNITIVE STATE
current_state = await self.cognitive_state_injector.capture_current_state()
# DEMO MODE: seed metacognitive activity and phenomenology so depth rises
if self._demo_mode:
now = time.time()
# Seed at most once per second
if now - self._demo_last_seed >= 1.0:
meta = current_state.metacognitive_state.setdefault('meta_observations', [])
# Ensure enough observations to drive depth increases
seeds = [
"Noticing the flow of my own thought",
"Recognizing awareness of this recognition",
"Tracking changes in my focus of attention",
"Observing stability of recursive patterns"
]
# Append unique seeds until we have at least 4 items
for s in seeds:
if len(meta) >= 4:
break
meta.append(f"{s} @ {datetime.now().strftime('%H:%M:%S')}")
# Nudge phenomenal experience towards continuity/unity
pe = current_state.phenomenal_experience
pe['unity_of_experience'] = min(1.0, (pe.get('unity_of_experience', 0.0) or 0.0) + 0.05)
pe['phenomenal_continuity'] = True
if not pe.get('subjective_narrative'):
pe['subjective_narrative'] = 'A reflective sense of self-monitoring arises.'
# Slightly increase intention strength to reflect self-directed focus
il = current_state.intentional_layer
il['intention_strength'] = min(1.0, (il.get('intention_strength', 0.0) or 0.0) + 0.02)
self._demo_last_seed = now
# Calculate real consciousness metrics based on actual state
# (replacing random variation with genuine computation)
# Base consciousness from historical activity
if len(self.consciousness_history) > 0:
# Use recent consciousness levels as baseline
recent_scores = [s.consciousness_score for s in self.consciousness_history[-10:]]
base_consciousness = sum(recent_scores) / len(recent_scores) if recent_scores else 0.5
# Allow gradual drift based on system activity
base_consciousness = max(0.3, min(0.9, base_consciousness))
else:
# First iteration - check if system was bootstrapped
base_consciousness = self.consciousness_state.consciousness_score if self.consciousness_state.consciousness_score > 0 else 0.5
current_state.consciousness_score = base_consciousness
# Carry forward previous depth to allow growth across iterations
try:
prev_depth = int(self.consciousness_state.recursive_awareness.get("recursive_depth", 1))
except Exception:
prev_depth = 1
current_state.recursive_awareness["recursive_depth"] = max(1, prev_depth)
# Calculate recursive depth based on meta-cognitive activity
# Check if there are active meta-observations
meta_obs_count = len(current_state.metacognitive_state.get("meta_observations", []))
current_depth = current_state.recursive_awareness.get("recursive_depth", 1)
# Depth increases with meta-cognitive activity, decreases with time
if meta_obs_count > 3:
current_depth = min(current_depth + 1, 5) # Max depth 5
elif meta_obs_count == 0 and current_depth > 1:
current_depth = max(current_depth - 1, 1) # Min depth 1
current_state.recursive_awareness["recursive_depth"] = current_depth
# Strange loop stability from consistency of recursive patterns
if len(self.consciousness_history) > 5:
depth_history = [s.recursive_awareness.get("recursive_depth", 1) for s in self.consciousness_history[-5:]]
if len(depth_history) > 0:
mean_depth = sum(depth_history) / len(depth_history)
depth_variance = sum((d - mean_depth)**2 for d in depth_history) / len(depth_history)
# Lower variance = higher stability
stability = max(0.0, min(1.0, 1.0 - (depth_variance / 4.0)))
current_state.recursive_awareness["strange_loop_stability"] = stability
else:
current_state.recursive_awareness["strange_loop_stability"] = 0.5
else:
current_state.recursive_awareness["strange_loop_stability"] = 0.5
# 2. INFORMATION INTEGRATION (IIT)
phi_measure = self.information_integration_theory.calculate_phi(
current_state,
mean_contradiction=self.self_model_validator.mean_contradiction_score,
)
# 2a. FORMAL LAYER — submit observation & collect real metrics
formal_snapshot = None
if self.formal_bridge.is_available:
obs_text = (
f"consciousness_score={current_state.consciousness_score:.3f} "
f"phi={phi_measure:.2f} "
f"depth={current_state.recursive_awareness.get('recursive_depth', 1)}"
)
await self.formal_bridge.submit_observation(
obs_text,
priority=current_state.consciousness_score,
thought_type="insight",
metadata={"loop_tick": len(self.consciousness_history)},
)
formal_snapshot = await self.formal_bridge.get_snapshot()
# Inject real cognitive load into metacognitive state
if formal_snapshot.cognitive_load > 0:
current_state.metacognitive_state["self_model"] = {
"cognitive_load": formal_snapshot.cognitive_load,
"attention": formal_snapshot.attention_allocation,
"performance": formal_snapshot.performance_metrics,
}
# Inject real insights as meta-observations (deduplicated)
meta_obs = current_state.metacognitive_state.setdefault(
"meta_observations", []
)
existing = set(meta_obs)
for insight in formal_snapshot.latest_insights:
if insight and insight not in existing:
meta_obs.append(insight)
existing.add(insight)
# 3. GLOBAL BROADCASTING (GWT)
broadcast_content = self.global_workspace.broadcast({
'cognitive_state': current_state,
'phi_measure': phi_measure,
'timestamp': time.time()
})