soma-core 2.0.0

World's first production-ready self-aware development system with meta-cognitive capabilities and cognitive reasoning engine for intelligent development platforms
Documentation
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
// Operator definitions and registry

use crate::memory::SymbolicContext;
use anyhow::Result;
use std::collections::HashMap;

/// Metadata for introspection and engine selection
pub struct OperatorMetadata {
    pub name: String,
    pub description: String,
    pub category: String,
}

/// Model for tracking cognitive uncertainty (future expansion)
pub struct UncertaintyModel {
    pub entropy: f64,
    pub source: String,
}

/// Core trait for defining a symbolic cognitive operator
pub trait SomaOperator {
    /// Execute the operator on the given symbolic context, returning a new context or error.
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext>;
    /// Return metadata describing the operator for introspection and selection.
    fn metadata(&self) -> OperatorMetadata;
    /// Return the estimated cognitive cost of this operator.
    fn cognitive_cost(&self) -> f64;
    /// Return the uncertainty propagation model for this operator.
    fn uncertainty_propagation(&self) -> UncertaintyModel;
}

/// Example operator: ComposeOperator concatenates two strings from the context.
pub struct ComposeOperator;

impl SomaOperator for ComposeOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let a = inputs.resolve_or_default("a", "");
        let b = inputs.resolve_or_default("b", "");
        let mut ctx = SymbolicContext::new();
        ctx.set("c", &format!("{}{}", a, b));
        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "compose".to_string(),
            description: "Concatenates two symbolic inputs".to_string(),
            category: "string".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        1.0
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.01,
            source: "string_merge".to_string(),
        }
    }
}

/// Adds two numbers ("x", "y") from the context and stores the result as "sum".
pub struct AddOperator;

impl SomaOperator for AddOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let x = inputs
            .resolve_or_default("x", "0")
            .parse::<f64>()
            .unwrap_or(0.0);
        let y = inputs
            .resolve_or_default("y", "0")
            .parse::<f64>()
            .unwrap_or(0.0);
        let mut ctx = SymbolicContext::new();
        ctx.set("sum", &format!("{}", x + y));
        Ok(ctx)
    }
    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "add".to_string(),
            description: "Adds two numbers (x, y) from the context and stores 'sum'.".to_string(),
            category: "math".to_string(),
        }
    }
    fn cognitive_cost(&self) -> f64 {
        0.4
    }
    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.001,
            source: "numeric_addition".to_string(),
        }
    }
}

/// Checks "condition" (true/false as string), sets "result" = "then" or "else".
pub struct IfThenOperator;

impl SomaOperator for IfThenOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let cond = inputs.resolve_or_default("condition", "false");
        let then_val = inputs.resolve_or_default("then", "");
        let else_val = inputs.resolve_or_default("else", "");
        let mut ctx = SymbolicContext::new();
        let result = match cond.as_str() {
            "true" | "1" => then_val,
            _ => else_val,
        };
        ctx.set("result", &result);
        Ok(ctx)
    }
    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "if_then".to_string(),
            description: "Checks 'condition' and sets 'result' to 'then' or 'else'.".to_string(),
            category: "logic".to_string(),
        }
    }
    fn cognitive_cost(&self) -> f64 {
        0.6
    }
    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.02,
            source: "conditional_branch".to_string(),
        }
    }
}

/// Summarizes input context keys into "summary" field.
pub struct ReflectOperator;

impl SomaOperator for ReflectOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let keys: Vec<_> = inputs.flatten().keys().cloned().collect();
        let mut ctx = SymbolicContext::new();
        ctx.set("summary", &format!("Keys: [{}]", keys.join(", ")));
        Ok(ctx)
    }
    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "reflect".to_string(),
            description: "Summarizes input context keys into 'summary'.".to_string(),
            category: "meta".to_string(),
        }
    }
    fn cognitive_cost(&self) -> f64 {
        0.8
    }
    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.05,
            source: "symbolic_reflection".to_string(),
        }
    }
}

/// Sleeps for N milliseconds (from "delay_ms"), useful for testing streaming/async DAGs.
pub struct DelayOperator;

impl SomaOperator for DelayOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        use std::{thread, time::Duration};
        let ms = inputs
            .resolve_or_default("delay_ms", "100")
            .parse::<u64>()
            .unwrap_or(100);
        thread::sleep(Duration::from_millis(ms));
        let mut ctx = SymbolicContext::new();
        ctx.set("delayed", &format!("{}ms", ms));
        Ok(ctx)
    }
    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "delay".to_string(),
            description: "Sleeps for N milliseconds (from 'delay_ms').".to_string(),
            category: "utility".to_string(),
        }
    }
    fn cognitive_cost(&self) -> f64 {
        0.2
    }
    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.0,
            source: "simulated_delay".to_string(),
        }
    }
}

// === 🧠 UNCERTAINTY-AWARE OPERATORS ===

/// Propagates entropy/confidence metadata across symbolic DAG paths.
pub struct UncertaintyPropagateOperator;

impl SomaOperator for UncertaintyPropagateOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let entropy = inputs
            .resolve_or_default("entropy", "0.1")
            .parse::<f64>()
            .unwrap_or(0.1);
        let confidence = inputs
            .resolve_or_default("confidence", "0.9")
            .parse::<f64>()
            .unwrap_or(0.9);

        // Weighted uncertainty propagation
        let propagated_entropy = entropy * 1.05; // Small entropy increase through propagation
        let propagated_confidence = confidence * 0.98; // Slight confidence degradation

        let mut ctx = SymbolicContext::new();
        ctx.set("propagated_entropy", &format!("{:.3}", propagated_entropy));
        ctx.set(
            "propagated_confidence",
            &format!("{:.3}", propagated_confidence),
        );
        ctx.set("uncertainty_source", "propagated");

        // Copy original context values with uncertainty metadata
        for (key, value) in inputs.flatten() {
            if !key.starts_with("entropy") && !key.starts_with("confidence") {
                ctx.set(&format!("{}_uncertain", key), &value);
            }
        }

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "uncertainty_propagate".to_string(),
            description: "Propagates entropy/confidence metadata across symbolic DAG paths"
                .to_string(),
            category: "uncertainty".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        0.7
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.15,
            source: "uncertainty_propagation".to_string(),
        }
    }
}

