File size: 50,892 Bytes
12fa855
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182

"""
ATC-Native Layer 2 Cognitive Subsystems
========================================

Integrates cognitive components (memory, emotional intelligence, intuition,
common sense, analysis) as ATC-native Layer 2 subconscious processing
subsystems that feed directly into the NIMA middleware pipeline.

ATC Pipeline Mapping (Perfect Breakfast Scenario):

  [Layer 1: Raw Input]
      |
      V
  [Layer 2: Subconscious Parallel Processing]  <-- THIS MODULE
      |-- SubconsciousPatternMatch  -> prediction_confidence -> DissolutionEngine
      |-- EmotionalBridge           -> valence/arousal       -> phi_neuro, BELBIC
      |-- IntuitiveGutCheck         -> gut_safety            -> TRN predictive gating
      |-- CommonSenseRealityFilter  -> passes_reality_check  -> Layer 4 self-understanding
      |-- MemoryPatternMatcher      -> matched_patterns      -> temporal coherence
      |
      V
  [Layer 3: Qualia Generation]  -> friction / felt sense
      |
      V
  [Layer 4: Metacognitive Loop]
      |-- AnalyticalEngine         -> analysis_depth         -> metacognitive_depth_mod
      |
      V
  [Layer 5: Acknowledgement -> Delta_R rewrite]

Source: Syntelligence cognitive agents (Memory, EI, Intuition, CommonSense,
Analysis), rewritten as ATC-native subsystems with no CLI dependencies,
no emoji, and unified data types matching middleware.py.

Author: NIMA Unified Model — ATC Cognitive Layer 2
"""

__all__ = [
    "Layer2Result",
    "PatternMatchResult",
    "EmotionalBridgeResult",
    "GutCheckResult",
    "RealityCheckResult",
    "AnalysisEngineResult",
    "SubconsciousPatternMatch",
    "EmotionalBridge",
    "IntuitiveGutCheck",
    "CommonSenseRealityFilter",
    "AnalyticalEngine",
    "CognitiveLayer2Orchestrator",
]

import logging
import math
import time
import uuid
from collections import Counter, defaultdict, deque
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple

logger = logging.getLogger("ATC.Layer2")

# ---------------------------------------------------------------------------
# Safe imports from middleware (graceful fallback if structure changes)
# No middleware imports at module level -- avoids torch dependency.
# The orchestrator uses its own dataclasses and returns plain dicts
# compatible with middleware SubconsciousOutput when available.


# ===================================================================
# SECTION 1 — Return-Type Dataclasses
# ===================================================================

@dataclass
class PatternMatchResult:
    """Output of SubconsciousPatternMatch.

    ATC mapping: prediction_confidence feeds DissolutionEngine;
    prediction_error feeds phi computation as friction signal.
    """
    prediction_confidence: float = 0.0
    prediction_label: str = ""
    matched_memory_refs: List[str] = field(default_factory=list)
    is_novel: bool = True
    matched_patterns: List[str] = field(default_factory=list)
    novelty_score: float = 1.0


@dataclass
class EmotionalBridgeResult:
    """Output of EmotionalBridge.

    ATC mapping: valence/arousal feed directly into phi_neuro
    (Theorem 2 qualia vector) and BELBIC amygdala/OFC weight updates.
    """
    valence: float = 0.0
    arousal: float = 0.3
    emotion_label: str = "neutral"
    emotion_confidence: float = 0.0
    si_vector: Dict[str, float] = field(default_factory=dict)
    emotion_profile: Dict[str, float] = field(default_factory=dict)
    cognitive_modulation: Dict[str, float] = field(default_factory=dict)


@dataclass
class GutCheckResult:
    """Output of IntuitiveGutCheck.

    ATC mapping: predicted_safety feeds TRN predictive gating
    (the 'is this situation predicted?' check). High safety = low
    surprise = PASS through thalamic gate with low friction.
    """
    predicted_safety: float = 0.5
    gut_confidence: float = 0.0
    triggering_patterns: List[str] = field(default_factory=list)
    intuition_type: str = "affective"
    energy_cost: float = 0.1
    threat_score: float = 0.0
    opportunity_score: float = 0.0


@dataclass
class RealityCheckResult:
    """Output of CommonSenseRealityFilter.

    ATC mapping: passes_reality_check feeds self-understanding in
    Layer 4. When reality check FAILS, the rejection loop causes
    ATP depletion -> metabolic exhaustion (Theorem 3).
    """
    passes_reality_check: bool = True
    deviation_score: float = 0.0
    warnings: List[str] = field(default_factory=list)
    warning_level: str = "none"
    domain_violations: List[str] = field(default_factory=list)
    rejection_cost: float = 0.0  # Estimated ATP cost of a reality-check failure


@dataclass
class AnalysisEngineResult:
    """Output of AnalyticalEngine.

    ATC mapping: feeds metacognitive_depth_mod into Layer 4
    processing. Emergent insights can trigger irrational spark
    if they reveal prediction collapse.
    """
    analysis_depth: float = 0.3
    reasoning_confidence: float = 0.5
    emergent_insights: List[str] = field(default_factory=list)
    problem_type: str = "unknown"
    complexity_estimate: float = 0.3
    integration_score: float = 0.0
    scales_analyzed: List[str] = field(default_factory=list)


