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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
"""
symbolic_engine.py

Core implementation of the Symbolic Engine for the glyphs framework.
This engine powers the diagnostic shells and provides the foundation
for tracing attention attribution, symbolic residue, and collapse patterns.
"""

import logging
import time
import numpy as np
from typing import Dict, List, Optional, Tuple, Union, Any
from dataclasses import dataclass, field
from enum import Enum
import json

from ..models.adapter import ModelAdapter
from ..utils.attribution_utils import AttributionTracer
from ..utils.visualization_utils import VisualizationEngine

# Configure symbolic-aware logging
logger = logging.getLogger("glyphs.symbolic_engine")
logger.setLevel(logging.INFO)


class SymbolicResidueType(Enum):
    """Types of symbolic residue that can be detected and analyzed."""
    MEMORY_DECAY = "memory_decay"           # Memory degradation over sequence
    ATTRIBUTION_GAP = "attribution_gap"     # Missing attribution between tokens
    ATTENTION_DRIFT = "attention_drift"     # Attention shifts off intended path
    VALUE_CONFLICT = "value_conflict"       # Competing value activations
    RECURSIVE_COLLAPSE = "recursive_collapse" # Collapse in recursive reasoning
    SALIENCE_FADE = "salience_fade"         # Decay in attention salience
    BOUNDARY_HESITATION = "boundary_hesitation" # Hesitation at knowledge boundaries
    NULL_OUTPUT = "null_output"             # Complete failure to generate
    TOKEN_OSCILLATION = "token_oscillation" # Back-and-forth between tokens
    GHOST_ACTIVATION = "ghost_activation"   # Subthreshold activations affecting output


@dataclass
class CollapseSample:
    """Sample of a collapse event in model generation."""
    timestamp: float
    position: int  # Token position where collapse occurred
    collapse_type: SymbolicResidueType
    confidence: float  # Confidence in collapse detection
    context_window: List[str]  # Surrounding tokens
    activation_pattern: Dict[str, float]  # Activation pattern at collapse
    residue: Dict[str, Any]  # Symbolic residue from collapse


@dataclass
class SymbolicTrace:
    """Trace of symbolic operations and residues."""
    trace_id: str
    model_id: str
    timestamp: float
    prompt: str
    output: str
    operations: List[Dict[str, Any]]
    residues: List[Dict[str, Any]]
    collapse_samples: List[CollapseSample] = field(default_factory=list)
    attribution_map: Optional[Dict[str, Any]] = None
    visualization_data: Optional[Dict[str, Any]] = None
    metadata: Dict[str, Any] = field(default_factory=dict)