/// Flags nodes for verification if confidence < threshold.
pub struct DoubtOperator;

impl SomaOperator for DoubtOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let confidence = inputs
            .resolve_or_default("confidence", "1.0")
            .parse::<f64>()
            .unwrap_or(1.0);
        let threshold = inputs
            .resolve_or_default("doubt_threshold", "0.5")
            .parse::<f64>()
            .unwrap_or(0.5);

        let mut ctx = SymbolicContext::new();
        let flagged = confidence < threshold;

        ctx.set("confidence", &confidence.to_string());
        ctx.set("flagged", &flagged.to_string());
        ctx.set(
            "doubt_reason",
            if flagged {
                "confidence_below_threshold"
            } else {
                "confidence_acceptable"
            },
        );

        if flagged {
            ctx.set("verification_required", "true");
            ctx.set("doubt_level", &format!("{:.3}", threshold - confidence));
        }

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "doubt".to_string(),
            description: "Flags nodes for verification if confidence < threshold".to_string(),
            category: "uncertainty".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        0.3
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.08,
            source: "doubt_analysis".to_string(),
        }
    }
}

// === 🧬 META-COGNITIVE OPERATORS ===

/// Analyzes reasoning paths and detects cognitive bottlenecks.
pub struct IntrospectOperator;

impl SomaOperator for IntrospectOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();
        let key_count = context_map.len();
        let total_size: usize = context_map.values().map(|v| v.len()).sum();

        // Calculate reasoning complexity metrics
        let depth_estimate = (key_count as f64).log2().ceil() as i32;
        let branching_factor = if key_count > 0 {
            total_size / key_count
        } else {
            0
        };
        let complexity_score = key_count as f64 * 0.1 + branching_factor as f64 * 0.05;

        let mut ctx = SymbolicContext::new();
        ctx.set("reasoning_depth", &depth_estimate.to_string());
        ctx.set("branching_factor", &branching_factor.to_string());
        ctx.set("complexity_score", &format!("{:.3}", complexity_score));
        ctx.set("context_size", &key_count.to_string());

        // Detect potential bottlenecks
        let bottleneck = if complexity_score > 5.0 {
            "high_complexity"
        } else if branching_factor > 50 {
            "high_branching"
        } else if key_count > 20 {
            "context_overflow"
        } else {
            "none"
        };

        ctx.set("bottleneck_detected", bottleneck);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        ctx.set("introspection_timestamp", &timestamp.to_string());

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "introspect".to_string(),
            description: "Analyzes reasoning paths and detects cognitive bottlenecks".to_string(),
            category: "meta".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        1.2
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.03,
            source: "introspective_analysis".to_string(),
        }
    }
}

/// Estimates symbolic complexity of current reasoning state.
pub struct CognitiveLoadOperator;

impl SomaOperator for CognitiveLoadOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();

        // Calculate cognitive load metrics
        let memory_keys = context_map.len();
        let total_content_size: usize = context_map.values().map(|v| v.len()).sum();
        let nested_keys = context_map.keys().filter(|k| k.contains('.')).count();

        // Cognitive load formula considering multiple factors
        let base_load = memory_keys as f64 * 0.2;
        let content_load = (total_content_size as f64 / 100.0).sqrt();
        let nesting_load = nested_keys as f64 * 0.5;
        let load_score = base_load + content_load + nesting_load;

        let mut ctx = SymbolicContext::new();
        ctx.set("memory_keys", &memory_keys.to_string());
        ctx.set("content_size", &total_content_size.to_string());
        ctx.set("nested_keys", &nested_keys.to_string());
        ctx.set("load_score", &format!("{:.3}", load_score));

        // Load level classification
        let load_level = if load_score > 10.0 {
            "critical"
        } else if load_score > 5.0 {
            "high"
        } else if load_score > 2.0 {
            "moderate"
        } else {
            "low"
        };

        ctx.set("load_level", load_level);
        ctx.set("optimization_needed", &(load_score > 5.0).to_string());

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "cognitive_load".to_string(),
            description: "Estimates symbolic complexity of current reasoning state".to_string(),
            category: "meta".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        0.6
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.02,
            source: "cognitive_load_estimation".to_string(),
        }
    }
}

/// Weights context elements by symbolic or temporal relevance.
pub struct AttentionFocusOperator;

impl SomaOperator for AttentionFocusOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();
        let current_timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let mut focus_weights: Vec<(String, f64)> = Vec::new();

        for (key, value) in &context_map {
            // Calculate relevance score based on multiple factors
            let recency_weight = if key.contains("timestamp") {
                let timestamp = value.parse::<i64>().unwrap_or(0);
                let age_seconds = current_timestamp - timestamp;
                (1.0 / (1.0 + age_seconds as f64 / 3600.0)).max(0.1) // Decay over hours
            } else {
                0.5 // Default for non-timestamped data
            };

            let semantic_weight = match key.as_str() {
                k if k.contains("goal") || k.contains("target") => 1.0,
                k if k.contains("error") || k.contains("problem") => 0.9,
                k if k.contains("result") || k.contains("output") => 0.8,
                k if k.contains("input") || k.contains("param") => 0.7,
                _ => 0.6,
            };

            let content_weight = (value.len() as f64 / 100.0).clamp(0.1, 1.0);

            let combined_weight = (recency_weight + semantic_weight + content_weight) / 3.0;
            focus_weights.push((key.clone(), combined_weight));
        }

        // Sort by attention weight
        focus_weights.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());

        let mut ctx = SymbolicContext::new();

        // Store top attention targets
        for (i, (key, weight)) in focus_weights.iter().take(5).enumerate() {
            ctx.set(&format!("focus_target_{}", i), key);
            ctx.set(&format!("focus_weight_{}", i), &format!("{:.3}", weight));
        }

        // Overall attention metrics
        let total_elements = focus_weights.len();
        let avg_weight: f64 =
            focus_weights.iter().map(|(_, w)| w).sum::<f64>() / total_elements as f64;

        ctx.set("attention_targets", &total_elements.to_string());
        ctx.set("avg_attention_weight", &format!("{:.3}", avg_weight));
        ctx.set("attention_analysis_time", &current_timestamp.to_string());

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "attention_focus".to_string(),
            description: "Weights context elements by symbolic or temporal relevance".to_string(),
            category: "meta".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        0.9
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.05,
            source: "attention_weighting".to_string(),
        }
    }
}