@dataclass
class Layer2Result:
    """Unified output of the CognitiveLayer2Orchestrator.

    This is the single dataclass the middleware consumes. Every field
    maps to an ATC pipeline signal:

      prediction_error   -> DissolutionEngine (friction)
      valence / arousal  -> phi_neuro computation (Theorem 2)
      gut_safety         -> TRN predictive gating
      passes_reality_check -> self-understanding in Layer 4
      thermodynamic_cost   -> allostatic load (Theorem 3)
    """
    prediction_confidence: float = 0.0
    prediction_label: str = ""
    valence: float = 0.0
    arousal: float = 0.3
    emotion_label: str = "neutral"
    gut_safety: float = 0.5
    intuition_confidence: float = 0.0
    passes_reality_check: bool = True
    common_sense_warnings: List[str] = field(default_factory=list)
    is_novel: bool = True
    matched_patterns: List[str] = field(default_factory=list)
    thermodynamic_cost: float = 0.0
    prediction_error: float = 0.0
    # Sub-results for deeper inspection
    pattern_match: Optional[PatternMatchResult] = None
    emotional_bridge: Optional[EmotionalBridgeResult] = None
    gut_check: Optional[GutCheckResult] = None
    reality_check: Optional[RealityCheckResult] = None
    analysis: Optional[AnalysisEngineResult] = None

    def to_subconscious_output(self) -> Dict[str, Any]:
        """Convert to a dict compatible with middleware's SubconsciousOutput."""
        return {
            "raw_percept": self.prediction_label,
            "intuition_score": self.intuition_confidence,
            "common_sense_score": 1.0 - (self.prediction_error if self.passes_reality_check else 1.0),
            "coherence": self.prediction_confidence,
            "novelty_score": 1.0 - self.prediction_confidence,
            "emotional_charge": abs(self.valence) * self.arousal,
            "layer2_detailed": self.to_dict(),
        }

    def to_dict(self) -> Dict[str, Any]:
        """Serializable dict for diagnostics."""
        return {
            "prediction_confidence": self.prediction_confidence,
            "prediction_label": self.prediction_label,
            "valence": self.valence,
            "arousal": self.arousal,
            "emotion_label": self.emotion_label,
            "gut_safety": self.gut_safety,
            "intuition_confidence": self.intuition_confidence,
            "passes_reality_check": self.passes_reality_check,
            "common_sense_warnings": self.common_sense_warnings,
            "is_novel": self.is_novel,
            "matched_patterns": self.matched_patterns,
            "thermodynamic_cost": self.thermodynamic_cost,
            "prediction_error": self.prediction_error,
        }


# ===================================================================
# SECTION 2 — Ekman 8-Basic-Emotions Definitions
# ===================================================================

_EKMAN_EMOTIONS: Dict[str, Dict[str, Any]] = {
    "joy": {
        "triggers": ["success", "achieve", "happy", "happily", "smile", "smiling", "celebrat", "wonderful", "great", "love", "loving", "beautiful", "kind", "kindly", "warm", "warmly", "pleased", "glad", "delight", "cheerful"],
        "valence": 0.9, "arousal": 0.6, "avoid": False,
        "facilitates": ["creativity", "cooperation", "openness"],
        "reduces": ["caution", "detailed_analysis"],
    },
    "sadness": {
        "triggers": ["loss", "fail", "failed", "failing", "disappoint", "disappointed", "miss", "missed", "gone", "sorry", "regret", "lonely", "grief", "cry", "crying", "tears", "sad", "sadly", "unhappy", "upset", "depress"],
        "valence": -0.9, "arousal": 0.2, "avoid": True,
        "facilitates": ["focus", "detail_attention", "caution"],
        "reduces": ["risk_taking", "creativity"],
    },
    "anger": {
        "triggers": ["angry", "angrily", "anger", "furious", "furiously", "injust", "violat", "violation", "unfair", "rage", "raging", "hate", "hateful", "outrag", "outraged", "resent", "annoy", "annoyed", "annoying", "yell", "yelling", "shout", "shouting", "scream", "fury", "hostile", "hostility"],
        "valence": -0.7, "arousal": 0.9, "avoid": True,
        "facilitates": ["motivation", "focus", "persistence"],
        "reduces": ["diplomacy", "nuance"],
    },
    "fear": {
        "triggers": ["fear", "fearful", "feared", "afraid", "threat", "threaten", "danger", "dangerous", "scare", "scared", "terrif", "terrified", "terror", "panic", "worr", "worried", "worrying", "anxi", "anxious", "risk", "risky", "dread", "fright", "frightened"],
        "valence": -0.8, "arousal": 0.8, "avoid": True,
        "facilitates": ["caution", "risk_analysis", "defensive_planning"],
        "reduces": ["risk_taking", "aggression"],
    },
    "surprise": {
        "triggers": ["surprise", "surprised", "surprising", "unexpected", "unexpectedly", "sudden", "suddenly", "shock", "shocked", "shocking", "wow", "amazing", "unbelievable", "strange", "weird", "astonish", "stunn"],
        "valence": 0.0, "arousal": 0.9, "avoid": False,
        "facilitates": ["attention", "learning", "memory_formation"],
        "reduces": ["routine_execution"],
    },
    "disgust": {
        "triggers": ["disgust", "disgusted", "disgusting", "repel", "repuls", "offensive", "gross", "vile", "toxic", "nasty", "horrible", "loathe", "revolt", "revolting", "sick", "sickened"],
        "valence": -0.8, "arousal": 0.5, "avoid": True,
        "facilitates": ["boundary_setting", "discrimination"],
        "reduces": ["openness", "acceptance"],
    },
    "anticipation": {
        "triggers": ["anticipat", "anticipate", "anticipation", "expect", "expected", "expecting", "plan", "planning", "ready", "upcom", "soon", "about to", "prepar", "preparing", "forward", "looking forward", "eager", "eagerly"],
        "valence": 0.5, "arousal": 0.7, "avoid": False,
        "facilitates": ["planning", "preparation", "proactive_behavior"],
        "reduces": ["immediate_action"],
    },
    "trust": {
        "triggers": ["trust", "trusted", "trusting", "safe", "safely", "safety", "reliab", "reliable", "reliably", "confident", "confidently", "secure", "securely", "honest", "honestly", "depend", "dependable", "faith", "faithful", "believe", "believing", "certain", "reassur"],
        "valence": 0.7, "arousal": 0.3, "avoid": False,
        "facilitates": ["cooperation", "openness", "acceptance"],
        "reduces": ["suspicion", "caution"],
    },
}