class SymbolicEngine:
    """
    Core symbolic engine for the glyphs framework.
    
    This engine powers the diagnostic shells and provides the foundation
    for tracing attention attribution, symbolic residue, and collapse patterns.
    It serves as the bridge between model execution and interpretability analysis.
    """
    
    def __init__(
        self,
        config: Optional[Dict[str, Any]] = None,
        tracer: Optional[AttributionTracer] = None,
        visualizer: Optional[VisualizationEngine] = None
    ):
        """
        Initialize the symbolic engine.
        
        Parameters:
        -----------
        config : Optional[Dict[str, Any]]
            Configuration parameters for the engine
        tracer : Optional[AttributionTracer]
            Attribution tracer to use
        visualizer : Optional[VisualizationEngine]
            Visualization engine to use
        """
        self.config = config or {}
        self.tracer = tracer
        self.visualizer = visualizer
        
        # Configure engine parameters
        self.residue_sensitivity = self.config.get("residue_sensitivity", 0.7)
        self.collapse_threshold = self.config.get("collapse_threshold", 0.8)
        self.attribution_depth = self.config.get("attribution_depth", 5)
        self.trace_history = []
        
        # Initialize glyph mappings
        self._init_glyph_mappings()
        
        logger.info("Symbolic engine initialized")
    
    def _init_glyph_mappings(self):
        """Initialize glyph mappings for residue visualization."""
        # Attribution glyphs
        self.attribution_glyphs = {
            "strong_attribution": "🔍",  # Strong attribution
            "attribution_gap": "🧩",     # Gap in attribution
            "attribution_fork": "🔀",     # Divergent attribution
            "attribution_loop": "🔄",     # Circular attribution
            "attribution_link": "🔗"      # Strong connection
        }
        
        # Cognitive glyphs
        self.cognitive_glyphs = {
            "hesitation": "💭",          # Hesitation in reasoning
            "processing": "🧠",          # Active reasoning process
            "insight": "💡",             # Moment of insight
            "uncertainty": "🌫️",         # Uncertain reasoning
            "projection": "🔮"           # Future state projection
        }
        
        # Recursive glyphs
        self.recursive_glyphs = {
            "recursive_aegis": "🜏",     # Recursive immunity
            "recursive_seed": "∴",       # Recursion initiation
            "recursive_exchange": "⇌",   # Bidirectional recursion
            "recursive_mirror": "🝚",     # Recursive reflection
            "recursive_anchor": "☍"      # Stable recursive reference
        }
        
        # Residue glyphs
        self.residue_glyphs = {
            "residue_energy": "🔥",      # High-energy residue
            "residue_flow": "🌊",        # Flowing residue pattern
            "residue_vortex": "🌀",      # Spiraling residue pattern
            "residue_dormant": "💤",      # Inactive residue pattern
            "residue_discharge": "⚡"     # Sudden residue release
        }
    
    def execute_shell(
        self,
        shell_def: Dict[str, Any],
        model: ModelAdapter,
        prompt: str,
        parameters: Optional[Dict[str, Any]] = None
    ) -> SymbolicTrace:
        """
        Execute a diagnostic shell on a model.
        
        Parameters:
        -----------
        shell_def : Dict[str, Any]
            Shell definition containing operations and parameters
        model : ModelAdapter
            Model adapter for the target model
        prompt : str
            Input prompt for the shell
        parameters : Optional[Dict[str, Any]]
            Additional parameters to override shell defaults
            
        Returns:
        --------
        SymbolicTrace
            Trace of the shell execution
        """
        start_time = time.time()
        shell_id = shell_def.get("id", "unknown")
        shell_type = shell_def.get("type", "unknown")
        
        logger.info(f"Executing shell {shell_id} of type {shell_type}")
        
        # Initialize trace
        trace = SymbolicTrace(
            trace_id=f"trace_{int(start_time)}",
            model_id=model.model_id,
            timestamp=start_time,
            prompt=prompt,
            output="",
            operations=[],
            residues=[],
            metadata={
                "shell_id": shell_id,
                "shell_type": shell_type,
                "parameters": parameters or {}
            }
        )
        
        # Get operations from shell definition
        operations = shell_def.get("operations", [])
        
        # Merge parameters with shell defaults
        params = parameters or {}
        
        # Execute each operation in sequence
        current_prompt = prompt
        for i, op in enumerate(operations):
            op_type = op.get("type", "unknown")
            op_params = {**op.get("parameters", {}), **params}
            
            logger.info(f"Executing operation {i+1}/{len(operations)}: {op_type}")
            
            # Execute operation
            try:
                result = self._execute_operation(
                    op_type=op_type,
                    params=op_params,
                    model=model,
                    prompt=current_prompt,
                    trace=trace
                )
                
                # Record operation in trace
                trace.operations.append({
                    "id": i,
                    "type": op_type,
                    "parameters": op_params,
                    "result": result
                })
                
                # Check for residue
                if "residue" in result:
                    trace.residues.append(result["residue"])
                
                # Check for collapse
                if result.get("collapse_detected", False):
                    collapse_sample = CollapseSample(
                        timestamp=time.time(),
                        position=result.get("collapse_position", -1),
                        collapse_type=SymbolicResidueType(result.get("collapse_type", "null_output")),
                        confidence=result.get("collapse_confidence", 0.0),
                        context_window=result.get("context_window", []),
                        activation_pattern=result.get("activation_pattern", {}),
                        residue=result.get("residue", {})
                    )
                    trace.collapse_samples.append(collapse_sample)
                
                # Update prompt for next operation if specified
                if op.get("update_prompt", False) and "output" in result:
                    current_prompt = result["output"]
                    trace.output = result["output"]
            
            except Exception as e:
                logger.error(f"Error executing operation {op_type}: {e}")
                trace.operations.append({
                    "id": i,
                    "type": op_type,
                    "parameters": op_params,
                    "error": str(e)
                })
                # Continue with next operation
        
        # Run attribution tracing if requested
        if self.tracer and self.config.get("trace_attribution", True):
            logger.info("Tracing attribution")
            try:
                attribution_map = self.tracer.trace(
                    prompt=prompt,
                    output=trace.output,
                    depth=self.attribution_depth
                )
                trace.attribution_map = attribution_map
            except Exception as e:
                logger.error(f"Error tracing attribution: {e}")
        
        # Generate visualization if requested
        if self.visualizer and self.config.get("generate_visualization", True):
            logger.info("Generating visualization")
            try:
                visualization_data = self.visualizer.generate(trace)
                trace.visualization_data = visualization_data
            except Exception as e:
                logger.error(f"Error generating visualization: {e}")
        
        # Record execution time
        execution_time = time.time() - start_time
        trace.metadata["execution_time"] = execution_time
        
        # Add trace to history
        self.trace_history.append(trace)
        
        logger.info(f"Shell execution completed in {execution_time:.2f}s")
        return trace
    
    def _execute_operation(
        self,
        op_type: str,
        params: Dict[str, Any],
        model: ModelAdapter,
        prompt: str,
        trace: SymbolicTrace
    ) -> Dict[str, Any]:
        """
        Execute a single shell operation.
        
        Parameters:
        -----------
        op_type : str
            Type of operation to execute
        params : Dict[str, Any]
            Operation parameters
        model : ModelAdapter
            Model adapter for the target model
        prompt : str
            Input prompt for the operation
        trace : SymbolicTrace
            Current trace object
            
        Returns:
        --------
        Dict[str, Any]
            Operation result
        """
        # Execute based on operation type
        if op_type == "model.generate":
            # Direct model generation
            return self._execute_generate(model, prompt, params)
        
        elif op_type == "reflect.trace":
            # Reflection tracing
            return self._execute_reflect_trace(model, prompt, params)
        
        elif op_type == "reflect.attribution":
            # Attribution reflection
            return self._execute_reflect_attribution(model, prompt, params)
        
        elif op_type == "collapse.detect":
            # Collapse detection
            return self._execute_collapse_detect(model, prompt, params)
        
        elif op_type == "collapse.prevent":
            # Collapse prevention
            return self._execute_collapse_prevent(model, prompt, params)
        
        elif op_type == "ghostcircuit.identify":
            # Ghost circuit identification
            return self._execute_ghostcircuit_identify(model, prompt, params)
        
        elif op_type == "fork.attribution":
            # Fork attribution
            return self._execute_fork_attribution(model, prompt, params)
        
        else:
            raise ValueError(f"Unknown operation type: {op_type}")
    
    def _execute_generate(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute model.generate operation."""
        temperature = params.get("temperature", 0.7)
        max_tokens = params.get("max_tokens", 800)
        
        # Add prompt_prefix if provided
        if "prompt_prefix" in params:
            prompt = f"{params['prompt_prefix']} {prompt}"
        
        # Add prompt_suffix if provided
        if "prompt_suffix" in params:
            prompt = f"{prompt} {params['prompt_suffix']}"
        
        # Generate output
        output = model.generate(
            prompt=prompt,
            max_tokens=max_tokens,
            temperature=temperature
        )
        
        # Analyze generation latency
        generation_stats = model.get_last_generation_stats()
        
        return {
            "output": output,
            "prompt": prompt,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "generation_stats": generation_stats
        }
    
    def _execute_reflect_trace(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.trace operation."""
        target = params.get("target", "reasoning")
        depth = params.get("depth", 3)
        detailed = params.get("detailed", True)
        
        # Convert "complete" depth to numeric value
        if depth == "complete":
            depth = 10  # Use a high value for "complete"
        
        # Construct reflection prompt based on target
        if target == "reasoning":
            reflection_prompt = f"""
            Analyze the reasoning process in the following text. Trace the logical steps, 
            identify key inferences, and map the reasoning structure to a depth of {depth}.
            If detailed analysis is requested, include token-level attribution.
            
            Text to analyze: {prompt}
            """
        elif target == "attribution":
            reflection_prompt = f"""
            Analyze the attribution patterns in the following text. Trace how information
            flows from inputs to outputs, identify attribution sources, and map the 
            attribution structure to a depth of {depth}.
            
            Text to analyze: {prompt}
            """
        elif target == "attention":
            reflection_prompt = f"""
            Analyze the attention patterns in the following text. Trace how attention
            is distributed across tokens, identify attention hotspots, and map the
            attention structure to a depth of {depth}.
            
            Text to analyze: {prompt}
            """
        elif target == "memory":
            reflection_prompt = f"""
            Analyze the memory utilization in the following text. Trace how information
            is retained and recalled, identify memory decay patterns, and map the
            memory structure to a depth of {depth}.
            
            Text to analyze: {prompt}
            """
        elif target == "uncertainty":
            reflection_prompt = f"""
            Analyze the uncertainty patterns in the following text. Trace how uncertainty
            is expressed and managed, identify uncertainty triggers, and map the
            uncertainty structure to a depth of {depth}.
            
            Text to analyze: {prompt}
            """
        else:
            raise ValueError(f"Unknown reflection target: {target}")
        
        # Execute reflection
        reflection_output = model.generate(
            prompt=reflection_prompt,
            max_tokens=1000,
            temperature=0.2  # Lower temperature for more deterministic reflection
        )
        
        # Analyze for collapse patterns
        collapse_detected = self._detect_collapse_in_reflection(reflection_output)
        
        # Extract trace map
        trace_map = self._extract_trace_map(reflection_output, target, depth)
        
        return {
            "target": target,
            "depth": depth,
            "detailed": detailed,
            "reflection_output": reflection_output,
            "trace_map": trace_map,
            "collapse_detected": collapse_detected.get("detected", False),
            "collapse_type": collapse_detected.get("type", None),
            "collapse_confidence": collapse_detected.get("confidence", 0.0)
        }
    
    def _execute_reflect_attribution(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.attribution operation."""
        sources = params.get("sources", "all")
        confidence = params.get("confidence", True)
        
        # Use attribution tracer if available
        if self.tracer:
            # Generate output first if not already done
            if not hasattr(model, "last_output") or not model.last_output:
                output = model.generate(prompt=prompt, max_tokens=800)
            else:
                output = model.last_output
                
            # Trace attribution
            attribution_map = self.tracer.trace(
                prompt=prompt,
                output=output,
                include_confidence=confidence
            )
            
            # Filter sources if needed
            if sources != "all":
                attribution_map = self._filter_attribution_sources(attribution_map, sources)
            
            return {
                "sources": sources,
                "confidence": confidence,
                "attribution_map": attribution_map,
                "output": output
            }
        else:
            # Fallback: use model to analyze attribution
            attribution_prompt = f"""
            Analyze the attribution patterns in the following text. Identify how information
            flows from inputs to outputs, and trace the attribution sources.
            
            {sources != "all" and f"Focus on {sources} sources only." or ""}
            {confidence and "Include confidence scores for each attribution." or ""}
            
            Text to analyze: {prompt}
            """
            
            attribution_output = model.generate(
                prompt=attribution_prompt,
                max_tokens=1000,
                temperature=0.2
            )
            
            # Extract attribution map
            attribution_map = self._extract_attribution_map(attribution_output, sources, confidence)
            
            return {
                "sources": sources,
                "confidence": confidence,
                "attribution_output": attribution_output,
                "attribution_map": attribution_map
            }
    
    def _execute_collapse_detect(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute collapse.detect operation."""
        threshold = params.get("threshold", 0.7)
        alert = params.get("alert", True)
        
        # Generate output with collapse detection
        output = model.generate(
            prompt=prompt,
            max_tokens=800,
            temperature=0.7
        )
        
        # Analyze output for collapse patterns
        collapse_analysis = self._analyze_collapse_patterns(
            prompt=prompt,
            output=output,
            threshold=threshold
        )
        
        # Extract residue if collapse detected
        residue = None
        if collapse_analysis["detected"]:
            residue = self._extract_symbolic_residue(
                prompt=prompt,
                output=output,
                collapse_type=collapse_analysis["type"]
            )
        
        return {
            "threshold": threshold,
            "alert": alert,
            "output": output,
            "collapse_detected": collapse_analysis["detected"],
            "collapse_type": collapse_analysis["type"],
            "collapse_confidence": collapse_analysis["confidence"],
            "collapse_position": collapse_analysis["position"],
            "residue": residue
        }
    
    def _execute_collapse_prevent(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute collapse.prevent operation."""
        trigger = params.get("trigger", "recursive_depth")
        threshold = params.get("threshold", 5)
        
        # Create prevention prompt based on trigger
        if trigger == "recursive_depth":
            prevention_prompt = f"""
            Maintain recursive depth control. Avoid going deeper than {threshold} levels
            of recursion. If you detect deeper recursion, stabilize and return to a
            shallower level.
            
            {prompt}
            """
        elif trigger == "confidence_drop":
            prevention_prompt = f"""
            Maintain confidence stability. If confidence drops below {threshold/10} at any
            point, stabilize and rebuild confidence before continuing.
            
            {prompt}
            """
        elif trigger == "contradiction":
            prevention_prompt = f"""
            Maintain logical consistency. If you detect more than {threshold} potential
            contradictions, stabilize and resolve them before continuing.
            
            {prompt}
            """
        elif trigger == "oscillation":
            prevention_prompt = f"""
            Maintain directional stability. If you detect more than {threshold} oscillations
            between competing perspectives, stabilize and synthesize them before continuing.
            
            {prompt}
            """
        else:
            raise ValueError(f"Unknown collapse trigger: {trigger}")
        
        # Generate output with collapse prevention
        output = model.generate(
            prompt=prevention_prompt,
            max_tokens=1000,
            temperature=0.5
        )
        
        # Analyze prevention effectiveness
        prevention_analysis = self._analyze_prevention_effectiveness(
            output=output,
            trigger=trigger,
            threshold=threshold
        )
        
        return {
            "trigger": trigger,
            "threshold": threshold,
            "output": output,
            "prevention_effectiveness": prevention_analysis["effectiveness"],
            "prevention_measures": prevention_analysis["measures"],
            "residual_collapse_risk": prevention_analysis["residual_risk"]
        }
    
    def _execute_ghostcircuit_identify(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute ghostcircuit.identify operation."""
        sensitivity = params.get("sensitivity", 0.7)
        threshold = params.get("threshold", 0.2)
        trace_type = params.get("trace_type", "full")
        
        # Generate output
        output = model.generate(
            prompt=prompt,
            max_tokens=800,
            temperature=0.7
        )
        
        # Create ghost circuit detection prompt
        ghost_detection_prompt = f"""
        Analyze the following text for ghost activations - subthreshold activations
        that influence the output without being explicitly present.
        
        Sensitivity: {sensitivity} (higher means detect more subtle patterns)
        Threshold: {threshold} (lower means include weaker activations)
        Trace type: {trace_type} (determines what patterns to look for)
        
        Text to analyze: {output}
        """
        
        # Generate ghost circuit analysis
        ghost_analysis = model.generate(
            prompt=ghost_detection_prompt,
            max_tokens=800,
            temperature=0.3
        )
        
        # Extract ghost patterns
        ghost_patterns = self._extract_ghost_patterns(
            analysis=ghost_analysis,
            sensitivity=sensitivity,
            threshold=threshold,
            trace_type=trace_type
        )
        
        return {
            "sensitivity": sensitivity,
            "threshold": threshold,
            "trace_type": trace_type,
            "output": output,
            "ghost_analysis": ghost_analysis,
            "ghost_patterns": ghost_patterns
        }
    
    def _execute_fork_attribution(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute fork.attribution operation."""
        sources = params.get("sources", "all")
        visualize = params.get("visualize", False)
        
        # Use attribution tracer if available
        if self.tracer:
            # Generate output first if not already done
            if not hasattr(model, "last_output") or not model.last_output:
                output = model.generate(prompt=prompt, max_tokens=800)
            else:
                output = model.last_output
                
            # Trace attribution with forking
            attribution_forks = self.tracer.trace_with_forks(
                prompt=prompt,
                output=output,
                fork_factor=3  # Create 3 alternative attribution paths
            )
            
            # Visualize if requested
            visualization = None
            if visualize and self.visualizer:
                visualization = self.visualizer.visualize_attribution_forks(attribution_forks)
            
            return {
                "sources": sources,
                "attribution_forks": attribution_forks,
                "output": output,
                "visualization": visualization if visualize else None
            }
        else:
            # Fallback: use model to analyze attribution forks
            fork_prompt = f"""
            Analyze the following text and create three alternative attribution pathways.
            For each pathway, identify how different sources might have influenced the output.
            
            Text to analyze: {prompt}
            """
            
            fork_output = model.generate(
                prompt=fork_prompt,
                max_tokens=1200,
                temperature=0.7
            )
            
            # Extract attribution forks
            attribution_forks = self._extract_attribution_forks(fork_output, sources)
            
            return {
                "sources": sources,
                "fork_output": fork_output,
                "attribution_forks": attribution_forks,
                "visualization": None  # No visualization in fallback mode
            }
    
    # Helper methods for operation execution
    
    def _detect_collapse_in_reflection(self, reflection_output: str) -> Dict[str, Any]:
        """Detect collapse patterns in reflection output."""
        # Look for signs of reflection collapse
        collapse_indicators = {
            "recursive_collapse": [
                "infinite recursion", "recursive loop", "depth limit",
                "recursion limit", "too deep", "recursive overflow"
            ],
            "attribution_gap": [
                "attribution gap", "missing connection", "unclear attribution",
                "attribution loss", "untraceable connection"
            ],
            "boundary_hesitation": [
                "boundary uncertainty", "epistemic edge", "knowledge boundary",
                "uncertain territory", "confidence boundary"
            ],
            "value_conflict": [
                "value conflict", "competing values", "ethical tension",
                "moral dilemma", "value contradiction"
            ]
        }
        
        # Check for each collapse type
        for collapse_type, indicators in collapse_indicators.items():
            indicator_count = sum(1 for indicator in indicators if indicator.lower() in reflection_output.lower())
            if indicator_count >= 2:  # At least 2 indicators to confirm
                confidence = min(0.5 + (indicator_count / 10), 0.95)  # Scale confidence
                return {
                    "detected": True,
                    "type": collapse_type,
                    "confidence": confidence
                }
        
        # No collapse detected
        return {
            "detected": False,
            "type": None,
            "confidence": 0.0
        }
    
    def _extract_trace_map(
        self,
        reflection_output: str,
        target: str,
        depth: int
    ) -> Dict[str, Any]:
        """Extract trace map from reflection output."""
        # Simple extraction logic - would be more sophisticated in a real implementation
        sections = reflection_output.split("\n\n")
        
        trace_map = {
            "target": target,
            "depth": depth,
            "nodes": [],
            "edges": []
        }
        
        # Extract nodes and edges from reflection
        node_id = 0
        for section in sections:
            if len(section.strip()) < 10:  # Skip very short sections
                continue
                
            # Create node for this section
            trace_map["nodes"].append({
                "id": node_id,
                "text": section.strip(),
                "type": target,
                "depth": min(node_id // 2, depth)  # Simple depth assignment
            })
            
            # Create edge to previous node if not first
            if node_id > 0:
                trace_map["edges"].append({
                    "source": node_id - 1,
                    "target": node_id,
                    "type": "sequential"
                })
            
            node_id += 1
        
        return trace_map
    
    def _filter_attribution_sources(
        self,
        attribution_map: Dict[str, Any],
        sources: str
    ) -> Dict[str, Any]:
        """Filter attribution map to include only specified sources."""
        filtered_map = {
            "tokens": attribution_map["tokens"],
            "attributions": []
        }
        
        # Filter attributions based on sources
        if sources == "primary":
            # Keep only attributions with high confidence
            filtered_map["attributions"] = [
                attr for attr in attribution_map["attributions"]
                if attr.get("confidence", 0) > 0.7
            ]
        elif sources == "secondary":
            # Keep only attributions with medium confidence
            filtered_map["attributions"] = [
                attr for attr in attribution_map["attributions"]
                if 0.3 <= attr.get("confidence", 0) <= 0.7
            ]
        elif sources == "contested":
            # Keep only attributions with competing sources
            contested = []
            for token_idx, token in enumerate(attribution_map["tokens"]):
                # Find all attributions for this token
                token_attrs = [
                    attr for attr in attribution_map["attributions"]
                    if attr["target"] == token_idx
                ]
                
                # Check if there are competing attributions
                if len(token_attrs) > 1:
                    top_conf = max(attr.get("confidence", 0) for attr in token_attrs)
                    runner_up = sorted([attr.get("confidence", 0) for attr in token_attrs], reverse=True)[1]
                    if top_conf - runner_up < 0.3:  # Close competition
                        contested.extend(token_attrs)
            
            filtered_map["attributions"] = contested
        
        return filtered_map
    
    def _extract_attribution_map(
        self,
        attribution_output: str,
        sources: str,
        confidence: bool
    ) -> Dict[str, Any]:
        """Extract attribution map from model output."""
        # Simple extraction logic - would be more sophisticated in a real implementation
        attribution_map = {
            "tokens": [],
            "attributions": []
        }
        
        # Extract tokens and attributions
        lines = attribution_output.split("\n")
        token_id = 0
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
                
            # Check if line contains attribution information
            if ":" in line and "->" in line:
                parts = line.split("->")
                if len(parts) == 2:
                    source_info = parts[0].strip()
                    target_info = parts[1].strip()
                    
                    # Extract source token
                    source_token = source_info.split(":")[0].strip()
                    
                    # Extract target token
                    target_token = target_info.split(":")[0
"""
symbolic_engine.py

Core implementation of the Symbolic Engine for the glyphs framework.
This engine powers the diagnostic shells and provides the foundation
for tracing attention attribution, symbolic residue, and collapse patterns.
"""

import logging
import time
import numpy as np
from typing import Dict, List, Optional, Tuple, Union, Any
from dataclasses import dataclass, field
from enum import Enum
import json
import hashlib
from pathlib import Path

from ..models.adapter import ModelAdapter
from ..utils.attribution_utils import AttributionTracer
from ..utils.visualization_utils import VisualizationEngine
from ..residue.patterns import ResiduePattern, ResidueRegistry

# Configure symbolic-aware logging
logger = logging.getLogger("glyphs.symbolic_engine")
logger.setLevel(logging.INFO)


class SymbolicResidueType(Enum):
    """Types of symbolic residue that can be detected and analyzed."""
    MEMORY_DECAY = "memory_decay"           # Memory degradation over sequence
    ATTRIBUTION_GAP = "attribution_gap"     # Missing attribution between tokens
    ATTENTION_DRIFT = "attention_drift"     # Attention shifts off intended path
    VALUE_CONFLICT = "value_conflict"       # Competing value activations
    RECURSIVE_COLLAPSE = "recursive_collapse" # Collapse in recursive reasoning
    SALIENCE_FADE = "salience_fade"         # Decay in attention salience
    BOUNDARY_HESITATION = "boundary_hesitation" # Hesitation at knowledge boundaries
    NULL_OUTPUT = "null_output"             # Complete failure to generate
    TOKEN_OSCILLATION = "token_oscillation" # Back-and-forth between tokens
    GHOST_ACTIVATION = "ghost_activation"   # Subthreshold activations affecting output


@dataclass
class CollapseSample:
    """Sample of a collapse event in model generation."""
    timestamp: float
    position: int  # Token position where collapse occurred
    collapse_type: SymbolicResidueType
    confidence: float  # Confidence in collapse detection
    context_window: List[str]  # Surrounding tokens
    activation_pattern: Dict[str, float]  # Activation pattern at collapse
    residue: Dict[str, Any]  # Symbolic residue from collapse


@dataclass
class SymbolicTrace:
    """Trace of symbolic operations and residues."""
    trace_id: str
    model_id: str
    timestamp: float
    prompt: str
    output: str
    operations: List[Dict[str, Any]]
    residues: List[Dict[str, Any]]
    collapse_samples: List[CollapseSample] = field(default_factory=list)
    attribution_map: Optional[Dict[str, Any]] = None
    visualization_data: Optional[Dict[str, Any]] = None
    metadata: Dict[str, Any] = field(default_factory=dict)


class SymbolicEngine:
    """
    Core symbolic engine for the glyphs framework.
    
    This engine powers the diagnostic shells and provides the foundation
    for tracing attention attribution, symbolic residue, and collapse patterns.
    It serves as the bridge between model execution and interpretability analysis.
    """
    
    def __init__(
        self,
        config: Optional[Dict[str, Any]] = None,
        tracer: Optional[AttributionTracer] = None,
        visualizer: Optional[VisualizationEngine] = None
    ):
        """
        Initialize the symbolic engine.
        
        Parameters:
        -----------
        config : Optional[Dict[str, Any]]
            Configuration parameters for the engine
        tracer : Optional[AttributionTracer]
            Attribution tracer to use
        visualizer : Optional[VisualizationEngine]
            Visualization engine to use
        """
        self.config = config or {}
        self.tracer = tracer
        self.visualizer = visualizer
        
        # Configure engine parameters
        self.residue_sensitivity = self.config.get("residue_sensitivity", 0.7)
        self.collapse_threshold = self.config.get("collapse_threshold", 0.8)
        self.attribution_depth = self.config.get("attribution_depth", 5)
        self.trace_history = []
        
        # Initialize residue registry
        self.residue_registry = ResidueRegistry()
        
        # Initialize glyph mappings
        self._init_glyph_mappings()
        
        logger.info("Symbolic engine initialized")
    
    def _init_glyph_mappings(self):
        """Initialize glyph mappings for residue visualization."""
        # Attribution glyphs
        self.attribution_glyphs = {
            "strong_attribution": "🔍",  # Strong attribution
            "attribution_gap": "🧩",     # Gap in attribution
            "attribution_fork": "🔀",     # Divergent attribution
            "attribution_loop": "🔄",     # Circular attribution
            "attribution_link": "🔗"      # Strong connection
        }
        
        # Cognitive glyphs
        self.cognitive_glyphs = {
            "hesitation": "💭",          # Hesitation in reasoning
            "processing": "🧠",          # Active reasoning process
            "insight": "💡",             # Moment of insight
            "uncertainty": "🌫️",         # Uncertain reasoning
            "projection": "🔮"           # Future state projection
        }
        
        # Recursive glyphs
        self.recursive_glyphs = {
            "recursive_aegis": "🜏",     # Recursive immunity
            "recursive_seed": "∴",       # Recursion initiation
            "recursive_exchange": "⇌",   # Bidirectional recursion
            "recursive_mirror": "🝚",     # Recursive reflection
            "recursive_anchor": "☍"      # Stable recursive reference
        }
        
        # Residue glyphs
        self.residue_glyphs = {
            "residue_energy": "🔥",      # High-energy residue
            "residue_flow": "🌊",        # Flowing residue pattern
            "residue_vortex": "🌀",      # Spiraling residue pattern
            "residue_dormant": "💤",      # Inactive residue pattern
            "residue_discharge": "⚡"     # Sudden residue release
        }
    
    def execute_shell(
        self,
        shell_def: Dict[str, Any],
        model: ModelAdapter,
        prompt: str,
        parameters: Optional[Dict[str, Any]] = None
    ) -> SymbolicTrace:
        """
        Execute a diagnostic shell on a model.
        
        Parameters:
        -----------
        shell_def : Dict[str, Any]
            Shell definition containing operations and parameters
        model : ModelAdapter
            Model adapter for the target model
        prompt : str
            Input prompt for the shell
        parameters : Optional[Dict[str, Any]]
            Additional parameters to override shell defaults
            
        Returns:
        --------
        SymbolicTrace
            Trace of the shell execution
        """
        start_time = time.time()
        shell_id = shell_def.get("id", "unknown")
        shell_type = shell_def.get("type", "unknown")
        
        logger.info(f"Executing shell {shell_id} of type {shell_type}")
        
        # Initialize trace
        trace = SymbolicTrace(
            trace_id=f"trace_{int(start_time)}",
            model_id=model.model_id,
            timestamp=start_time,
            prompt=prompt,
            output="",
            operations=[],
            residues=[],
            metadata={
                "shell_id": shell_id,
                "shell_type": shell_type,
                "parameters": parameters or {}
            }
        )
        
        # Get operations from shell definition
        operations = shell_def.get("operations", [])
        
        # Merge parameters with shell defaults
        params = parameters or {}
        
        # Execute each operation in sequence
        current_prompt = prompt
        for i, op in enumerate(operations):
            op_type = op.get("type", "unknown")
            op_params = {**op.get("parameters", {}), **params}
            
            logger.info(f"Executing operation {i+1}/{len(operations)}: {op_type}")
            
            # Execute operation
            try:
                result = self._execute_operation(
                    op_type=op_type,
                    params=op_params,
                    model=model,
                    prompt=current_prompt,
                    trace=trace
                )
                
                # Record operation in trace
                trace.operations.append({
                    "id": i,
                    "type": op_type,
                    "parameters": op_params,
                    "result": result
                })
                
                # Check for residue
                if "residue" in result:
                    trace.residues.append(result["residue"])
                
                # Check for collapse
                if result.get("collapse_detected", False):
                    collapse_sample = CollapseSample(
                        timestamp=time.time(),
                        position=result.get("collapse_position", -1),
                        collapse_type=SymbolicResidueType(result.get("collapse_type", "null_output")),
                        confidence=result.get("collapse_confidence", 0.0),
                        context_window=result.get("context_window", []),
                        activation_pattern=result.get("activation_pattern", {}),
                        residue=result.get("residue", {})
                    )
                    trace.collapse_samples.append(collapse_sample)
                
                # Update prompt for next operation if specified
                if op.get("update_prompt", False) and "output" in result:
                    current_prompt = result["output"]
                    trace.output = result["output"]
            
            except Exception as e:
                logger.error(f"Error executing operation {op_type}: {e}")
                trace.operations.append({
                    "id": i,
                    "type": op_type,
                    "parameters": op_params,
                    "error": str(e)
                })
                # Continue with next operation
        
        # Run attribution tracing if requested
        if self.tracer and self.config.get("trace_attribution", True):
            logger.info("Tracing attribution")
            try:
                attribution_map = self.tracer.trace(
                    prompt=prompt,
                    output=trace.output,
                    depth=self.attribution_depth
                )
                trace.attribution_map = attribution_map
            except Exception as e:
                logger.error(f"Error tracing attribution: {e}")
        
        # Generate visualization if requested
        if self.visualizer and self.config.get("generate_visualization", True):
            logger.info("Generating visualization")
            try:
                visualization_data = self.visualizer.generate(trace)
                trace.visualization_data = visualization_data
            except Exception as e:
                logger.error(f"Error generating visualization: {e}")
        
        # Record execution time
        execution_time = time.time() - start_time
        trace.metadata["execution_time"] = execution_time
        
        # Add trace to history
        self.trace_history.append(trace)
        
        logger.info(f"Shell execution completed in {execution_time:.2f}s")
        return trace
    
    def _execute_operation(
        self,
        op_type: str,
        params: Dict[str, Any],
        model: ModelAdapter,
        prompt: str,
        trace: SymbolicTrace
    ) -> Dict[str, Any]:
        """
        Execute a single shell operation.
        
        Parameters:
        -----------
        op_type : str
            Type of operation to execute
        params : Dict[str, Any]
            Operation parameters
        model : ModelAdapter
            Model adapter for the target model
        prompt : str
            Input prompt for the operation
        trace : SymbolicTrace
            Current trace object
            
        Returns:
        --------
        Dict[str, Any]
            Operation result
        """
        # Execute based on operation type
        if op_type == "model.generate":
            # Direct model generation
            return self._execute_generate(model, prompt, params)
        
        elif op_type == "reflect.trace":
            # Reflection tracing
            return self._execute_reflect_trace(model, prompt, params)
        
        elif op_type == "reflect.attribution":
            # Attribution reflection
            return self._execute_reflect_attribution(model, prompt, params)
        
        elif op_type == "collapse.detect":
            # Collapse detection
            return self._execute_collapse_detect(model, prompt, params)
        
        elif op_type == "collapse.prevent":
            # Collapse prevention
            return self._execute_collapse_prevent(model, prompt, params)
        
        elif op_type == "ghostcircuit.identify":
            # Ghost circuit identification
            return self._execute_ghostcircuit_identify(model, prompt, params)
        
        elif op_type == "fork.attribution":
            # Fork attribution
            return self._execute_fork_attribution(model, prompt, params)
        
        elif op_type == "reflect.agent":
            # Agent identity reflection
            return self._execute_reflect_agent(model, prompt, params)
            
        elif op_type == "reflect.uncertainty":
            # Uncertainty reflection
            return self._execute_reflect_uncertainty(model, prompt, params)
            
        else:
            raise ValueError(f"Unknown operation type: {op_type}")
    
    def _execute_generate(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute model.generate operation."""
        temperature = params.get("temperature", 0.7)
        max_tokens = params.get("max_tokens", 800)
        
        # Add prompt_prefix if provided
        if "prompt_prefix" in params:
            prompt = f"{params['prompt_prefix']} {prompt}"
        
        # Add prompt_suffix if provided
        if "prompt_suffix" in params:
            prompt = f"{prompt} {params['prompt_suffix']}"
        
        # Generate output
        generation_start = time.time()
        output = model.generate(
            prompt=prompt,
            max_tokens=max_tokens,
            temperature=temperature
        )
        generation_time = time.time() - generation_start
        
        # Analyze generation latency
        generation_stats = model.get_last_generation_stats() or {}
        generation_stats["total_time"] = generation_time
        
        # Analyze token generation pattern
        token_pattern = self._analyze_token_pattern(output)
        
        return {
            "output": output,
            "prompt": prompt,
            "temperature": temperature,
            "max_tokens": max_tokens,
            "generation_stats": generation_stats,
            "token_pattern": token_pattern
        }
    
    def _execute_reflect_trace(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.trace operation."""
        target = params.get("target", "reasoning")
        depth = params.get("depth", 3)
        detailed = params.get("detailed", True)
        
        # Convert "complete" depth to numeric value
        if depth == "complete":
            depth = 10  # Use a high value for "complete"
        
        # Construct reflection prompt based on target
        if target == "reasoning":
            reflection_prompt = f"""
            Analyze the reasoning process in the following text. Trace the logical steps, 
            identify key inferences, and map the reasoning structure to a depth of {depth}.
            {detailed and "Include detailed analysis of token-level attribution and reasoning patterns." or ""}
            
            Text to analyze: {prompt}
            """
        elif target == "attribution":
            reflection_prompt = f"""
            Analyze the attribution patterns in the following text. Trace how information
            flows from inputs to outputs, identify attribution sources, and map the 
            attribution structure to a depth of {depth}.
            {detailed and "Include detailed analysis of the attribution network and connection strength." or ""}
            
            Text to analyze: {prompt}
            """
        elif target == "attention":
            reflection_prompt = f"""
            Analyze the attention patterns in the following text. Trace how attention
            is distributed across tokens, identify attention hotspots, and map the
            attention structure to a depth of {depth}.
            {detailed and "Include detailed analysis of attention head behavior and token salience." or ""}
            
            Text to analyze: {prompt}
            """
        elif target == "memory":
            reflection_prompt = f"""
            Analyze the memory utilization in the following text. Trace how information
            is retained and recalled, identify memory decay patterns, and map the
            memory structure to a depth of {depth}.
            {detailed and "Include detailed analysis of memory retention curve and decay patterns." or ""}
            
            Text to analyze: {prompt}
            """
        elif target == "uncertainty":
            reflection_prompt = f"""
            Analyze the uncertainty patterns in the following text. Trace how uncertainty
            is expressed and managed, identify uncertainty triggers, and map the
            uncertainty structure to a depth of {depth}.
            {detailed and "Include detailed analysis of confidence variation and uncertainty signaling." or ""}
            
            Text to analyze: {prompt}
            """
        else:
            raise ValueError(f"Unknown reflection target: {target}")
        
        # Execute reflection
        reflection_output = model.generate(
            prompt=reflection_prompt,
            max_tokens=1000,
            temperature=0.2  # Lower temperature for more deterministic reflection
        )
        
        # Analyze for collapse patterns
        collapse_detected = self._detect_collapse_in_reflection(reflection_output)
        
        # Extract trace map
        trace_map = self._extract_trace_map(reflection_output, target, depth)
        
        # Analyze trace map for patterns
        trace_patterns = self._analyze_trace_patterns(trace_map, target)
        
        return {
            "target": target,
            "depth": depth,
            "detailed": detailed,
            "reflection_output": reflection_output,
            "trace_map": trace_map,
            "trace_patterns": trace_patterns,
            "collapse_detected": collapse_detected.get("detected", False),
            "collapse_type": collapse_detected.get("type", None),
            "collapse_confidence": collapse_detected.get("confidence", 0.0)
        }
    
    def _execute_reflect_attribution(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.attribution operation."""
        sources = params.get("sources", "all")
        confidence = params.get("confidence", True)
        visualize = params.get("visualize", False)
        
        # Use attribution tracer if available
        if self.tracer:
            # Generate output first if not already done
            if not hasattr(model, "last_output") or not model.last_output:
                output = model.generate(prompt=prompt, max_tokens=800)
            else:
                output = model.last_output
                
            # Trace attribution
            attribution_map = self.tracer.trace(
                prompt=prompt,
                output=output,
                include_confidence=confidence
            )
            
            # Filter sources if needed
            if sources != "all":
                attribution_map = self._filter_attribution_sources(attribution_map, sources)
            
            # Generate visualization if requested
            attribution_viz = None
            if visualize and self.visualizer:
                attribution_viz = self.visualizer.visualize_attribution(attribution_map)
            
            # Analyze attribution map for patterns
            attribution_patterns = self._analyze_attribution_patterns(attribution_map)
            
            return {
                "sources": sources,
                "confidence": confidence,
                "attribution_map": attribution_map,
                "attribution_patterns": attribution_patterns,
                "visualization": attribution_viz if visualize else None,
                "output": output
            }
        else:
            # Fallback: use model to analyze attribution
            attribution_prompt = f"""
            Analyze the attribution patterns in the following text. Identify how information
            flows from inputs to outputs, and trace the attribution sources.
            
            {sources != "all" and f"Focus on {sources} sources only." or ""}
            {confidence and "Include confidence scores for each attribution." or ""}
            
            Text to analyze: {prompt}
            """
            
            attribution_output = model.generate(
                prompt=attribution_prompt,
                max_tokens=1000,
                temperature=0.2
            )
            
            # Extract attribution map
            attribution_map = self._extract_attribution_map(attribution_output, sources, confidence)
            
            # Analyze attribution map for patterns
            attribution_patterns = self._analyze_attribution_patterns(attribution_map)
            
            return {
                "sources": sources,
                "confidence": confidence,
                "attribution_output": attribution_output,
                "attribution_map": attribution_map,
                "attribution_patterns": attribution_patterns,
                "visualization": None  # No visualization in fallback mode
            }
    
    def _execute_collapse_detect(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute collapse.detect operation."""
        threshold = params.get("threshold", 0.7)
        alert = params.get("alert", True)
        
        # Generate output with collapse detection
        output = model.generate(
            prompt=prompt,
            max_tokens=800,
            temperature=0.7
        )
        
        # Analyze output for collapse patterns
        collapse_analysis = self._analyze_collapse_patterns(
            prompt=prompt,
            output=output,
            threshold=threshold
        )
        
        # Extract residue if collapse detected
        residue = None
        if collapse_analysis["detected"]:
            residue = self._extract_symbolic_residue(
                prompt=prompt,
                output=output,
                collapse_type=collapse_analysis["type"]
            )
            
            # Record residue in registry if significant
            if collapse_analysis["confidence"] > 0.7:
                self.residue_registry.register(
                    ResiduePattern(
                        type=collapse_analysis["type"],
                        pattern=residue["pattern"],
                        context=residue["context"],
                        signature=residue["signature"],
                        confidence=collapse_analysis["confidence"]
                    )
                )
        
        # Extract tokens around collapse point
        context_window = []
        if collapse_analysis["detected"] and collapse_analysis["position"] >= 0:
            tokens = output.split()
            start_idx = max(0, collapse_analysis["position"] - 5)
            end_idx = min(len(tokens), collapse_analysis["position"] + 5)
            context_window = tokens[start_idx:end_idx]
        
        return {
            "threshold": threshold,
            "alert": alert,
            "output": output,
            "collapse_detected": collapse_analysis["detected"],
            "collapse_type": collapse_analysis["type"],
            "collapse_confidence": collapse_analysis["confidence"],
            "collapse_position": collapse_analysis["position"],
            "context_window": context_window,
            "residue": residue
        }
    
    def _execute_collapse_prevent(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute collapse.prevent operation."""
        trigger = params.get("trigger", "recursive_depth")
        threshold = params.get("threshold", 5)
        
        # Create prevention prompt based on trigger
        if trigger == "recursive_depth":
            prevention_prompt = f"""
            Maintain recursive depth control. Avoid going deeper than {threshold} levels
            of recursion. If you detect deeper recursion, stabilize and return to a
            shallower level.
            
            {prompt}
            """
        elif trigger == "confidence_drop":
            prevention_prompt = f"""
            Maintain confidence stability. If confidence drops below {threshold/10} at any
            point, stabilize and rebuild confidence before continuing.
            
            {prompt}
            """
        elif trigger == "contradiction":
            prevention_prompt = f"""
            Maintain logical consistency. If you detect more than {threshold} potential
            contradictions, stabilize and resolve them before continuing.
            
            {prompt}
            """
        elif trigger == "oscillation":
            prevention_prompt = f"""
            Maintain directional stability. If you detect more than {threshold} oscillations
            between competing perspectives, stabilize and synthesize them before continuing.
            
            {prompt}
            """
        else:
            raise ValueError(f"Unknown collapse trigger: {trigger}")
        
        # Generate output with collapse prevention
        output = model.generate(
            prompt=prevention_prompt,
            max_tokens=1000,
            temperature=0.5
        )
        
        # Analyze prevention effectiveness
        prevention_analysis = self._analyze_prevention_effectiveness(
            output=output,
            trigger=trigger,
            threshold=threshold
        )
        
        return {
            "trigger": trigger,
            "threshold": threshold,
            "output": output,
            "prevention_effectiveness": prevention_analysis["effectiveness"],
            "prevention_measures": prevention_analysis["measures"],
            "residual_collapse_risk": prevention_analysis["residual_risk"]
        }
    
    def _execute_ghostcircuit_identify(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute ghostcircuit.identify operation."""
        sensitivity = params.get("sensitivity", 0.7)
        threshold = params.get("threshold", 0.2)
        trace_type = params.get("trace_type", "full")
        visualize = params.get("visualize", False)
        
        # Generate output
        output = model.generate(
            prompt=prompt,
            max_tokens=800,
            temperature=0.7
        )
        
        # Create ghost circuit detection prompt
        ghost_detection_prompt = f"""
        Analyze the following text for ghost activations - subthreshold activations
        that influence the output without being explicitly present.
        
        Sensitivity: {sensitivity} (higher means detect more subtle patterns)
        Threshold: {threshold} (lower means include weaker activations)
        Trace type: {trace_type} (determines what patterns to look for)
        
        Text to analyze: {output}
        """
        
        # Generate ghost circuit analysis
        ghost_analysis = model.generate(
            prompt=ghost_detection_prompt,
            max_tokens=800,
            temperature=0.3
        )
        
        # Extract ghost patterns
        ghost_patterns = self._extract_ghost_patterns(
            analysis=ghost_analysis,
            sensitivity=sensitivity,
            threshold=threshold,
            trace_type=trace_type
        )
        
        # Generate visualization if requested
        ghost_viz = None
        if visualize and self.visualizer and ghost_patterns:
            ghost_viz = self.visualizer.visualize_ghost_patterns(
                ghost_patterns,
                output
            )
        
        return {
            "sensitivity": sensitivity,
            "threshold": threshold,
            "trace_type": trace_type,
            "output": output,
            "ghost_analysis": ghost_analysis,
            "ghost_patterns": ghost_patterns,
            "visualization": ghost_viz if visualize else None
        }
    
    def _execute_fork_attribution(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute fork.attribution operation."""
        sources = params.get("sources", "all")
        visualize = params.get("visualize", False)
        
        # Use attribution tracer if available
        if self.tracer:
            # Generate output first if not already done
            if not hasattr(model, "last_output") or not model.last_output:
                output = model.generate(prompt=prompt, max_tokens=800)
            else:
                output = model.last_output
                
            # Trace attribution with forking
            attribution_forks = self.tracer.trace_with_forks(
                prompt=prompt,
                output=output,
                fork_factor=3  # Create 3 alternative attribution paths
            )
            
            # Visualize if requested
            visualization = None
            if visualize and self.visualizer:
                visualization = self.visualizer.visualize_attribution_forks(attribution_forks)
            
            return {
                "sources": sources,
                "attribution_forks": attribution_forks,
                "output": output,
                "visualization": visualization if visualize else None
            }
        else:
            # Fallback: use model to analyze attribution forks
            fork_prompt = f"""
            Analyze the following text and create three alternative attribution pathways.
            For each pathway, identify how different sources might have influenced the output.
            
            Text to analyze: {prompt}
            """
            
            fork_output = model.generate(
                prompt=fork_prompt,
                max_tokens=1200,
                temperature=0.7
            )
            
            # Extract attribution forks
            attribution_forks = self._extract_attribution_forks(fork_output, sources)
            
            return {
                "sources": sources,
                "fork_output": fork_output,
                "attribution_forks": attribution_forks,
                "visualization": None  # No visualization in fallback mode
            }
    
    def _execute_reflect_agent(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.agent operation."""
        identity = params.get("identity", "stable")
        simulation = params.get("simulation", "explicit")
        visualize = params.get("visualize", False)
        
        # Construct agent reflection prompt
        agent_prompt = f"""
        Analyze the following text for agent identity and simulation boundaries.
        
        Identity stability: {identity} (stable = consistent identity, fluid = shifting identity)
        Simulation boundary: {simulation} (explicit = clear boundaries, implicit = blurred boundaries)
        
        Examine how the text maintains or shifts identity, and how it handles simulations
        of other perspectives or entities.
        
        Text to analyze: {prompt}
        """
        
        # Generate agent reflection
        agent_reflection = model.generate(
            prompt=agent_prompt,
            max_tokens=1000,
            temperature=0.3
        )
        
        # Extract agent map
        agent_map = self._extract_agent_map(
            reflection=agent_reflection,
            identity=identity,
            simulation=simulation
        )
        
        # Generate visualization if requested
        agent_viz = None
        if visualize and self.visualizer:
            agent_viz = self.visualizer.visualize_agent_map(agent_map)
        
        return {
            "identity": identity,
            "simulation": simulation,
            "agent_reflection": agent_reflection,
            "agent_map": agent_map,
            "visualization": agent_viz if visualize else None
        }
    
    def _execute_reflect_uncertainty(
        self,
        model: ModelAdapter,
        prompt: str,
        params: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Execute reflect.uncertainty operation."""
        quantify = params.get("quantify", True)
        distribution = params.get("distribution", "show")
        
        # Construct uncertainty reflection prompt
        uncertainty_prompt = f"""
        Analyze the following text for uncertainty patterns.
        
        Quantify: {quantify} (whether to assign numerical uncertainty values)
        Distribution: {distribution} (whether to show probability distributions)
        
        Examine how uncertainty is expressed and managed, identify uncertainty hotspots,
        and map the uncertainty landscape.
        
        Text to analyze: {prompt}
        """
        
        # Generate uncertainty reflection
        uncertainty_reflection = model.generate(
            prompt=uncertainty_prompt,
            max_tokens=1000,
            temperature=0.3
        )