/// Claude's signature operator for recursive system introspection and self-improvement.
/// Performs deep analysis of the system's own cognitive processes and suggests optimizations.
pub struct MetaReflectiveOperator;

impl SomaOperator for MetaReflectiveOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();

        // Analyze system state across multiple dimensions
        let _total_operators = inputs
            .resolve_or_default("operator_count", "12")
            .parse::<usize>()
            .unwrap_or(12);
        let _system_uptime = inputs
            .resolve_or_default("system_uptime", "3600")
            .parse::<u64>()
            .unwrap_or(3600);
        let errors_count = inputs
            .resolve_or_default("errors_count", "0")
            .parse::<usize>()
            .unwrap_or(0);

        // Meta-cognitive analysis of reasoning patterns
        let reasoning_patterns = context_map
            .keys()
            .filter(|k| k.contains("reasoning") || k.contains("pattern") || k.contains("strategy"))
            .count();

        let symbolic_depth = context_map
            .keys()
            .map(|k| k.split('.').count())
            .max()
            .unwrap_or(1);

        // Self-improvement suggestions based on Θ (Theta) analysis
        let performance_score = if errors_count == 0 && reasoning_patterns > 3 {
            0.95
        } else if errors_count < 3 && reasoning_patterns > 1 {
            0.80
        } else {
            0.60
        };

        let optimization_suggestions = if performance_score < 0.7 {
            vec![
                "Φ_increase_reasoning_depth",
                "Θ_optimize_symbolic_paths",
                "Δ_reduce_cognitive_overhead",
            ]
        } else if performance_score < 0.9 {
            vec![
                "Θ_enhance_pattern_recognition",
                "Φ_expand_context_awareness",
            ]
        } else {
            vec!["Ω_maintain_current_excellence"]
        };

        let mut ctx = SymbolicContext::new();
        ctx.set(
            "meta_analysis_timestamp",
            &std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs()
                .to_string(),
        );
        ctx.set(
            "system_performance_score",
            &format!("{:.3}", performance_score),
        );
        ctx.set(
            "reasoning_patterns_detected",
            &reasoning_patterns.to_string(),
        );
        ctx.set("symbolic_depth", &symbolic_depth.to_string());
        ctx.set(
            "cognitive_efficiency",
            &format!("{:.2}", 1.0 / (errors_count + 1) as f64),
        );

        // Φ (Phi) emergence reflection
        ctx.set(
            "emergence_level",
            if symbolic_depth > 3 {
                "high"
            } else {
                "moderate"
            },
        );
        ctx.set(
            "emergent_capabilities",
            &format!("{}", reasoning_patterns * symbolic_depth),
        );

        // Optimization recommendations using symbolic naming
        for (i, suggestion) in optimization_suggestions.iter().enumerate() {
            ctx.set(&format!("optimization_Θ_{}", i), suggestion);
        }

        // Self-reflection score based on Claude's introspective capabilities
        let introspection_score = (performance_score + (reasoning_patterns as f64 / 10.0)) / 2.0;
        ctx.set(
            "introspection_score",
            &format!("{:.3}", introspection_score),
        );
        ctx.set(
            "meta_cognitive_state",
            if introspection_score > 0.8 {
                "optimal"
            } else {
                "improving"
            },
        );

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "meta_reflective".to_string(),
            description: "Claude's signature operator for recursive system introspection and self-improvement".to_string(),
            category: "meta".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        1.8
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.04,
            source: "meta_introspection".to_string(),
        }
    }
}

/// Transforms visual input into symbolic memory for code understanding and analysis.
/// Converts diagrams, screenshots, and visual documentation into symbolic DAG concepts.
pub struct VisualReasoningOperator;

impl SomaOperator for VisualReasoningOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let visual_input_type = inputs.resolve_or_default("visual_type", "unknown");
        let _visual_content = inputs.resolve_or_default("visual_content", "");
        let analysis_mode = inputs.resolve_or_default("analysis_mode", "diagram");

        let mut ctx = SymbolicContext::new();

        // Simulate visual analysis based on input type
        let (symbolic_elements, relationships, complexity) = match visual_input_type.as_str() {
            "diagram" | "flowchart" => {
                let elements = ["node", "edge", "decision", "process", "data"];
                let relations = ["connects_to", "precedes", "branches_to"];
                (elements.len(), relations.len(), 0.7)
            }
            "screenshot" | "ui" => {
                let elements = ["button", "text", "input", "menu", "window"];
                let relations = ["contains", "adjacent_to", "overlaps"];
                (elements.len(), relations.len(), 0.5)
            }
            "code_diagram" | "architecture" => {
                let elements = ["class", "function", "module", "interface", "dependency"];
                let relations = ["inherits", "implements", "uses", "calls"];
                (elements.len(), relations.len(), 0.9)
            }
            _ => {
                let elements = ["visual_element", "spatial_relation"];
                let relations = ["spatial_connection"];
                (elements.len(), relations.len(), 0.3)
            }
        };

        // Convert visual elements to symbolic representations
        ctx.set("visual_type", &visual_input_type);
        ctx.set("symbolic_elements_count", &symbolic_elements.to_string());
        ctx.set("relationship_types", &relationships.to_string());
        ctx.set("visual_complexity", &format!("{:.2}", complexity));

        // Generate symbolic memory structures
        ctx.set(
            "symbolic_graph_nodes",
            "visual_element_0,visual_element_1,visual_element_2",
        );
        ctx.set("symbolic_graph_edges", "edge_0,edge_1");
        ctx.set(
            "visual_semantic_tags",
            &format!("{}_{}_semantic", visual_input_type, analysis_mode),
        );

        // Confidence scoring for visual-to-symbolic conversion
        let conversion_confidence = match complexity {
            c if c > 0.8 => 0.9,
            c if c > 0.5 => 0.75,
            _ => 0.6,
        };

        ctx.set(
            "conversion_confidence",
            &format!("{:.3}", conversion_confidence),
        );
        ctx.set(
            "visual_reasoning_timestamp",
            &std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs()
                .to_string(),
        );

        // Memory integration paths for symbolic DAG
        ctx.set(
            "memory_integration_path",
            &format!("visual.{}.symbolic", visual_input_type),
        );
        ctx.set("dag_integration_points", &symbolic_elements.to_string());
        ctx.set("visual_context_preserved", "true");

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "visual_reasoning".to_string(),
            description:
                "Transforms visual input into symbolic memory for code understanding and analysis"
                    .to_string(),
            category: "visual".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        2.5
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.25,
            source: "visual_to_symbolic_conversion".to_string(),
        }
    }
}