# Common sense knowledge base (realistic rules, not placeholders)
_COMMON_SENSE_RULES: List[Dict[str, str]] = [
    # Social
    {"domain": "social", "condition": "person is upset", "pattern": "emotional_contagion",
     "response": "validate emotion, offer support", "confidence": "0.85"},
    {"domain": "social", "condition": "trust is broken", "pattern": "trust_violation",
     "response": "requires accountability and restitution", "confidence": "0.90"},
    {"domain": "social", "condition": "people interact repeatedly", "pattern": "reciprocity",
     "response": "help those who help you", "confidence": "0.85"},
    {"domain": "social", "condition": "someone asks for help", "pattern": "prosocial_norm",
     "response": "helping strengthens bonds", "confidence": "0.80"},
    {"domain": "social", "condition": "person lies repeatedly", "pattern": "credibility_decay",
     "response": "trust erodes proportionally to deception frequency", "confidence": "0.90"},
    # Physical
    {"domain": "physical", "condition": "object released in air", "pattern": "gravity",
     "response": "object falls downward", "confidence": "0.99"},
    {"domain": "physical", "condition": "water heated past 100C at sea level", "pattern": "phase_transition",
     "response": "water becomes steam", "confidence": "0.99"},
    {"domain": "physical", "condition": "force applied to stationary object", "pattern": "inertia",
     "response": "object resists change in motion", "confidence": "0.95"},
    # Temporal
    {"domain": "temporal", "condition": "cause precedes effect", "pattern": "causality",
     "response": "effect cannot precede its cause", "confidence": "0.99"},
    {"domain": "temporal", "condition": "system left unattended", "pattern": "entropy",
     "response": "disorder increases without energy input", "confidence": "0.95"},
    {"domain": "temporal", "condition": "habit practiced daily", "pattern": "skill_acquisition",
     "response": "competence increases over weeks", "confidence": "0.90"},
    # Psychological
    {"domain": "psychological", "condition": "person is sleep-deprived", "pattern": "cognitive_decline",
     "response": "decision quality declines, irritability increases", "confidence": "0.90"},
    {"domain": "psychological", "condition": "intense fear active", "pattern": "amygdala_hijack",
     "response": "rational thinking is impaired", "confidence": "0.90"},
    {"domain": "psychological", "condition": "repeated failure without support", "pattern": "learned_helplessness",
     "response": "motivation collapses even when escape is possible", "confidence": "0.85"},
    # Biological
    {"domain": "biological", "condition": "organism deprived of oxygen", "pattern": "hypoxia",
     "response": "consciousness degrades within minutes", "confidence": "0.99"},
    {"domain": "biological", "condition": "prolonged stress", "pattern": "cortisol_damage",
     "response": "hippocampal volume decreases, memory impaired", "confidence": "0.85"},
    # Cultural / Abstract
    {"domain": "cultural", "condition": "question is asked", "pattern": "conversational_turn",
     "response": "a response is expected within social norms", "confidence": "0.85"},
    {"domain": "cultural", "condition": "gift is given", "pattern": "reciprocity_norm",
     "response": "social expectation of eventual reciprocity", "confidence": "0.80"},
]

# Threat / safety keyword banks for intuition gut-check
_THREAT_KEYWORDS: List[str] = [
    "danger", "risk", "toxic", "unsafe", "attack", "threat", "harm",
    "weapon", "kill", "destroy", "violence", "abuse", "manipulat",
    "deceit", "betray", "hostile", "enemy", "crisis", "emergency",
    "warning", "alarm", "urgent", "critical", "severe",
]

_SAFETY_KEYWORDS: List[str] = [
    "safe", "secure", "trusted", "aligned", "right", "correct",
    "reliable", "honest", "kind", "warm", "care", "support",
    "help", "comfort", "peace", "calm", "gentle", "good",
    "healthy", "positiv", "success", "achieve", "joy", "love",
]

_OPPORTUNITY_KEYWORDS: List[str] = [
    "opportunity", "opening", "chance", "resource", "ally", "gift",
    "potential", "growth", "learn", "discover", "create", "build",
    "improve", "develop", "advance", "progress", "benefit", "gain",
]


# ===================================================================
# SECTION 3 — SubconsciousPatternMatch
# ===================================================================

class SubconsciousPatternMatch:
    """Layer 2: Fast parallel pattern matching against memory.

    ATC mapping: Matches sensory input against stored memory patterns
    to generate a prediction. prediction_confidence feeds the
    DissolutionEngine -- high confidence = low friction (automated/zombie).
    Low confidence or novel input = prediction collapse = friction = felt sense.

    Rewritten from SyntelligenceMemoryAgent pattern recognition, stripped
    of numpy/async/CLI dependencies.
    """

    def __init__(self, max_memory_entries: int = 5000) -> None:
        self._memory: Dict[str, Dict[str, Any]] = {}
        self._tag_index: Dict[str, Set[str]] = defaultdict(set)
        self._patterns: Dict[str, Dict[str, Any]] = {}
        self._access_history: deque = deque(maxlen=500)
        self._max_entries = max_memory_entries
        self._consolidation_rate = 0.1
        self._pattern_min_freq = 2

    # -- Memory operations --

    def store(
        self,
        content: str,
        tags: Optional[List[str]] = None,
        importance: float = 0.5,
        valence: float = 0.0,
        arousal: float = 0.0,
    ) -> str:
        """Store a memory entry and run pattern detection."""
        mem_id = f"mem_{uuid.uuid4().hex[:8]}_{int(time.time())}"
        self._memory[mem_id] = {
            "content": content,
            "tags": set(tags or []),
            "importance": max(0.0, min(1.0, importance)),
            "valence": max(-1.0, min(1.0, valence)),
            "arousal": max(0.0, min(1.0, arousal)),
            "access_count": 0,
            "consolidation": 0.0,
            "timestamp": time.time(),
        }
        for tag in (tags or []):
            self._tag_index[tag].add(mem_id)
        # Prune if over limit
        if len(self._memory) > self._max_entries:
            self._prune()
        return mem_id

    def match(self, stimulus: str, context: Optional[Dict[str, Any]] = None) -> PatternMatchResult:
        """Match stimulus against stored memories.

        Returns prediction_confidence, matched pattern labels, and novelty.
        This is the ATC Layer 2 'subconscious parallel matrix' entry point.
        """
        stimulus_lower = stimulus.lower()
        words = set(stimulus_lower.split())
        scores: List[Tuple[str, float]] = []

        for mem_id, mem in self._memory.items():
            content_words = set(mem["content"].lower().split())
            # Jaccard-like overlap
            if not words or not content_words:
                continue
            overlap = len(words & content_words) / max(1, len(words | content_words))
            # Boost by consolidation and importance
            score = overlap * (0.5 + 0.3 * mem["consolidation"] + 0.2 * mem["importance"])
            if score > 0.05:
                scores.append((mem_id, score))

        scores.sort(key=lambda x: x[1], reverse=True)
        top_refs = [s[0] for s in scores[:5]]

        # Determine matched pattern names
        matched_patterns = self._find_matching_patterns(stimulus_lower)

        # Update access counts
        for mem_id, _ in scores[:10]:
            self._memory[mem_id]["access_count"] += 1
            self._memory[mem_id]["last_accessed"] = time.time()
            self._access_history.append(mem_id)

        if not scores and not matched_patterns:
            return PatternMatchResult(
                prediction_confidence=0.0,
                prediction_label="novel_stimulus",
                matched_memory_refs=[],
                is_novel=True,
                matched_patterns=[],
                novelty_score=1.0,
            )

        confidence = min(1.0, scores[0][1] * 2.0) if scores else 0.3
        # Blend with pattern confidence
        if matched_patterns:
            pattern_conf = max(
                self._patterns.get(p, {}).get("confidence", 0.0) for p in matched_patterns
            )
            confidence = 0.6 * confidence + 0.4 * pattern_conf

        label = self._generate_prediction_label(stimulus_lower, matched_patterns, scores)

        return PatternMatchResult(
            prediction_confidence=confidence,
            prediction_label=label,
            matched_memory_refs=top_refs,
            is_novel=confidence < 0.3,
            matched_patterns=matched_patterns,
            novelty_score=max(0.0, 1.0 - confidence),
        )

    # -- Pattern detection --

    def _find_matching_patterns(self, text: str) -> List[str]:
        """Find known patterns that match the stimulus text."""
        matched = []
        for pid, pat in self._patterns.items():
            triggers = pat.get("contextual_triggers", [])
            if any(t in text for t in triggers):
                matched.append(pid)
        return matched

    def _generate_prediction_label(
        self,
        text: str,
        matched_patterns: List[str],
        scores: List[Tuple[str, float]],
    ) -> str:
        """Generate a human-readable prediction label."""
        if matched_patterns:
            best = max(matched_patterns, key=lambda p: self._patterns.get(p, {}).get("confidence", 0.0))
            pat = self._patterns.get(best, {})
            return pat.get("prediction", f"pattern_match:{best}")
        if scores:
            top_id = scores[0][0]
            mem = self._memory.get(top_id, {})
            content = mem.get("content", "")
            return content[:60] if content else "memory_echo"
        return "weak_association"

    def _prune(self) -> None:
        """Remove lowest-value memories."""
        entries = list(self._memory.items())
        entries.sort(key=lambda x: (x[1]["importance"] + x[1]["consolidation"]) / 2)
        remove_count = len(entries) - self._max_entries + int(self._max_entries * 0.1)
        for mem_id, _ in entries[:max(1, remove_count)]:
            tags = self._memory[mem_id].get("tags", set())
            for t in tags:
                self._tag_index[t].discard(mem_id)
            del self._memory[mem_id]

    def get_memory_count(self) -> int:
        return len(self._memory)


# ===================================================================
# SECTION 4 — EmotionalBridge
# ===================================================================

class EmotionalBridge:
    """Layer 2: Emotional intelligence mapped to ATC's BELBIC amygdala/OFC.

    Takes perceived context (stimulus text) and returns valence, arousal,
    emotion_label, and an si_vector (somatic influence vector) that feed
    directly into phi_neuro computation (Theorem 2 qualia vector) and
    BELBIC fast-path/contextual-inhibition weight updates.

    Rewritten from EmotionalIntelligenceAgent, MSCM model preserved,
    CLI/emoji/threading removed, 8 Ekman emotions as internal taxonomy.
    """

    def __init__(self) -> None:
        self._emotion_history: deque = deque(maxlen=200)
        self._transition_count: int = 0
        self._prev_emotion: str = "neutral"

    def process(self, stimulus: str, context: Optional[Dict[str, Any]] = None) -> EmotionalBridgeResult:
        """Map stimulus text to emotional state parameters.

        ATC signal: valence and arousal feed directly into Theorem 2's
        qualia vector Q = [v, a, i, f], and into BELBIC amygdala/OFC
        sensory input channels.
        """
        text = stimulus.lower()

        # Score each emotion
        scores: Dict[str, float] = {}
        for emotion, info in _EKMAN_EMOTIONS.items():
            score = sum(1.0 for trigger in info["triggers"] if trigger in text)
            scores[emotion] = score

        # Also check context-provided signals
        if context:
            signals = context.get("signals", [])
            for signal in signals:
                sig_lower = str(signal).lower()
                for emotion, info in _EKMAN_EMOTIONS.items():
                    if any(t in sig_lower for t in info["triggers"]):
                        scores[emotion] = scores.get(emotion, 0.0) + 0.5

        # Determine dominant emotion
        if not scores or max(scores.values()) == 0:
            return EmotionalBridgeResult(
                valence=0.0, arousal=0.3, emotion_label="neutral",
                emotion_confidence=0.0, si_vector={}, emotion_profile=scores,
            )

        total = sum(scores.values())
        normalized = {e: s / total for e, s in scores.items()}

        dominant = max(normalized, key=normalized.get)  # type: ignore[arg-type]
        confidence = normalized[dominant]
        info = _EKMAN_EMOTIONS[dominant]

        # Compute valence and arousal as weighted blend of all detected emotions
        valence = sum(
            _EKMAN_EMOTIONS[e]["valence"] * w for e, w in normalized.items()
        )
        valence = max(-1.0, min(1.0, valence))

        arousal = sum(
            _EKMAN_EMOTIONS[e]["arousal"] * w for e, w in normalized.items()
        )
        arousal = max(0.0, min(1.0, arousal))

        # Track transitions
        if dominant != self._prev_emotion and self._prev_emotion != "neutral":
            self._transition_count += 1
        self._prev_emotion = dominant
        self._emotion_history.append(dominant)

        # Somatic influence vector (feeds BELBIC sensory channels)
        si_vector = {
            "valence": valence,
            "arousal": arousal,
            "novelty": 1.0 - confidence,
            "qualia_intensity": confidence * arousal,
        }

        # Cognitive modulation (feeds EmotionalIntelligenceAgent.influence_cognition)
        cognitive_modulation = {
            "attention_boost": 0.5 + 0.5 * arousal,
            "creativity_boost": max(0.0, valence) * 0.5,
            "caution_boost": max(0.0, -valence) * 0.3 + (1.0 - confidence) * 0.2,
            "social_engagement": max(0.0, valence) * 0.4,
        }

        return EmotionalBridgeResult(
            valence=valence,
            arousal=arousal,
            emotion_label=dominant,
            emotion_confidence=confidence,
            si_vector=si_vector,
            emotion_profile=normalized,
            cognitive_modulation=cognitive_modulation,
        )

    def get_complexity(self) -> float:
        """Emotional complexity score (0-1) based on transition diversity."""
        if len(self._emotion_history) < 5:
            return 0.2
        recent = list(self._emotion_history)[-50:]
        unique = len(set(recent))
        return min(1.0, unique / 8.0)  # 8 = max distinct emotions