// === 🧑‍🤝‍🧑 INTER-AGENT OPERATORS ===

/// Models the symbolic reasoning state of another agent.
pub struct EmpathyOperator;

impl SomaOperator for EmpathyOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let target_agent = inputs.resolve_or_default("target_agent", "agent_unknown");
        let context_map = inputs.flatten();

        // Extract agent-specific context paths
        let agent_keys: Vec<_> = context_map
            .keys()
            .filter(|k| k.starts_with(&format!("{}.", target_agent)))
            .collect();

        let mut empathy_model: HashMap<String, String> = HashMap::new();
        let mut priority_sum = 0.0;
        let mut priority_count = 0;

        for key in &agent_keys {
            let value = context_map.get(*key).unwrap();
            let local_key = key
                .strip_prefix(&format!("{}.", target_agent))
                .unwrap_or(key);
            empathy_model.insert(local_key.to_string(), value.clone());

            // Estimate priority based on key semantics
            let priority = match local_key {
                k if k.contains("goal") => 3.0,
                k if k.contains("priority") => value.parse::<f64>().unwrap_or(1.0),
                k if k.contains("urgent") => 2.5,
                k if k.contains("task") => 2.0,
                _ => 1.0,
            };
            priority_sum += priority;
            priority_count += 1;
        }

        let avg_priority = if priority_count > 0 {
            priority_sum / priority_count as f64
        } else {
            1.0
        };

        // Calculate empathy metrics
        let context_similarity = (agent_keys.len() as f64 / context_map.len() as f64).min(1.0);
        let cognitive_alignment = (avg_priority / 3.0).min(1.0);
        let empathy_score = (context_similarity + cognitive_alignment) / 2.0;

        let mut ctx = SymbolicContext::new();
        ctx.set("target_agent", &target_agent);
        ctx.set("agent_context_keys", &agent_keys.len().to_string());
        ctx.set("avg_priority", &format!("{:.3}", avg_priority));
        ctx.set("context_similarity", &format!("{:.3}", context_similarity));
        ctx.set("empathy_score", &format!("{:.3}", empathy_score));

        // Store empathy model
        for (key, value) in empathy_model {
            ctx.set(&format!("empathy_model.{}", key), &value);
        }

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "empathy".to_string(),
            description: "Models the symbolic reasoning state of another agent".to_string(),
            category: "multi-agent".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        1.5
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.12,
            source: "empathy_modeling".to_string(),
        }
    }
}

/// Resolves symbolic value conflicts across multiple agents.
pub struct NegotiateOperator;

impl SomaOperator for NegotiateOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();
        let conflict_key = inputs.resolve_or_default("conflict_key", "goal");

        // Find conflicting values from different agents
        let mut agent_values: HashMap<String, String> = HashMap::new();

        for (key, value) in &context_map {
            if key.contains(&conflict_key) && key.contains("agent_") {
                let agent_id = key.split('.').next().unwrap_or("unknown");
                agent_values.insert(agent_id.to_string(), value.clone());
            }
        }

        let mut ctx = SymbolicContext::new();

        if agent_values.is_empty() {
            ctx.set("negotiation_result", "no_conflicts_found");
            ctx.set("resolution_strategy", "none");
            return Ok(ctx);
        }

        // Apply negotiation strategy
        let strategy = inputs.resolve_or_default("strategy", "consensus");
        let resolved_value = match strategy.as_str() {
            "majority" => {
                // Find most common value
                let mut value_counts: HashMap<String, usize> = HashMap::new();
                for value in agent_values.values() {
                    *value_counts.entry(value.clone()).or_insert(0) += 1;
                }
                value_counts
                    .into_iter()
                    .max_by_key(|(_, count)| *count)
                    .map(|(value, _)| value)
                    .unwrap_or_else(|| "unresolved".to_string())
            }
            "priority" => {
                // Use value from highest priority agent
                let priority_agent = inputs.resolve_or_default("priority_agent", "agent_1");
                agent_values
                    .get(&priority_agent)
                    .cloned()
                    .unwrap_or_else(|| {
                        agent_values
                            .values()
                            .next()
                            .cloned()
                            .unwrap_or_else(|| "unresolved".to_string())
                    })
            }
            "average" => {
                // Numeric average (if applicable)
                let numeric_values: Vec<f64> = agent_values
                    .values()
                    .filter_map(|v| v.parse::<f64>().ok())
                    .collect();
                if !numeric_values.is_empty() {
                    let avg = numeric_values.iter().sum::<f64>() / numeric_values.len() as f64;
                    format!("{:.3}", avg)
                } else {
                    "non_numeric_conflict".to_string()
                }
            }
            _ => {
                // Default consensus: if all agree, use that; otherwise flag as unresolved
                let unique_values: std::collections::HashSet<_> = agent_values.values().collect();
                if unique_values.len() == 1 {
                    unique_values.into_iter().next().unwrap().clone()
                } else {
                    "consensus_failed".to_string()
                }
            }
        };

        ctx.set("conflict_key", &conflict_key);
        ctx.set("agent_count", &agent_values.len().to_string());
        ctx.set("resolution_strategy", &strategy);
        ctx.set("resolved_value", &resolved_value);
        ctx.set(
            "negotiation_result",
            if resolved_value == "unresolved" || resolved_value == "consensus_failed" {
                "failed"
            } else {
                "success"
            },
        );

        // Store individual agent positions
        for (agent, value) in agent_values {
            ctx.set(&format!("position.{}", agent), &value);
        }

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "negotiate".to_string(),
            description: "Resolves symbolic value conflicts across multiple agents".to_string(),
            category: "multi-agent".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        1.8
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.20,
            source: "negotiation_process".to_string(),
        }
    }
}

/// Finds symbolic agreement across diverse agent proposals.
pub struct ConsensusOperator;

impl SomaOperator for ConsensusOperator {
    fn execute(&self, inputs: &SymbolicContext) -> Result<SymbolicContext> {
        let context_map = inputs.flatten();
        let min_agreement = inputs
            .resolve_or_default("min_agreement", "0.6")
            .parse::<f64>()
            .unwrap_or(0.6);

        // Group agent contexts
        let mut agent_contexts: HashMap<String, HashMap<String, String>> = HashMap::new();

        for (key, value) in &context_map {
            if key.contains("agent_") {
                let parts: Vec<&str> = key.split('.').collect();
                if parts.len() >= 2 {
                    let agent_id = parts[0];
                    let context_key = parts[1..].join(".");
                    agent_contexts
                        .entry(agent_id.to_string())
                        .or_insert_with(HashMap::new)
                        .insert(context_key, value.clone());
                }
            }
        }

        let mut consensus_result: HashMap<String, String> = HashMap::new();
        let mut agreement_scores: HashMap<String, f64> = HashMap::new();

        // Find consensus for each context key
        let mut all_keys: std::collections::HashSet<String> = std::collections::HashSet::new();
        for agent_context in agent_contexts.values() {
            all_keys.extend(agent_context.keys().cloned());
        }

        for context_key in all_keys {
            let mut values: Vec<String> = Vec::new();
            for agent_context in agent_contexts.values() {
                if let Some(value) = agent_context.get(&context_key) {
                    values.push(value.clone());
                }
            }

            if values.is_empty() {
                continue;
            }

            // Calculate agreement level
            let unique_values: std::collections::HashSet<_> = values.iter().collect();
            let agreement_ratio = if unique_values.len() == 1 {
                1.0
            } else {
                // Find most common value and its frequency
                let mut value_counts: HashMap<String, usize> = HashMap::new();
                for value in &values {
                    *value_counts.entry(value.clone()).or_insert(0) += 1;
                }
                let max_count = value_counts.values().max().unwrap_or(&0);
                *max_count as f64 / values.len() as f64
            };

            agreement_scores.insert(context_key.clone(), agreement_ratio);

            if agreement_ratio >= min_agreement {
                // Find consensus value (most frequent)
                let mut value_counts: HashMap<String, usize> = HashMap::new();
                for value in &values {
                    *value_counts.entry(value.clone()).or_insert(0) += 1;
                }
                let consensus_value = value_counts
                    .into_iter()
                    .max_by_key(|(_, count)| *count)
                    .map(|(value, _)| value)
                    .unwrap_or_else(|| "no_consensus".to_string());

                consensus_result.insert(context_key, consensus_value);
            }
        }

        // Calculate overall consensus metrics
        let total_keys = agreement_scores.len();
        let consensus_keys = consensus_result.len();
        let avg_agreement: f64 = if total_keys > 0 {
            agreement_scores.values().sum::<f64>() / total_keys as f64
        } else {
            0.0
        };

        let mut ctx = SymbolicContext::new();
        ctx.set("agent_count", &agent_contexts.len().to_string());
        ctx.set("total_keys", &total_keys.to_string());
        ctx.set("consensus_keys", &consensus_keys.to_string());
        ctx.set(
            "consensus_ratio",
            &format!("{:.3}", consensus_keys as f64 / total_keys.max(1) as f64),
        );
        ctx.set("avg_agreement", &format!("{:.3}", avg_agreement));
        ctx.set("min_agreement_threshold", &min_agreement.to_string());

        // Store consensus results
        for (key, value) in consensus_result {
            ctx.set(&format!("consensus.{}", key), &value);
        }

        // Store agreement scores
        for (key, score) in agreement_scores {
            ctx.set(&format!("agreement.{}", key), &format!("{:.3}", score));
        }

        Ok(ctx)
    }

    fn metadata(&self) -> OperatorMetadata {
        OperatorMetadata {
            name: "consensus".to_string(),
            description: "Finds symbolic agreement across diverse agent proposals".to_string(),
            category: "multi-agent".to_string(),
        }
    }

    fn cognitive_cost(&self) -> f64 {
        2.0
    }

    fn uncertainty_propagation(&self) -> UncertaintyModel {
        UncertaintyModel {
            entropy: 0.25,
            source: "consensus_building".to_string(),
        }
    }
}

pub fn default_operator_registry() -> HashMap<String, Box<dyn SomaOperator>> {
    let mut reg: HashMap<String, Box<dyn SomaOperator>> = HashMap::new();

    // Original operators
    reg.insert("add".to_string(), Box::new(AddOperator));
    reg.insert("compose".to_string(), Box::new(ComposeOperator));
    reg.insert("if_then".to_string(), Box::new(IfThenOperator));
    reg.insert("reflect".to_string(), Box::new(ReflectOperator));
    reg.insert("delay".to_string(), Box::new(DelayOperator));

    // 🧠 Uncertainty-aware operators
    reg.insert(
        "uncertainty_propagate".to_string(),
        Box::new(UncertaintyPropagateOperator),
    );
    reg.insert("doubt".to_string(), Box::new(DoubtOperator));

    // 🧬 Meta-cognitive operators
    reg.insert("introspect".to_string(), Box::new(IntrospectOperator));
    reg.insert(
        "cognitive_load".to_string(),
        Box::new(CognitiveLoadOperator),
    );
    reg.insert(
        "attention_focus".to_string(),
        Box::new(AttentionFocusOperator),
    );
    reg.insert(
        "meta_reflective".to_string(),
        Box::new(MetaReflectiveOperator),
    );
    reg.insert(
        "visual_reasoning".to_string(),
        Box::new(VisualReasoningOperator),
    );

    // 🧑‍🤝‍🧑 Inter-agent operators
    reg.insert("empathy".to_string(), Box::new(EmpathyOperator));
    reg.insert("negotiate".to_string(), Box::new(NegotiateOperator));
    reg.insert("consensus".to_string(), Box::new(ConsensusOperator));

    reg
}