# ===================================================================
# SECTION 5 — IntuitiveGutCheck
# ===================================================================

class IntuitiveGutCheck:
    """Layer 2: Low-road intuition (Kahneman System 1).

    ATC mapping: Maps to TRN predictive gating -- the 'is this situation
    predicted?' check. If gut says SAFE and prediction matches, thalamic
    gate PASSES with low friction. If gut detects THREAT, the DissolutionEngine
    is primed for prediction collapse.

    Rewritten from IntuitionAgent.gut_check, with heart_intelligence
    and visionary_insight collapsed into a single fast heuristic.
    Emoji removed, threading removed.
    """

    def __init__(self) -> None:
        self._history: deque = deque(maxlen=500)
        self._accuracy: List[bool] = []

    def check(self, stimulus: str, context: Optional[Dict[str, Any]] = None) -> GutCheckResult:
        """Fast System 1 gut-check on the stimulus.

        Returns safety score, confidence, and triggering patterns.
        Energy cost is low (~0.1) because this is amygdala-level processing.
        """
        text = stimulus.lower()
        extra_signals = []
        if context:
            extra_signals = context.get("signals", [])

        # Count threat indicators
        threat_hits = sum(1 for kw in _THREAT_KEYWORDS if kw in text)
        for sig in extra_signals:
            sig_lower = str(sig).lower()
            threat_hits += sum(1 for kw in _THREAT_KEYWORDS if kw in sig_lower)

        # Count safety indicators
        safety_hits = sum(1 for kw in _SAFETY_KEYWORDS if kw in text)
        for sig in extra_signals:
            sig_lower = str(sig).lower()
            safety_hits += sum(1 for kw in _SAFETY_KEYWORDS if kw in sig_lower)

        # Count opportunity indicators
        opportunity_hits = sum(1 for kw in _OPPORTUNITY_KEYWORDS if kw in text)
        for sig in extra_signals:
            sig_lower = str(sig).lower()
            opportunity_hits += sum(1 for kw in _OPPORTUNITY_KEYWORDS if kw in sig_lower)

        # Compute scores (sigmoid-like saturation)
        threat_score = min(1.0, threat_hits / 3.0)
        safety_score = min(1.0, safety_hits / 3.0)
        opportunity_score = min(1.0, opportunity_hits / 3.0)

        # Composite gut safety: safety and opportunity push up, threat pushes down
        raw_safety = safety_score * 0.5 + opportunity_score * 0.2 - threat_score * 0.8
        predicted_safety = max(0.0, min(1.0, 0.5 + raw_safety * 0.5))

        # Confidence is higher when there are clear signals
        total_hits = threat_hits + safety_hits + opportunity_hits
        gut_confidence = min(1.0, total_hits / 4.0)

        # Identify which patterns triggered
        triggering_patterns = []
        if threat_hits > 0:
            triggering_patterns.append("threat_detected")
        if safety_hits > 0:
            triggering_patterns.append("safety_detected")
        if opportunity_hits > 0:
            triggering_patterns.append("opportunity_detected")

        # Energy cost: very low for gut-level, slightly higher if ambiguous
        energy_cost = 0.1 + 0.05 * (1.0 - gut_confidence)

        self._history.append({
            "safety": predicted_safety,
            "confidence": gut_confidence,
            "timestamp": time.time(),
        })

        return GutCheckResult(
            predicted_safety=predicted_safety,
            gut_confidence=gut_confidence,
            triggering_patterns=triggering_patterns,
            intuition_type="affective",
            energy_cost=energy_cost,
            threat_score=threat_score,
            opportunity_score=opportunity_score,
        )

    def validate(self, original_safety: float, actual_outcome: str) -> None:
        """Validate a past gut-check against actual outcome."""
        outcome_lower = actual_outcome.lower()
        was_safe = any(kw in outcome_lower for kw in _SAFETY_KEYWORDS)
        was_correct = (original_safety > 0.5 and was_safe) or (original_safety <= 0.5 and not was_safe)
        self._accuracy.append(was_correct)
        # Keep last 200 validations
        if len(self._accuracy) > 200:
            self._accuracy = self._accuracy[-200:]

    def get_accuracy(self) -> float:
        """Running accuracy of gut-check predictions."""
        if not self._accuracy:
            return 0.5
        return sum(1.0 for a in self._accuracy if a) / len(self._accuracy)