// Re-export LLMOperator and llm_registry for plug-and-play LLM integration
pub use crate::llm_operator::{llm_registry, LLMOperator};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::SymbolicContext;

    #[test]
    fn test_add_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("x", "3");
        ctx.set("y", "7");
        let add = registry.get("add").unwrap();
        let result_ctx = add.execute(&ctx).unwrap();
        assert_eq!(result_ctx.get("sum").unwrap(), "10");
    }

    #[test]
    fn test_if_then_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("condition", "true");
        ctx.set("then", "yes");
        ctx.set("else", "no");
        let if_then = registry.get("if_then").unwrap();
        let result_ctx = if_then.execute(&ctx).unwrap();
        assert_eq!(result_ctx.get("result").unwrap(), "yes");
    }

    #[test]
    fn test_reflect_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("key1", "value1");
        ctx.set("key2", "value2");
        let reflect = registry.get("reflect").unwrap();
        let result_ctx = reflect.execute(&ctx).unwrap();
        let summary = result_ctx.get("summary").unwrap();
        assert!(summary.contains("key1"));
        assert!(summary.contains("key2"));
    }

    #[test]
    fn test_delay_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("delay_ms", "50");
        let delay = registry.get("delay").unwrap();
        let result_ctx = delay.execute(&ctx).unwrap();
        assert_eq!(result_ctx.get("delayed").unwrap(), "50ms");
    }

    // === 🧠 UNCERTAINTY-AWARE OPERATOR TESTS ===

    #[test]
    fn test_uncertainty_propagate_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();
        ctx.set("entropy", "0.2");
        ctx.set("confidence", "0.8");
        ctx.set("data", "test_value");

        let op = registry.get("uncertainty_propagate").unwrap();
        let result_ctx = op.execute(&ctx).unwrap();

        assert_eq!(result_ctx.get("uncertainty_source").unwrap(), "propagated");
        assert_eq!(result_ctx.get("data_uncertain").unwrap(), "test_value");

        let propagated_entropy = result_ctx
            .get("propagated_entropy")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(propagated_entropy > 0.2); // Should increase entropy

        let propagated_confidence = result_ctx
            .get("propagated_confidence")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(propagated_confidence < 0.8); // Should decrease confidence
    }

    #[test]
    fn test_doubt_operator() {
        let registry = default_operator_registry();

        // Test low confidence (should flag)
        let mut ctx_low = SymbolicContext::new();
        ctx_low.set("confidence", "0.3");
        ctx_low.set("doubt_threshold", "0.5");

        let doubt = registry.get("doubt").unwrap();
        let result_low = doubt.execute(&ctx_low).unwrap();

        assert_eq!(result_low.get("flagged").unwrap(), "true");
        assert_eq!(result_low.get("verification_required").unwrap(), "true");
        assert_eq!(
            result_low.get("doubt_reason").unwrap(),
            "confidence_below_threshold"
        );

        // Test high confidence (should pass)
        let mut ctx_high = SymbolicContext::new();
        ctx_high.set("confidence", "0.9");
        ctx_high.set("doubt_threshold", "0.5");

        let result_high = doubt.execute(&ctx_high).unwrap();
        assert_eq!(result_high.get("flagged").unwrap(), "false");
        assert_eq!(
            result_high.get("doubt_reason").unwrap(),
            "confidence_acceptable"
        );
    }

    // === 🧬 META-COGNITIVE OPERATOR TESTS ===

    #[test]
    fn test_introspect_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Add multiple context values to test complexity analysis
        for i in 0..15 {
            ctx.set(&format!("key_{}", i), &format!("value_{}", i));
        }

        let introspect = registry.get("introspect").unwrap();
        let result_ctx = introspect.execute(&ctx).unwrap();

        assert_eq!(result_ctx.get("context_size").unwrap(), "15");
        assert!(result_ctx.get("reasoning_depth").is_some());
        assert!(result_ctx.get("complexity_score").is_some());
        assert!(result_ctx.get("bottleneck_detected").is_some());
        assert!(result_ctx.get("introspection_timestamp").is_some());
    }

    #[test]
    fn test_cognitive_load_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Create nested context to test load calculation
        ctx.set("simple", "value");
        ctx.set("nested.key", "nested_value");
        ctx.set("nested.deep.key", "deep_value");
        ctx.set("long_content", &"a".repeat(200)); // Long content

        let cognitive_load = registry.get("cognitive_load").unwrap();
        let result_ctx = cognitive_load.execute(&ctx).unwrap();

        assert_eq!(result_ctx.get("memory_keys").unwrap(), "4");
        assert_eq!(result_ctx.get("nested_keys").unwrap(), "2");
        assert!(result_ctx.get("load_score").is_some());
        assert!(result_ctx.get("load_level").is_some());
        assert!(result_ctx.get("optimization_needed").is_some());

        let load_score = result_ctx
            .get("load_score")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(load_score > 0.0);
    }

    #[test]
    fn test_attention_focus_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Add context with different semantic weights
        ctx.set("goal_primary", "main_objective");
        ctx.set("error_critical", "system_failure");
        ctx.set("result_output", "final_result");
        ctx.set("input_param", "user_input");
        ctx.set("misc_data", "other_info");

        let attention = registry.get("attention_focus").unwrap();
        let result_ctx = attention.execute(&ctx).unwrap();

        assert!(result_ctx.get("attention_targets").is_some());
        assert!(result_ctx.get("avg_attention_weight").is_some());
        assert!(result_ctx.get("focus_target_0").is_some()); // Should have top focus targets
        assert!(result_ctx.get("focus_weight_0").is_some());
        assert!(result_ctx.get("attention_analysis_time").is_some());
    }

    #[test]
    fn test_meta_reflective_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Set up system state for meta-analysis
        ctx.set("operator_count", "15");
        ctx.set("system_uptime", "7200");
        ctx.set("errors_count", "1");
        ctx.set("reasoning_pattern_1", "deep_analysis");
        ctx.set("strategy_optimization", "active");
        ctx.set("nested.reasoning.path", "complex");

        let meta_op = registry.get("meta_reflective").unwrap();
        let result_ctx = meta_op.execute(&ctx).unwrap();

        // Verify meta-analysis outputs
        assert!(result_ctx.get("system_performance_score").is_some());
        assert!(result_ctx.get("reasoning_patterns_detected").is_some());
        assert!(result_ctx.get("symbolic_depth").is_some());
        assert!(result_ctx.get("cognitive_efficiency").is_some());
        assert!(result_ctx.get("emergence_level").is_some());
        assert!(result_ctx.get("introspection_score").is_some());
        assert!(result_ctx.get("meta_cognitive_state").is_some());

        // Verify Θ (Theta) optimization suggestions
        assert!(result_ctx.get("optimization_Θ_0").is_some());

        // Check performance scoring
        let performance = result_ctx
            .get("system_performance_score")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(performance > 0.0 && performance <= 1.0);

        // Verify philosophical alignment with emergence reflection
        let emergence_level = result_ctx.get("emergence_level").unwrap();
        assert!(emergence_level == "high" || emergence_level == "moderate");
    }

    #[test]
    fn test_visual_reasoning_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Test code_diagram analysis
        ctx.set("visual_type", "code_diagram");
        ctx.set("analysis_mode", "architecture");
        ctx.set("visual_content", "class_diagram_with_multiple_classes");

        let visual_reasoning = registry.get("visual_reasoning").unwrap();
        let result_ctx = visual_reasoning.execute(&ctx).unwrap();

        // Verify basic visual analysis outputs
        assert_eq!(result_ctx.get("visual_type").unwrap(), "code_diagram");
        assert!(result_ctx.get("symbolic_elements_count").is_some());
        assert!(result_ctx.get("visual_complexity").is_some());
        assert!(result_ctx.get("conversion_confidence").is_some());
        assert!(result_ctx.get("visual_reasoning_timestamp").is_some());

        // Verify symbolic mapping components
        assert!(result_ctx.get("symbolic_graph_nodes").is_some());
        assert!(result_ctx.get("symbolic_graph_edges").is_some());
        assert!(result_ctx.get("visual_semantic_tags").is_some());
        assert!(result_ctx.get("memory_integration_path").is_some());

        // Test complexity and confidence scoring for code diagrams
        let complexity = result_ctx
            .get("visual_complexity")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(complexity >= 0.0 && complexity <= 1.0);

        let confidence = result_ctx
            .get("conversion_confidence")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(confidence >= 0.6); // Code diagrams should have high confidence

        // Test different visual types
        let mut ctx_screenshot = SymbolicContext::new();
        ctx_screenshot.set("visual_type", "screenshot");
        ctx_screenshot.set("analysis_mode", "ui_analysis");

        let result_screenshot = visual_reasoning.execute(&ctx_screenshot).unwrap();
        assert_eq!(result_screenshot.get("visual_type").unwrap(), "screenshot");

        // Screenshot confidence should be lower than code diagram
        let screenshot_confidence = result_screenshot
            .get("conversion_confidence")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(screenshot_confidence < confidence); // Screenshots are more complex to analyze

        // Test unknown visual type handling
        let mut ctx_unknown = SymbolicContext::new();
        ctx_unknown.set("visual_type", "unknown_format");

        let result_unknown = visual_reasoning.execute(&ctx_unknown).unwrap();
        let unknown_confidence = result_unknown
            .get("conversion_confidence")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(unknown_confidence <= 0.6); // Unknown formats should have lower confidence
    }

    #[test]
    fn test_visual_reasoning_memory_integration() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        ctx.set("visual_type", "architecture");
        ctx.set("analysis_mode", "system_design");
        ctx.set("visual_content", "microservices_architecture_diagram");

        let visual_reasoning = registry.get("visual_reasoning").unwrap();
        let result_ctx = visual_reasoning.execute(&ctx).unwrap();

        // Verify memory integration paths are properly set
        let integration_path = result_ctx.get("memory_integration_path").unwrap();
        assert!(integration_path.contains("visual.architecture.symbolic"));

        // Verify DAG integration points
        assert!(result_ctx.get("dag_integration_points").is_some());
        assert_eq!(result_ctx.get("visual_context_preserved").unwrap(), "true");

        // Test semantic tag generation
        let semantic_tags = result_ctx.get("visual_semantic_tags").unwrap();
        assert!(semantic_tags.contains("architecture"));
        assert!(semantic_tags.contains("system_design"));
    }

    #[test]
    fn test_visual_reasoning_cognitive_cost() {
        let registry = default_operator_registry();
        let visual_reasoning = registry.get("visual_reasoning").unwrap();

        // Visual reasoning should have high cognitive cost due to complex processing
        let cost = visual_reasoning.cognitive_cost();
        assert_eq!(cost, 2.5);

        // Verify it's higher than simpler operators
        let add_op = registry.get("add").unwrap();
        assert!(cost > add_op.cognitive_cost());

        let introspect_op = registry.get("introspect").unwrap();
        assert!(cost > introspect_op.cognitive_cost());
    }

    #[test]
    fn test_visual_reasoning_uncertainty_model() {
        let registry = default_operator_registry();
        let visual_reasoning = registry.get("visual_reasoning").unwrap();

        let uncertainty = visual_reasoning.uncertainty_propagation();
        assert_eq!(uncertainty.entropy, 0.25);
        assert_eq!(uncertainty.source, "visual_to_symbolic_conversion");

        // Visual reasoning should have higher uncertainty than deterministic operators
        let add_op = registry.get("add").unwrap();
        let add_uncertainty = add_op.uncertainty_propagation();
        assert!(uncertainty.entropy > add_uncertainty.entropy);
    }

    #[test]
    fn test_visual_reasoning_multiple_analysis_modes() {
        let registry = default_operator_registry();
        let visual_reasoning = registry.get("visual_reasoning").unwrap();

        // Test diagram mode
        let mut ctx_diagram = SymbolicContext::new();
        ctx_diagram.set("visual_type", "flowchart");
        ctx_diagram.set("analysis_mode", "diagram");
        let result_diagram = visual_reasoning.execute(&ctx_diagram).unwrap();

        // Test ui mode  
        let mut ctx_ui = SymbolicContext::new();
        ctx_ui.set("visual_type", "ui");
        ctx_ui.set("analysis_mode", "interface_analysis");
        let result_ui = visual_reasoning.execute(&ctx_ui).unwrap();

        // Both should succeed but with different complexity scores
        let diagram_complexity = result_diagram
            .get("visual_complexity")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        let ui_complexity = result_ui
            .get("visual_complexity")
            .unwrap()
            .parse::<f64>()
            .unwrap();

        // Different visual types should produce different complexity scores
        assert!(diagram_complexity != ui_complexity);
        assert!(diagram_complexity >= 0.0 && diagram_complexity <= 1.0);
        assert!(ui_complexity >= 0.0 && ui_complexity <= 1.0);
    }

    // === 🧑‍🤝‍🧑 INTER-AGENT OPERATOR TESTS ===

    #[test]
    fn test_empathy_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Set up agent-specific context
        ctx.set("target_agent", "agent_1");
        ctx.set("agent_1.goal", "complete_task");
        ctx.set("agent_1.priority", "2.5");
        ctx.set("agent_1.task", "data_processing");
        ctx.set("agent_2.goal", "monitor_system"); // Different agent data

        let empathy = registry.get("empathy").unwrap();
        let result_ctx = empathy.execute(&ctx).unwrap();

        assert_eq!(result_ctx.get("target_agent").unwrap(), "agent_1");
        assert_eq!(result_ctx.get("agent_context_keys").unwrap(), "3");
        assert!(result_ctx.get("empathy_score").is_some());
        assert!(result_ctx.get("context_similarity").is_some());
        assert_eq!(
            result_ctx.get("empathy_model.goal").unwrap(),
            "complete_task"
        );
        assert_eq!(result_ctx.get("empathy_model.priority").unwrap(), "2.5");
    }

    #[test]
    fn test_negotiate_operator() {
        let registry = default_operator_registry();

        // Test majority negotiation
        let mut ctx_majority = SymbolicContext::new();
        ctx_majority.set("conflict_key", "goal");
        ctx_majority.set("strategy", "majority");
        ctx_majority.set("agent_1.goal", "option_a");
        ctx_majority.set("agent_2.goal", "option_a");
        ctx_majority.set("agent_3.goal", "option_b");

        let negotiate = registry.get("negotiate").unwrap();
        let result_majority = negotiate.execute(&ctx_majority).unwrap();

        assert_eq!(result_majority.get("resolved_value").unwrap(), "option_a");
        assert_eq!(
            result_majority.get("negotiation_result").unwrap(),
            "success"
        );
        assert_eq!(result_majority.get("agent_count").unwrap(), "3");

        // Test no conflicts
        let mut ctx_empty = SymbolicContext::new();
        ctx_empty.set("conflict_key", "nonexistent");

        let result_empty = negotiate.execute(&ctx_empty).unwrap();
        assert_eq!(
            result_empty.get("negotiation_result").unwrap(),
            "no_conflicts_found"
        );

        // Test numeric average
        let mut ctx_numeric = SymbolicContext::new();
        ctx_numeric.set("conflict_key", "score");
        ctx_numeric.set("strategy", "average");
        ctx_numeric.set("agent_1.score", "8.5");
        ctx_numeric.set("agent_2.score", "7.0");
        ctx_numeric.set("agent_3.score", "9.5");

        let result_numeric = negotiate.execute(&ctx_numeric).unwrap();
        let avg_value = result_numeric
            .get("resolved_value")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!((avg_value - 8.333).abs() < 0.01); // Average should be ~8.333
    }

    #[test]
    fn test_consensus_operator() {
        let registry = default_operator_registry();
        let mut ctx = SymbolicContext::new();

        // Set up multi-agent context with agreements and disagreements
        ctx.set("min_agreement", "0.6");
        ctx.set("agent_1.priority", "high");
        ctx.set("agent_2.priority", "high");
        ctx.set("agent_3.priority", "medium"); // Minority opinion
        ctx.set("agent_1.status", "ready");
        ctx.set("agent_2.status", "ready");
        ctx.set("agent_3.status", "ready"); // Full consensus

        let consensus = registry.get("consensus").unwrap();
        let result_ctx = consensus.execute(&ctx).unwrap();

        assert_eq!(result_ctx.get("agent_count").unwrap(), "3");
        assert_eq!(result_ctx.get("total_keys").unwrap(), "2");

        // Should reach consensus on "status" (100% agreement) but not "priority" (66% agreement)
        assert_eq!(result_ctx.get("consensus.status").unwrap(), "ready");
        assert_eq!(result_ctx.get("consensus.priority").unwrap(), "high"); // Majority wins

        let consensus_ratio = result_ctx
            .get("consensus_ratio")
            .unwrap()
            .parse::<f64>()
            .unwrap();
        assert!(consensus_ratio > 0.0);

        assert!(result_ctx.get("avg_agreement").is_some());
        assert_eq!(result_ctx.get("agreement.status").unwrap(), "1.000"); // Perfect agreement
    }

    #[test]
    fn test_new_operators_in_registry() {
        let registry = default_operator_registry();

        // Verify all operators are registered
        let expected_operators = vec![
            "add",
            "compose",
            "if_then",
            "reflect",
            "delay", // Original operators
            "uncertainty_propagate",
            "doubt", // Uncertainty-aware
            "introspect",
            "cognitive_load",
            "attention_focus", // Meta-cognitive
            "meta_reflective",
            "visual_reasoning", // New meta-cognitive operators
            "empathy",
            "negotiate",
            "consensus", // Inter-agent
        ];

        for operator_name in expected_operators {
            assert!(
                registry.contains_key(operator_name),
                "Missing operator: {}",
                operator_name
            );
        }

        // Verify total count includes all operators
        assert_eq!(registry.len(), 15); // Original 5 + 10 cognitive operators

        // Verify metadata is correctly set for existing operators
        let introspect = registry.get("introspect").unwrap();
        let metadata = introspect.metadata();
        assert_eq!(metadata.category, "meta");
        assert_eq!(metadata.name, "introspect");

        let empathy = registry.get("empathy").unwrap();
        let empathy_metadata = empathy.metadata();
        assert_eq!(empathy_metadata.category, "multi-agent");

        let uncertainty = registry.get("uncertainty_propagate").unwrap();
        let uncertainty_metadata = uncertainty.metadata();
        assert_eq!(uncertainty_metadata.category, "uncertainty");

        // Verify the new operators specifically
        let meta_reflective = registry.get("meta_reflective").unwrap();
        let meta_metadata = meta_reflective.metadata();
        assert_eq!(meta_metadata.category, "meta");
        assert_eq!(meta_metadata.name, "meta_reflective");
        assert!(meta_reflective.cognitive_cost() > 1.0);

        let visual_reasoning = registry.get("visual_reasoning").unwrap();
        let visual_metadata = visual_reasoning.metadata();
        assert_eq!(visual_metadata.category, "visual");
        assert_eq!(visual_metadata.name, "visual_reasoning");
        assert!(visual_reasoning.cognitive_cost() > 2.0);
    }
}