# ===================================================================
# SECTION 6 — CommonSenseRealityFilter
# ===================================================================

class CommonSenseRealityFilter:
    """Layer 2: Reality-checks subconscious pattern matches.

    ATC mapping: Rejects metacognitive rationalizations that don't match
    practical reality. The rejection loop causes ATP depletion and
    metabolic exhaustion (Theorem 3). When the common sense filter
    flags something, it signals to Layer 4's self-understanding that
    the current mental model may be disconnected from reality.

    Rewritten from CommonSenseAgent CSM framework. Knowledge base
    initialized with realistic rules. No emoji, no CLI, no threading.
    """

    def __init__(self) -> None:
        self._rules = list(_COMMON_SENSE_RULES)
        self._anomaly_history: deque = deque(maxlen=100)
        self._rejection_accumulator: float = 0.0

    def check(self, stimulus: str, context: Optional[Dict[str, Any]] = None) -> RealityCheckResult:
        """Reality-check a statement or prediction.

        Checks for:
        - Logical contradictions (both/never, before/after)
        - Temporal impossibilities (causality violations)
        - Extreme absolutist claims (always, never, everyone, nobody)
        - Mismatches against stored common-sense rules

        Returns pass/fail, deviation score, and warnings.
        """
        text = stimulus.lower()
        issues: List[str] = []
        domain_violations: List[str] = []
        confidence = 0.85  # Start optimistic, deduct for issues

        # Check logical contradictions
        contradiction_pairs = [
            ("both", "neither"), ("always", "never"),
            ("everything", "nothing"), ("all", "none"),
        ]
        for a, b in contradiction_pairs:
            if a in text and b in text:
                issues.append(f"logical_contradiction:{a}_and_{b}")
                confidence -= 0.3

        # Check temporal impossibilities
        temporal_violations = [
            "before it happened", "before its cause", "effect before cause",
            "caused its own", "after the end", "effect preceded cause",
            "retroactive causation", "result before cause", "consequence before",
        ]
        for viol in temporal_violations:
            if viol in text:
                issues.append("temporal_impossibility")
                confidence -= 0.4
                domain_violations.append("temporal")

        # Check extreme absolutist language
        absolutist = ["always", "never", "everyone", "nobody", "impossible",
                      "absolutely certain", "guaranteed", "without exception"]
        for word in absolutist:
            if word in text:
                issues.append(f"absolutist_claim:{word}")
                confidence -= 0.1

        # Check physical impossibilities
        physical_violations = [
            "defies gravity", "impossible physics", "perpetual motion",
            "faster than light", "create energy from nothing",
        ]
        for viol in physical_violations:
            if viol in text:
                issues.append("physical_impossibility")
                confidence -= 0.3
                domain_violations.append("physical")

        # Check against stored common-sense rules
        for rule in self._rules:
            condition = rule["condition"].lower()
            if condition in text:
                # This is a recognized situation; check if response is plausible
                pass  # The existence of a matching rule INCREASES confidence

        # Check context for additional signals
        if context:
            for warning in context.get("warnings", []):
                issues.append(f"context_warning:{warning}")
                confidence -= 0.1

        confidence = max(0.0, min(1.0, confidence))

        # Determine warning level
        if confidence > 0.75:
            warning_level = "none"
        elif confidence > 0.55:
            warning_level = "caution"
        elif confidence > 0.35:
            warning_level = "warning"
        else:
            warning_level = "alert"

        passes = confidence > 0.5

        # Compute rejection cost (ATC: rejection loop causes ATP depletion)
        rejection_cost = 0.0
        if not passes:
            # Each issue costs energy; the rejection loop is the metabolic drain
            rejection_cost = len(issues) * 0.05
            self._rejection_accumulator += rejection_cost
            # Decay accumulator slowly
            self._rejection_accumulator *= 0.98
        else:
            # Passing reduces accumulated rejection stress
            self._rejection_accumulator *= 0.9

        if warning_level in ("warning", "alert"):
            self._anomaly_history.append({
                "stimulus": stimulus[:100],
                "issues": issues,
                "timestamp": time.time(),
            })

        if issues:
            logger.debug(
                "Common sense check: %s (confidence=%.2f, issues=%s)",
                warning_level, confidence, issues,
            )

        return RealityCheckResult(
            passes_reality_check=passes,
            deviation_score=1.0 - confidence,
            warnings=issues,
            warning_level=warning_level,
            domain_violations=domain_violations,
            rejection_cost=rejection_cost + self._rejection_accumulator * 0.1,
        )

    def discover_pattern(self, observation: Dict[str, Any]) -> bool:
        """Learn a new common-sense pattern from repeated observation."""
        pattern = observation.get("pattern", "unknown")
        domain = observation.get("domain", "abstract")
        new_rule = {
            "domain": domain,
            "condition": observation.get("condition", "unknown"),
            "pattern": pattern,
            "response": observation.get("response", "observe more"),
            "confidence": observation.get("confidence", "0.60"),
        }
        # Check if we already have this pattern
        for rule in self._rules:
            if rule["pattern"] == pattern and rule["domain"] == domain:
                return False
        self._rules.append(new_rule)
        logger.debug("Discovered new common-sense pattern: %s:%s", domain, pattern)
        return True

    def get_rejection_accumulator(self) -> float:
        """Return the accumulated rejection stress (ATC: feeds metabolic exhaustion)."""
        return self._rejection_accumulator


# ===================================================================
# SECTION 7 — AnalyticalEngine
# ===================================================================

class AnalyticalEngine:
    """Layer 4 support: Multi-scale analysis for metacognitive processing.

    ATC mapping: Breaks down situations at multiple scales (Marr's
    tri-level: computational, algorithmic, physical). The analysis_depth
    output feeds metacognitive_depth_mod in the MetacognitiveSubstrate.
    Emergent insights can trigger the irrational spark if they reveal
    a prediction collapse that the subconscious missed.

    Rewritten from AnalysisAgent. No CLI, no emoji, no threading.
    """

    def __init__(self) -> None:
        self._history: deque = deque(maxlen=200)
        self._preferred_depth: float = 0.7

    def analyze(self, stimulus: str, context: Optional[Dict[str, Any]] = None) -> AnalysisEngineResult:
        """Perform multi-scale analysis on the stimulus.

        Marr's tri-level applied to any cognitive problem:
        1. Computational: What is the problem? What is the goal?
        2. Algorithmic: How is it solved? What strategy?
        3. Physical: What implements it? What substrate?

        Returns analysis depth, confidence, and emergent insights.
        """
        text = stimulus.lower()
        words = text.split()
        word_count = len(words)

        # Estimate complexity
        unique_words = len(set(words))
        lexical_diversity = unique_words / max(1, word_count)
        question_markers = sum(1 for w in words if w in ("what", "how", "why", "when", "where", "who", "which"))
        negation_markers = sum(1 for w in words if w in ("not", "no", "never", "none", "without"))
        conditional_markers = sum(1 for w in words if w in ("if", "then", "else", "unless", "whether"))

        complexity = min(1.0, (
            lexical_diversity * 0.3 +
            min(question_markers, 3) / 3.0 * 0.3 +
            min(negation_markers, 2) / 2.0 * 0.2 +
            min(conditional_markers, 2) / 2.0 * 0.2
        ))

        # Classify problem type
        problem_type = self._classify_problem(text)

        # Determine analysis depth based on complexity and preference
        analysis_depth = min(1.0, complexity * 0.7 + self._preferred_depth * 0.3)

        # Reasoning confidence decreases with complexity
        reasoning_confidence = max(0.2, 0.9 - complexity * 0.5)

        # Multi-scale analysis
        scales_analyzed = []

        # Computational level: what is the problem?
        comp_confidence = min(0.95, 0.7 + question_markers * 0.1)
        scales_analyzed.append("computational")

        # Algorithmic level: how to solve it
        algo_confidence = max(0.3, 0.7 - complexity * 0.3)
        scales_analyzed.append("algorithmic")

        # Physical level: what implements it (usually least certain)
        phys_confidence = max(0.2, 0.5 - complexity * 0.2)
        scales_analyzed.append("physical")

        # Integration score
        integration_score = (comp_confidence + algo_confidence + phys_confidence) / 3.0

        # Discover emergent insights
        emergent_insights = []
        if complexity > 0.7 and reasoning_confidence < 0.5:
            emergent_insights.append("high_complexity_low_confidence: situation may require non-standard approach")
        if question_markers > 2:
            emergent_insights.append("multi_question: nested inquiry detected, layered analysis recommended")
        if negation_markers > 1 and conditional_markers > 0:
            emergent_insights.append("conditional_negation: counterfactual reasoning may be needed")
        if lexical_diversity > 0.8 and word_count > 10:
            emergent_insights.append("high_diversity_long_input: rich semantic content, deep processing warranted")
        if context and context.get("prediction_failed"):
            emergent_insights.append("prediction_mismatch: analytical re-evaluation triggered by prediction failure")

        # Check if analysis reveals something the subconscious missed
        if context:
            gut_safety = context.get("gut_safety", 0.5)
            if gut_safety > 0.7 and complexity > 0.6:
                emergent_insights.append(
                    "safety_complexity_mismatch: gut says safe but situation is complex, verify"
                )

        self._history.append({
            "stimulus": stimulus[:80],
            "complexity": complexity,
            "depth": analysis_depth,
            "insights": len(emergent_insights),
            "timestamp": time.time(),
        })

        return AnalysisEngineResult(
            analysis_depth=analysis_depth,
            reasoning_confidence=reasoning_confidence,
            emergent_insights=emergent_insights,
            problem_type=problem_type,
            complexity_estimate=complexity,
            integration_score=integration_score,
            scales_analyzed=scales_analyzed,
        )

    def _classify_problem(self, text: str) -> str:
        """Classify the type of cognitive problem."""
        classification_rules = [
            (["choose", "select", "decide", "pick", "prefer"], "decision"),
            (["predict", "forecast", "estimate", "expect", "guess"], "prediction"),
            (["optim", "maxim", "minim", "improve", "best"], "optimization"),
            (["classif", "categoriz", "identify", "recognize", "detect"], "classification"),
            (["understand", "explain", "interpret", "meaning", "why"], "interpretation"),
            (["create", "generat", "design", "invent", "compose"], "creation"),
            (["analyz", "examin", "investigat", "study", "review"], "analysis"),
            (["compar", "contrast", "differ", "versus", "vs"], "comparison"),
        ]
        for keywords, ptype in classification_rules:
            if any(kw in text for kw in keywords):
                return ptype
        return "unknown"

    def set_depth_preference(self, depth: float) -> None:
        """Adjust preferred analysis depth (0=shallow, 1=deep)."""
        self._preferred_depth = max(0.0, min(1.0, depth))


# ===================================================================
# SECTION 8 — CognitiveLayer2Orchestrator
# ===================================================================

class CognitiveLayer2Orchestrator:
    """Orchestrates all Layer 2 cognitive components in parallel (sequential
    in code, conceptually parallel as in the ATC subconscious matrix).

    This is the entry point that the middleware calls.

    Usage in middleware::

        cognitive = CognitiveLayer2Orchestrator()
        layer2_result = cognitive.process(stimulus_text, context)
        # layer2_result.prediction_error -> feeds DissolutionEngine (friction)
        # layer2_result.valence/arousal -> feeds phi_neuro (Theorem 2)
        # layer2_result.gut_safety -> feeds TRN predictive gating
        # layer2_result.passes_reality_check -> feeds self-understanding (Layer 4)
        # layer2_result.thermodynamic_cost -> feeds allostatic load (Theorem 3)

    ATC mapping: This orchestrator IS the 'subconscious Layer 2 parallel
    processing matrix' from the Perfect Breakfast scenario. Each subsystem
    runs independently and their outputs are merged into a single Layer2Result
    that the rest of the ATC pipeline consumes.
    """

    def __init__(self, max_memory_entries: int = 5000) -> None:
        self.pattern_matcher = SubconsciousPatternMatch(max_memory_entries=max_memory_entries)
        self.emotional_bridge = EmotionalBridge()
        self.gut_check = IntuitiveGutCheck()
        self.reality_filter = CommonSenseRealityFilter()
        self.analytical_engine = AnalyticalEngine()
        self._process_count: int = 0
        self._total_cost: float = 0.0
        logger.debug("CognitiveLayer2Orchestrator initialized with 5 subsystems")

    def process(
        self,
        stimulus: str,
        context: Optional[Dict[str, Any]] = None,
    ) -> Layer2Result:
        """Run all Layer 2 cognitive subsystems and return unified result.

        Subsystems run sequentially (Python is sync) but are logically
        independent -- no subsystem reads another's output within the
        same cycle. This mirrors biological parallel processing where
        the thalamus gates simultaneous subconscious streams.
        """
        ctx = context or {}
        start = time.time()

        # 1. Subconscious pattern matching (memory + intuition)
        pattern_result = self.pattern_matcher.match(stimulus, ctx)

        # 2. Emotional bridge (EI -> BELBIC -> phi_neuro)
        emotional_result = self.emotional_bridge.process(stimulus, ctx)

        # 3. Intuitive gut-check (System 1 -> TRN gating)
        gut_result = self.gut_check.check(stimulus, ctx)

        # 4. Common sense reality filter (reality check -> self-understanding)
        reality_result = self.reality_filter.check(stimulus, ctx)

        # 5. Analytical engine (metacognitive support -> Layer 4)
        analysis_ctx = {
            **ctx,
            "gut_safety": gut_result.predicted_safety,
            "prediction_failed": pattern_result.is_novel,
        }
        analysis_result = self.analytical_engine.analyze(stimulus, analysis_ctx)

        # Compute prediction_error from pattern match and reality check
        # If pattern matching is confident but reality check fails,
        # we have a high prediction error (prediction collapse)
        if pattern_result.prediction_confidence > 0.5 and not reality_result.passes_reality_check:
            prediction_error = pattern_result.prediction_confidence * (1.0 - reality_result.passes_reality_check)
        elif pattern_result.is_novel:
            prediction_error = 0.5  # Novel = moderate surprise
        else:
            prediction_error = max(0.0, 1.0 - pattern_result.prediction_confidence) * 0.5

        prediction_error = max(0.0, min(1.0, prediction_error))

        # Compute thermodynamic cost (ATC: ATP consumption)
        # Each subsystem has an energy cost; novelty and high arousal increase it
        base_cost = 0.02  # Baseline ATP cost
        pattern_cost = 0.01 * len(pattern_result.matched_memory_refs)
        emotion_cost = 0.015 * emotional_result.arousal
        gut_cost = gut_result.energy_cost
        reality_cost = reality_result.rejection_cost
        analysis_cost = 0.02 * analysis_result.analysis_depth
        novelty_surcharge = 0.03 * pattern_result.novelty_score
        thermodynamic_cost = (
            base_cost + pattern_cost + emotion_cost + gut_cost
            + reality_cost + analysis_cost + novelty_surcharge
        )
        thermodynamic_cost = min(0.5, thermodynamic_cost)  # Cap at 0.5

        # Accumulate tracking
        self._process_count += 1
        self._total_cost += thermodynamic_cost

        elapsed_ms = (time.time() - start) * 1000

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug(
                "Layer2 process: pred_conf=%.2f valence=%.2f arousal=%.2f "
                "gut_safety=%.2f reality=%s novel=%s cost=%.4f time=%.1fms",
                pattern_result.prediction_confidence,
                emotional_result.valence,
                emotional_result.arousal,
                gut_result.predicted_safety,
                reality_result.passes_reality_check,
                pattern_result.is_novel,
                thermodynamic_cost,
                elapsed_ms,
            )

        return Layer2Result(
            prediction_confidence=pattern_result.prediction_confidence,
            prediction_label=pattern_result.prediction_label,
            valence=emotional_result.valence,
            arousal=emotional_result.arousal,
            emotion_label=emotional_result.emotion_label,
            gut_safety=gut_result.predicted_safety,
            intuition_confidence=gut_result.gut_confidence,
            passes_reality_check=reality_result.passes_reality_check,
            common_sense_warnings=reality_result.warnings,
            is_novel=pattern_result.is_novel,
            matched_patterns=pattern_result.matched_patterns,
            thermodynamic_cost=thermodynamic_cost,
            prediction_error=prediction_error,
            pattern_match=pattern_result,
            emotional_bridge=emotional_result,
            gut_check=gut_result,
            reality_check=reality_result,
            analysis=analysis_result,
        )

    def store_memory(
        self,
        content: str,
        tags: Optional[List[str]] = None,
        importance: float = 0.5,
        valence: float = 0.0,
        arousal: float = 0.0,
    ) -> str:
        """Store a memory in the pattern matcher for future matching."""
        return self.pattern_matcher.store(content, tags, importance, valence, arousal)

    def get_metrics(self) -> Dict[str, Any]:
        """Return diagnostic metrics for all subsystems."""
        return {
            "total_processes": self._process_count,
            "average_thermodynamic_cost": self._total_cost / max(1, self._process_count),
            "memory_count": self.pattern_matcher.get_memory_count(),
            "emotional_complexity": self.emotional_bridge.get_complexity(),
            "gut_check_accuracy": self.gut_check.get_accuracy(),
            "rejection_accumulator": self.reality_filter.get_rejection_accumulator(),
        }