ipfrs-tensorlogic 0.2.0

Zero-copy tensor operations and logic programming for content-addressed storage
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
//! Neural-Symbolic Integrator — bridges continuous embedding representations
//! with symbolic logical rule reasoning for hybrid inference.
//!
//! This module implements [`NeuralSymbolicIntegrator`], a production-grade
//! system that combines learned neural patterns with explicit logical rules,
//! enabling inference that benefits from both paradigms.
//!
//! ## Architecture
//!
//! The integrator maintains:
//! - A registry of [`Symbol`]s, each with a name, high-dimensional embedding,
//!   and a base confidence score.
//! - A set of [`LogicalRule`]s that define horn-clause-style implication
//!   relationships between symbols, weighted by confidence and typed by
//!   [`RuleType`].
//!
//! Inference proceeds in three possible modes (controlled by [`InferenceMode`]):
//! - **Pure Symbolic** — forward-chain through rules only.
//! - **Pure Neural** — compute embedding similarity to evidence only.
//! - **Hybrid** — weighted combination of symbolic and neural signals.

use std::collections::HashMap;
use thiserror::Error;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors produced by [`NeuralSymbolicIntegrator`].
#[derive(Debug, Error, Clone, PartialEq)]
pub enum NsError {
    /// A symbol id referenced in a query or rule does not exist.
    #[error("symbol not found: id {0}")]
    SymbolNotFound(usize),

    /// The provided embedding has a different dimension than the integrator was
    /// configured with.
    #[error("dimension mismatch: expected {expected}, got {got}")]
    DimensionMismatch { expected: usize, got: usize },

    /// The symbol registry is full.
    #[error("maximum symbol count reached")]
    MaxSymbolsReached,

    /// A rule references invalid symbol ids or is otherwise structurally
    /// incorrect.
    #[error("invalid rule: {0}")]
    InvalidRule(String),
}

// ---------------------------------------------------------------------------
// Core identifiers and data types
// ---------------------------------------------------------------------------

/// A lightweight newtype wrapper for a symbol index in the integrator's
/// internal registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SymbolId(pub usize);

impl std::fmt::Display for SymbolId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "sym:{}", self.0)
    }
}

/// A named concept with a neural embedding and a base confidence score.
///
/// Symbols are the atomic units of knowledge in the integrator.  Each symbol
/// can participate in logical rules as a head or body atom, and its embedding
/// allows neural similarity to be computed against evidence embeddings.
#[derive(Debug, Clone)]
pub struct Symbol {
    /// Stable identifier within this integrator instance.
    pub id: SymbolId,
    /// Human-readable label.
    pub name: String,
    /// Dense embedding vector; length must equal
    /// [`IntegratorConfig::embedding_dim`].
    pub embedding: Vec<f64>,
    /// Prior confidence that this symbol holds in absence of other evidence;
    /// in `[0.0, 1.0]`.
    pub confidence: f64,
}

/// The flavour of a logical rule, controlling how body satisfaction is
/// translated into rule confidence.
#[derive(Debug, Clone, PartialEq)]
pub enum RuleType {
    /// Classical definite clause — body satisfaction is multiplied by the
    /// rule weight unchanged.
    Definite,
    /// Probabilistic rule — weight is further modulated by the body
    /// satisfaction probability.
    Probabilistic,
    /// Soft rule with temperature-controlled sigmoid.  Lower `temperature`
    /// makes the sigmoid steeper (closer to a step function).
    Soft {
        /// Controls sharpness of the sigmoid applied to body satisfaction.
        temperature: f64,
    },
}

/// A single implication rule: `weight * f(body) → head`.
#[derive(Debug, Clone)]
pub struct LogicalRule {
    /// The symbol that this rule can derive confidence for.
    pub head: SymbolId,
    /// Ordered list of body atoms that must be satisfied.
    pub body: Vec<SymbolId>,
    /// Base weight of the rule; in `(0.0, 1.0]` by convention.
    pub weight: f64,
    /// Determines the transfer function from body satisfaction to rule
    /// confidence.
    pub rule_type: RuleType,
}

// ---------------------------------------------------------------------------
// Query / result types
// ---------------------------------------------------------------------------

/// Selects which inference strategy the integrator uses when answering a
/// [`NsQuery`].
#[derive(Debug, Clone, PartialEq)]
pub enum InferenceMode {
    /// Only symbolic forward-chaining through rules.
    PureSymbolic,
    /// Only neural embedding similarity.
    PureNeural,
    /// Weighted blend: `neural_weight * neural + (1 - neural_weight) *
    /// symbolic`.
    Hybrid {
        /// Weight given to the neural signal; must be in `[0.0, 1.0]`.
        neural_weight: f64,
    },
}

/// A query to the integrator asking for the confidence of a target symbol
/// given some observed evidence.
#[derive(Debug, Clone)]
pub struct NsQuery {
    /// The symbol whose confidence we want to estimate.
    pub target: SymbolId,
    /// Observed symbols and their associated confidence values.
    pub evidence: Vec<(SymbolId, f64)>,
    /// Which inference strategy to apply.
    pub mode: InferenceMode,
}

/// The answer returned by [`NeuralSymbolicIntegrator::infer`].
#[derive(Debug, Clone)]
pub struct NsResult {
    /// The queried symbol.
    pub symbol: SymbolId,
    /// Combined confidence estimate produced by the chosen inference mode.
    pub confidence: f64,
    /// Human-readable strings describing the rules or similarities that
    /// contributed to this result.
    pub explanation: Vec<String>,
    /// The raw neural (embedding-similarity) component of the confidence.
    pub neural_contribution: f64,
    /// The raw symbolic (forward-chaining) component of the confidence.
    pub symbolic_contribution: f64,
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration parameters for [`NeuralSymbolicIntegrator`].
#[derive(Debug, Clone)]
pub struct IntegratorConfig {
    /// Dimensionality that every symbol embedding must have.
    pub embedding_dim: usize,
    /// Hard cap on the number of symbols that can be registered.
    pub max_symbols: usize,
    /// Maximum recursion depth during symbolic forward-chaining.
    pub inference_depth: usize,
    /// Cosine-similarity threshold below which a symbol is not considered a
    /// *similar* symbol in [`NeuralSymbolicIntegrator::similar_symbols`].
    pub similarity_threshold: f64,
}

impl Default for IntegratorConfig {
    fn default() -> Self {
        Self {
            embedding_dim: 128,
            max_symbols: 10_000,
            inference_depth: 5,
            similarity_threshold: 0.7,
        }
    }
}

// ---------------------------------------------------------------------------
// Statistics
// ---------------------------------------------------------------------------

/// Aggregate statistics for a [`NeuralSymbolicIntegrator`] instance.
#[derive(Debug, Clone, PartialEq)]
pub struct NsStats {
    /// Number of registered symbols.
    pub symbol_count: usize,
    /// Number of registered rules.
    pub rule_count: usize,
    /// Total number of inference calls that have completed successfully.
    pub total_inferences: u64,
    /// Mean L2 norm of all symbol embeddings; useful for sanity-checking that
    /// embeddings are properly normalised.
    pub avg_embedding_norm: f64,
}

// ---------------------------------------------------------------------------
// Main integrator
// ---------------------------------------------------------------------------

/// A production-grade neural-symbolic integration engine.
///
/// Maintains a registry of [`Symbol`]s with continuous embeddings alongside
/// a set of weighted [`LogicalRule`]s.  Inference combines cosine-similarity
/// lookup (neural path) with forward-chaining through rules (symbolic path).
///
/// # Thread safety
///
/// `NeuralSymbolicIntegrator` is **not** `Sync` by default because `infer`
/// takes `&mut self` to update the `total_inferences` counter.  Wrap in a
/// `Mutex` or `RwLock` for shared concurrent access.
pub struct NeuralSymbolicIntegrator {
    /// Configuration that was provided at construction time.
    pub config: IntegratorConfig,
    /// All registered symbols, indexed by their [`SymbolId`].
    pub symbols: Vec<Symbol>,
    /// All registered rules.
    pub rules: Vec<LogicalRule>,
    /// Monotonically increasing counter of successful `infer` calls.
    pub total_inferences: u64,
}

impl NeuralSymbolicIntegrator {
    // -----------------------------------------------------------------------
    // Construction
    // -----------------------------------------------------------------------

    /// Create a new, empty integrator with the given configuration.
    pub fn new(config: IntegratorConfig) -> Self {
        Self {
            config,
            symbols: Vec::new(),
            rules: Vec::new(),
            total_inferences: 0,
        }
    }

    // -----------------------------------------------------------------------
    // Registry management
    // -----------------------------------------------------------------------

    /// Register a new symbol.
    ///
    /// # Errors
    ///
    /// Returns [`NsError::MaxSymbolsReached`] when the symbol count would
    /// exceed [`IntegratorConfig::max_symbols`].
    ///
    /// Returns [`NsError::DimensionMismatch`] when `embedding.len()` differs
    /// from [`IntegratorConfig::embedding_dim`].
    pub fn add_symbol(
        &mut self,
        name: String,
        embedding: Vec<f64>,
        confidence: f64,
    ) -> Result<SymbolId, NsError> {
        if self.symbols.len() >= self.config.max_symbols {
            return Err(NsError::MaxSymbolsReached);
        }
        if embedding.len() != self.config.embedding_dim {
            return Err(NsError::DimensionMismatch {
                expected: self.config.embedding_dim,
                got: embedding.len(),
            });
        }
        let id = SymbolId(self.symbols.len());
        self.symbols.push(Symbol {
            id,
            name,
            embedding,
            confidence: confidence.clamp(0.0, 1.0),
        });
        Ok(id)
    }

    /// Register a logical rule.
    ///
    /// # Errors
    ///
    /// Returns [`NsError::InvalidRule`] if the head or any body symbol does
    /// not exist in the registry.
    pub fn add_rule(&mut self, rule: LogicalRule) -> Result<(), NsError> {
        if rule.head.0 >= self.symbols.len() {
            return Err(NsError::InvalidRule(format!(
                "head symbol {} does not exist",
                rule.head.0
            )));
        }
        for &body_sym in &rule.body {
            if body_sym.0 >= self.symbols.len() {
                return Err(NsError::InvalidRule(format!(
                    "body symbol {} does not exist",
                    body_sym.0
                )));
            }
        }
        self.rules.push(rule);
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Neural helpers
    // -----------------------------------------------------------------------

    /// Compute the cosine similarity between two embedding vectors.
    ///
    /// Returns `0.0` when either vector has zero norm (to avoid division by
    /// zero) and clamps the result to `[-1.0, 1.0]`.
    pub fn neural_similarity(a: &[f64], b: &[f64]) -> f64 {
        debug_assert_eq!(a.len(), b.len(), "embedding dimension mismatch");
        let dot: f64 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let norm_a: f64 = a.iter().map(|x| x * x).sum::<f64>().sqrt();
        let norm_b: f64 = b.iter().map(|x| x * x).sum::<f64>().sqrt();
        if norm_a == 0.0 || norm_b == 0.0 {
            return 0.0;
        }
        (dot / (norm_a * norm_b)).clamp(-1.0, 1.0)
    }

    // -----------------------------------------------------------------------
    // Symbolic inference
    // -----------------------------------------------------------------------

    /// Forward-chain through rules to estimate confidence in `target`.
    ///
    /// Recursively resolves body atoms up to `depth` levels deep.  Each call
    /// collects evidence from the provided map, multiplies body atoms to obtain
    /// body satisfaction, applies the rule-type transfer function, and returns
    /// the maximum confidence obtained across all matching rules.
    ///
    /// # Arguments
    ///
    /// * `target` — the symbol whose confidence we are computing.
    /// * `evidence` — the set of directly observed (symbol, confidence) pairs.
    /// * `depth` — remaining recursion budget.
    pub fn symbolic_forward_chain(
        &self,
        target: SymbolId,
        evidence: &[(SymbolId, f64)],
        depth: usize,
    ) -> f64 {
        // Build a lookup map from the evidence slice.
        let ev_map: HashMap<usize, f64> = evidence.iter().map(|(s, c)| (s.0, *c)).collect();
        self.symbolic_chain_inner(target, &ev_map, depth)
    }

    /// Internal recursive implementation of symbolic forward chaining.
    fn symbolic_chain_inner(
        &self,
        target: SymbolId,
        ev_map: &HashMap<usize, f64>,
        depth: usize,
    ) -> f64 {
        // Check direct evidence first.
        if let Some(&conf) = ev_map.get(&target.0) {
            return conf;
        }

        if depth == 0 {
            // At the recursion limit, fall back to the symbol's own confidence.
            return self
                .symbols
                .get(target.0)
                .map(|s| s.confidence)
                .unwrap_or(0.0);
        }

        let mut best: f64 = 0.0;

        for rule in &self.rules {
            if rule.head != target {
                continue;
            }
            if rule.body.is_empty() {
                // A fact (empty body) — body satisfaction is 1.0 (vacuously
                // true), so apply the transfer function with full satisfaction.
                let adjusted = self.apply_rule_type(rule, 1.0, rule.weight);
                if adjusted > best {
                    best = adjusted;
                }
                continue;
            }

            // Compute body satisfaction as the product of each body atom's
            // confidence, resolved recursively.
            let body_satisfaction: f64 = rule.body.iter().fold(1.0, |acc, &body_sym| {
                let body_conf = self.symbolic_chain_inner(body_sym, ev_map, depth - 1);
                acc * body_conf
            });

            let rule_confidence = self.apply_rule_type(rule, body_satisfaction, rule.weight);

            if rule_confidence > best {
                best = rule_confidence;
            }
        }

        best
    }

    /// Apply the [`RuleType`] transfer function to obtain the final rule
    /// confidence from the body satisfaction and rule weight.
    fn apply_rule_type(
        &self,
        rule: &LogicalRule,
        body_satisfaction: f64,
        _base_weight: f64,
    ) -> f64 {
        match &rule.rule_type {
            RuleType::Definite => rule.weight * body_satisfaction,
            RuleType::Probabilistic => rule.weight * body_satisfaction * body_satisfaction,
            RuleType::Soft { temperature } => {
                let temp = temperature.max(f64::EPSILON);
                let sigmoid_input = body_satisfaction / temp;
                let sigmoid = 1.0 / (1.0 + (-sigmoid_input).exp());
                rule.weight * sigmoid
            }
        }
    }

    // -----------------------------------------------------------------------
    // Neural inference
    // -----------------------------------------------------------------------

    /// Estimate confidence in `target` purely via embedding similarity.
    ///
    /// For each evidence pair `(sym, conf)`, computes
    /// `neural_similarity(target.embedding, sym.embedding) * conf` and returns
    /// the maximum across all evidence items.  Returns `0.0` when `target`
    /// does not exist or there is no evidence.
    pub fn neural_forward(&self, target: SymbolId, evidence: &[(SymbolId, f64)]) -> f64 {
        let target_sym = match self.symbols.get(target.0) {
            Some(s) => s,
            None => return 0.0,
        };

        let mut best: f64 = 0.0;
        for &(ev_sym_id, conf) in evidence {
            if let Some(ev_sym) = self.symbols.get(ev_sym_id.0) {
                let sim = Self::neural_similarity(&target_sym.embedding, &ev_sym.embedding);
                let score = sim * conf;
                if score > best {
                    best = score;
                }
            }
        }
        best
    }

    // -----------------------------------------------------------------------
    // Main inference entry point
    // -----------------------------------------------------------------------

    /// Answer an [`NsQuery`] using the specified [`InferenceMode`].
    ///
    /// # Errors
    ///
    /// Returns [`NsError::SymbolNotFound`] when `query.target` does not exist.
    pub fn infer(&mut self, query: &NsQuery) -> Result<NsResult, NsError> {
        // Validate target.
        if query.target.0 >= self.symbols.len() {
            return Err(NsError::SymbolNotFound(query.target.0));
        }

        let symbolic =
            self.symbolic_forward_chain(query.target, &query.evidence, self.config.inference_depth);
        let neural = self.neural_forward(query.target, &query.evidence);

        let combined = match &query.mode {
            InferenceMode::PureSymbolic => symbolic,
            InferenceMode::PureNeural => neural,
            InferenceMode::Hybrid { neural_weight } => {
                let nw = neural_weight.clamp(0.0, 1.0);
                nw * neural + (1.0 - nw) * symbolic
            }
        };

        // Collect explanation strings.
        let explanation = self.build_explanation(query.target, &query.evidence);

        self.total_inferences += 1;

        Ok(NsResult {
            symbol: query.target,
            confidence: combined.clamp(0.0, 1.0),
            explanation,
            neural_contribution: neural,
            symbolic_contribution: symbolic,
        })
    }

    /// Build a list of human-readable strings describing which rules
    /// contributed to the inference for `target`.
    fn build_explanation(&self, target: SymbolId, evidence: &[(SymbolId, f64)]) -> Vec<String> {
        let mut explanations: Vec<String> = Vec::new();

        // Identify contributing rules.
        for rule in &self.rules {
            if rule.head != target {
                continue;
            }
            let body_names: Vec<String> = rule
                .body
                .iter()
                .map(|b| {
                    self.symbols
                        .get(b.0)
                        .map(|s| s.name.clone())
                        .unwrap_or_else(|| format!("sym:{}", b.0))
                })
                .collect();
            let head_name = self
                .symbols
                .get(target.0)
                .map(|s| s.name.clone())
                .unwrap_or_else(|| format!("sym:{}", target.0));
            let body_str = if body_names.is_empty() {
                "".to_string()
            } else {
                body_names.join(", ")
            };
            explanations.push(format!(
                "rule_{}_from_[{}] (weight={:.3})",
                head_name, body_str, rule.weight
            ));
        }

        // Identify contributing neural evidence.
        if let Some(target_sym) = self.symbols.get(target.0) {
            for &(ev_id, conf) in evidence {
                if let Some(ev_sym) = self.symbols.get(ev_id.0) {
                    let sim = Self::neural_similarity(&target_sym.embedding, &ev_sym.embedding);
                    if sim > 0.0 {
                        explanations.push(format!(
                            "neural_similarity({}, {})={:.3} × conf={:.3}",
                            target_sym.name, ev_sym.name, sim, conf
                        ));
                    }
                }
            }
        }

        explanations
    }

    // -----------------------------------------------------------------------
    // Utility methods
    // -----------------------------------------------------------------------

    /// Return human-readable strings describing every rule whose head or body
    /// involves `id`.
    ///
    /// # Errors
    ///
    /// Returns [`NsError::SymbolNotFound`] if `id` is not registered.
    pub fn explain_symbol(&self, id: SymbolId) -> Result<Vec<String>, NsError> {
        if id.0 >= self.symbols.len() {
            return Err(NsError::SymbolNotFound(id.0));
        }
        let sym_name = &self.symbols[id.0].name;
        let mut lines: Vec<String> = Vec::new();
        for rule in &self.rules {
            if rule.head == id || rule.body.contains(&id) {
                let head_name = self
                    .symbols
                    .get(rule.head.0)
                    .map(|s| s.name.as_str())
                    .unwrap_or("?");
                let body_names: Vec<&str> = rule
                    .body
                    .iter()
                    .map(|b| {
                        self.symbols
                            .get(b.0)
                            .map(|s| s.name.as_str())
                            .unwrap_or("?")
                    })
                    .collect();
                lines.push(format!(
                    "{} ← [{}] (w={:.3}, {:?})",
                    head_name,
                    body_names.join(", "),
                    rule.weight,
                    rule.rule_type
                ));
            }
        }
        if lines.is_empty() {
            lines.push(format!("'{}' has no associated rules", sym_name));
        }
        Ok(lines)
    }

    /// Return the top-`k` symbols most similar (by cosine similarity) to the
    /// embedding of `id`, sorted by descending similarity.
    ///
    /// Only symbols with similarity ≥ [`IntegratorConfig::similarity_threshold`]
    /// are included.  The queried symbol itself is excluded.
    ///
    /// # Errors
    ///
    /// Returns [`NsError::SymbolNotFound`] if `id` is not registered.
    pub fn similar_symbols(&self, id: SymbolId, k: usize) -> Result<Vec<(SymbolId, f64)>, NsError> {
        if id.0 >= self.symbols.len() {
            return Err(NsError::SymbolNotFound(id.0));
        }
        let query_emb = &self.symbols[id.0].embedding;
        let threshold = self.config.similarity_threshold;

        let mut scored: Vec<(SymbolId, f64)> = self
            .symbols
            .iter()
            .filter(|s| s.id != id)
            .map(|s| {
                let sim = Self::neural_similarity(query_emb, &s.embedding);
                (s.id, sim)
            })
            .filter(|(_, sim)| *sim >= threshold)
            .collect();

        // Sort by descending similarity, then by symbol id for determinism.
        scored.sort_by(|a, b| {
            b.1.partial_cmp(&a.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.0.cmp(&b.0))
        });
        scored.truncate(k);
        Ok(scored)
    }

    /// Return aggregate statistics for this integrator.
    pub fn stats(&self) -> NsStats {
        let avg_embedding_norm = if self.symbols.is_empty() {
            0.0
        } else {
            let total_norm: f64 = self
                .symbols
                .iter()
                .map(|s| s.embedding.iter().map(|x| x * x).sum::<f64>().sqrt())
                .sum();
            total_norm / self.symbols.len() as f64
        };
        NsStats {
            symbol_count: self.symbols.len(),
            rule_count: self.rules.len(),
            total_inferences: self.total_inferences,
            avg_embedding_norm,
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::{
        InferenceMode, IntegratorConfig, LogicalRule, NeuralSymbolicIntegrator, NsError, NsQuery,
        RuleType, SymbolId,
    };

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    /// Build a unit vector of the given dimension with component `val`.
    fn uniform_emb(dim: usize, val: f64) -> Vec<f64> {
        let norm = (dim as f64 * val * val).sqrt();
        if norm == 0.0 {
            return vec![0.0; dim];
        }
        vec![val / norm; dim]
    }

    /// Build a standard-basis embedding with 1.0 at position `idx`.
    fn basis_emb(dim: usize, idx: usize) -> Vec<f64> {
        let mut v = vec![0.0; dim];
        if idx < dim {
            v[idx] = 1.0;
        }
        v
    }

    fn default_integrator() -> NeuralSymbolicIntegrator {
        NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 4,
            max_symbols: 100,
            inference_depth: 5,
            similarity_threshold: 0.5,
        })
    }

    // -----------------------------------------------------------------------
    // SymbolId tests
    // -----------------------------------------------------------------------

    #[test]
    fn symbol_id_display() {
        let id = SymbolId(42);
        assert_eq!(id.to_string(), "sym:42");
    }

    #[test]
    fn symbol_id_ordering() {
        assert!(SymbolId(0) < SymbolId(1));
        assert!(SymbolId(5) > SymbolId(3));
        assert_eq!(SymbolId(7), SymbolId(7));
    }

    // -----------------------------------------------------------------------
    // add_symbol tests
    // -----------------------------------------------------------------------

    #[test]
    fn add_symbol_returns_sequential_ids() {
        let mut ig = default_integrator();
        let id0 = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.9)
            .expect("test setup: add symbol 'a'");
        let id1 = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.8)
            .expect("test setup: add symbol 'b'");
        assert_eq!(id0, SymbolId(0));
        assert_eq!(id1, SymbolId(1));
    }

    #[test]
    fn add_symbol_dimension_mismatch() {
        let mut ig = default_integrator();
        let err = ig.add_symbol("x".into(), vec![0.1, 0.2], 0.5).unwrap_err();
        assert_eq!(
            err,
            NsError::DimensionMismatch {
                expected: 4,
                got: 2
            }
        );
    }

    #[test]
    fn add_symbol_max_reached() {
        let mut ig = NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 2,
            max_symbols: 2,
            inference_depth: 3,
            similarity_threshold: 0.5,
        });
        ig.add_symbol("a".into(), vec![1.0, 0.0], 1.0)
            .expect("test setup: add symbol 'a'");
        ig.add_symbol("b".into(), vec![0.0, 1.0], 1.0)
            .expect("test setup: add symbol 'b'");
        let err = ig.add_symbol("c".into(), vec![0.5, 0.5], 1.0).unwrap_err();
        assert_eq!(err, NsError::MaxSymbolsReached);
    }

    #[test]
    fn add_symbol_clamps_confidence() {
        let mut ig = default_integrator();
        let id = ig
            .add_symbol("over".into(), basis_emb(4, 0), 1.5)
            .expect("test setup: add symbol 'over'");
        assert!((ig.symbols[id.0].confidence - 1.0).abs() < 1e-9);
        let id2 = ig
            .add_symbol("neg".into(), basis_emb(4, 1), -0.3)
            .expect("test setup: add symbol 'neg'");
        assert!((ig.symbols[id2.0].confidence).abs() < 1e-9);
    }

    // -----------------------------------------------------------------------
    // add_rule tests
    // -----------------------------------------------------------------------

    #[test]
    fn add_rule_valid() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        let result = ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.8,
            rule_type: RuleType::Definite,
        });
        assert!(result.is_ok());
    }

    #[test]
    fn add_rule_invalid_head() {
        let mut ig = default_integrator();
        let err = ig
            .add_rule(LogicalRule {
                head: SymbolId(99),
                body: vec![],
                weight: 1.0,
                rule_type: RuleType::Definite,
            })
            .unwrap_err();
        assert!(matches!(err, NsError::InvalidRule(_)));
    }

    #[test]
    fn add_rule_invalid_body_sym() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let err = ig
            .add_rule(LogicalRule {
                head: a,
                body: vec![SymbolId(50)],
                weight: 0.9,
                rule_type: RuleType::Probabilistic,
            })
            .unwrap_err();
        assert!(matches!(err, NsError::InvalidRule(_)));
    }

    // -----------------------------------------------------------------------
    // neural_similarity tests
    // -----------------------------------------------------------------------

    #[test]
    fn neural_similarity_identical() {
        let v = vec![1.0, 0.0, 0.0, 0.0];
        let sim = NeuralSymbolicIntegrator::neural_similarity(&v, &v);
        assert!((sim - 1.0).abs() < 1e-10);
    }

    #[test]
    fn neural_similarity_orthogonal() {
        let a = vec![1.0, 0.0];
        let b = vec![0.0, 1.0];
        let sim = NeuralSymbolicIntegrator::neural_similarity(&a, &b);
        assert!(sim.abs() < 1e-10);
    }

    #[test]
    fn neural_similarity_opposite() {
        let a = vec![1.0, 0.0];
        let b = vec![-1.0, 0.0];
        let sim = NeuralSymbolicIntegrator::neural_similarity(&a, &b);
        assert!((sim + 1.0).abs() < 1e-10);
    }

    #[test]
    fn neural_similarity_zero_vector() {
        let a = vec![0.0, 0.0];
        let b = vec![1.0, 0.0];
        let sim = NeuralSymbolicIntegrator::neural_similarity(&a, &b);
        assert_eq!(sim, 0.0);
    }

    #[test]
    fn neural_similarity_partial() {
        let a = vec![1.0, 1.0];
        let b = vec![1.0, 0.0];
        let sim = NeuralSymbolicIntegrator::neural_similarity(&a, &b);
        let expected = 1.0 / 2.0_f64.sqrt();
        assert!((sim - expected).abs() < 1e-10);
    }

    #[test]
    fn neural_similarity_clamp() {
        // Vectors that are exactly parallel should give similarity 1.0;
        // and the result must be in [-1, 1].
        let a = vec![3.0, 4.0];
        let b = vec![6.0, 8.0]; // same direction, double magnitude
        let sim = NeuralSymbolicIntegrator::neural_similarity(&a, &b);
        assert!(sim <= 1.0);
        assert!(sim >= -1.0);
        assert!((sim - 1.0).abs() < 1e-10);
    }

    // -----------------------------------------------------------------------
    // symbolic_forward_chain tests
    // -----------------------------------------------------------------------

    #[test]
    fn symbolic_chain_direct_evidence() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.5)
            .expect("test setup: add symbol 'a'");
        // Direct evidence overrides symbol confidence.
        let conf = ig.symbolic_forward_chain(a, &[(a, 0.9)], 3);
        assert!((conf - 0.9).abs() < 1e-10);
    }

    #[test]
    fn symbolic_chain_simple_rule_definite() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.9,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let conf = ig.symbolic_forward_chain(a, &[(b, 1.0)], 3);
        // Definite: 0.9 * 1.0 = 0.9
        assert!((conf - 0.9).abs() < 1e-9);
    }

    #[test]
    fn symbolic_chain_probabilistic_rule() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Probabilistic,
        })
        .expect("test setup: add probabilistic rule a <- b");
        let conf = ig.symbolic_forward_chain(a, &[(b, 0.8)], 3);
        // Probabilistic: 1.0 * 0.8 * 0.8 = 0.64
        assert!((conf - 0.64).abs() < 1e-9);
    }

    #[test]
    fn symbolic_chain_soft_rule() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Soft { temperature: 1.0 },
        })
        .expect("test setup: add soft rule a <- b");
        let conf = ig.symbolic_forward_chain(a, &[(b, 1.0)], 3);
        // Soft: sigmoid(1.0/1.0) = 1/(1+e^-1) ≈ 0.731
        let expected = 1.0 / (1.0 + (-1.0_f64).exp());
        assert!((conf - expected).abs() < 1e-9);
    }

    #[test]
    fn symbolic_chain_empty_body_fact() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![],
            weight: 0.7,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add fact rule for 'a'");
        // An empty-body rule acts as a fact.
        let conf = ig.symbolic_forward_chain(a, &[], 3);
        assert!((conf - 0.7).abs() < 1e-9);
    }

    #[test]
    fn symbolic_chain_depth_limit() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        // depth=0 and no direct evidence → falls back to symbol confidence (0.0)
        let conf = ig.symbolic_forward_chain(a, &[], 0);
        assert_eq!(conf, 0.0);
    }

    #[test]
    fn symbolic_chain_multi_body() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        let c = ig
            .add_symbol("c".into(), basis_emb(4, 2), 0.0)
            .expect("test setup: add symbol 'c'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b, c],
            weight: 1.0,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b, c");
        // body_satisfaction = 0.8 * 0.6 = 0.48; result = 1.0 * 0.48
        let conf = ig.symbolic_forward_chain(a, &[(b, 0.8), (c, 0.6)], 3);
        assert!((conf - 0.48).abs() < 1e-9);
    }

    // -----------------------------------------------------------------------
    // neural_forward tests
    // -----------------------------------------------------------------------

    #[test]
    fn neural_forward_no_evidence() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        assert_eq!(ig.neural_forward(a, &[]), 0.0);
    }

    #[test]
    fn neural_forward_identical_embedding() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'b'");
        let score = ig.neural_forward(a, &[(b, 0.9)]);
        // similarity = 1.0, result = 1.0 * 0.9 = 0.9
        assert!((score - 0.9).abs() < 1e-9);
    }

    #[test]
    fn neural_forward_orthogonal_embedding() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        let score = ig.neural_forward(a, &[(b, 1.0)]);
        assert!(score.abs() < 1e-10);
    }

    #[test]
    fn neural_forward_invalid_target() {
        let ig = default_integrator();
        // No symbols registered → returns 0.0 gracefully.
        assert_eq!(ig.neural_forward(SymbolId(99), &[]), 0.0);
    }

    // -----------------------------------------------------------------------
    // infer tests
    // -----------------------------------------------------------------------

    #[test]
    fn infer_pure_symbolic() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let query = NsQuery {
            target: a,
            evidence: vec![(b, 1.0)],
            mode: InferenceMode::PureSymbolic,
        };
        let result = ig.infer(&query).expect("test setup: infer pure symbolic");
        assert!((result.confidence - 1.0).abs() < 1e-9);
        assert!((result.symbolic_contribution - 1.0).abs() < 1e-9);
    }

    #[test]
    fn infer_pure_neural() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'b'");
        let query = NsQuery {
            target: a,
            evidence: vec![(b, 0.7)],
            mode: InferenceMode::PureNeural,
        };
        let result = ig.infer(&query).expect("test setup: infer pure neural");
        // similarity=1.0, conf=0.7 → neural=0.7
        assert!((result.confidence - 0.7).abs() < 1e-9);
        assert!((result.neural_contribution - 0.7).abs() < 1e-9);
    }

    #[test]
    fn infer_hybrid() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        // Rule: a ← b, weight=1.0
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        // Evidence: b=1.0, but a and b are orthogonal so neural=0
        let query = NsQuery {
            target: a,
            evidence: vec![(b, 1.0)],
            mode: InferenceMode::Hybrid { neural_weight: 0.5 },
        };
        let result = ig.infer(&query).expect("test setup: infer hybrid");
        // symbolic=1.0, neural≈0.0, hybrid=0.5*0 + 0.5*1.0 = 0.5
        assert!((result.confidence - 0.5).abs() < 1e-9);
    }

    #[test]
    fn infer_target_not_found() {
        let mut ig = default_integrator();
        let query = NsQuery {
            target: SymbolId(99),
            evidence: vec![],
            mode: InferenceMode::PureSymbolic,
        };
        assert_eq!(ig.infer(&query).unwrap_err(), NsError::SymbolNotFound(99));
    }

    #[test]
    fn infer_increments_counter() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let query = NsQuery {
            target: a,
            evidence: vec![],
            mode: InferenceMode::PureSymbolic,
        };
        ig.infer(&query).expect("test setup: first infer call");
        ig.infer(&query).expect("test setup: second infer call");
        assert_eq!(ig.total_inferences, 2);
    }

    #[test]
    fn infer_result_confidence_clamped() {
        // Rule weight > 1.0 should still produce clamped result.
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![],
            weight: 2.0, // intentionally > 1
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule with weight > 1");
        let query = NsQuery {
            target: a,
            evidence: vec![],
            mode: InferenceMode::PureSymbolic,
        };
        let result = ig
            .infer(&query)
            .expect("test setup: infer with oversized weight");
        assert!(result.confidence <= 1.0);
    }

    #[test]
    fn infer_explanation_nonempty_for_matching_rule() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.9,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let query = NsQuery {
            target: a,
            evidence: vec![(b, 1.0)],
            mode: InferenceMode::PureSymbolic,
        };
        let result = ig.infer(&query).expect("test setup: infer for explanation");
        assert!(!result.explanation.is_empty());
        let rule_exp = result
            .explanation
            .iter()
            .any(|e| e.contains("rule_a_from_"));
        assert!(
            rule_exp,
            "expected rule explanation, got: {:?}",
            result.explanation
        );
    }

    // -----------------------------------------------------------------------
    // explain_symbol tests
    // -----------------------------------------------------------------------

    #[test]
    fn explain_symbol_not_found() {
        let ig = default_integrator();
        assert_eq!(
            ig.explain_symbol(SymbolId(0)),
            Err(NsError::SymbolNotFound(0))
        );
    }

    #[test]
    fn explain_symbol_no_rules() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let lines = ig
            .explain_symbol(a)
            .expect("test setup: explain symbol 'a'");
        assert!(!lines.is_empty());
        assert!(lines[0].contains("no associated rules"));
    }

    #[test]
    fn explain_symbol_as_head() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.8,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let lines = ig
            .explain_symbol(a)
            .expect("test setup: explain symbol 'a'");
        assert!(lines.iter().any(|l| l.contains("a ←")));
    }

    #[test]
    fn explain_symbol_as_body() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.8,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        // b appears in the body; explain_symbol(b) should mention it.
        let lines = ig
            .explain_symbol(b)
            .expect("test setup: explain symbol 'b'");
        assert!(lines.iter().any(|l| l.contains('b')));
    }

    // -----------------------------------------------------------------------
    // similar_symbols tests
    // -----------------------------------------------------------------------

    #[test]
    fn similar_symbols_not_found() {
        let ig = default_integrator();
        assert_eq!(
            ig.similar_symbols(SymbolId(99), 5),
            Err(NsError::SymbolNotFound(99))
        );
    }

    #[test]
    fn similar_symbols_returns_top_k() {
        let mut ig = NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 4,
            max_symbols: 100,
            inference_depth: 3,
            similarity_threshold: 0.0, // accept all
        });
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let _b = ig
            .add_symbol("b".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'b'"); // sim=1
        let _c = ig
            .add_symbol("c".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'c'"); // sim=1
        let _d = ig
            .add_symbol("d".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'd'"); // sim=0

        let results = ig
            .similar_symbols(a, 2)
            .expect("test setup: similar symbols for 'a'");
        // Should return at most 2 entries.
        assert!(results.len() <= 2);
    }

    #[test]
    fn similar_symbols_excludes_self() {
        let mut ig = NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 4,
            max_symbols: 100,
            inference_depth: 3,
            similarity_threshold: 0.0,
        });
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let results = ig
            .similar_symbols(a, 10)
            .expect("test setup: similar symbols for 'a'");
        // Only `a` is registered — no results possible.
        assert!(results.is_empty());
    }

    #[test]
    fn similar_symbols_threshold_filters() {
        let mut ig = NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 4,
            max_symbols: 100,
            inference_depth: 3,
            similarity_threshold: 0.9, // very high threshold
        });
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        // b is not identical → similarity < 1.0 with basis vectors...
        // but let us use an orthogonal one to ensure it's filtered.
        let _b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        let results = ig
            .similar_symbols(a, 10)
            .expect("test setup: similar symbols for 'a'");
        assert!(
            results.is_empty(),
            "orthogonal vector should be below threshold"
        );
    }

    #[test]
    fn similar_symbols_sorted_desc() {
        let mut ig = NeuralSymbolicIntegrator::new(IntegratorConfig {
            embedding_dim: 4,
            max_symbols: 100,
            inference_depth: 3,
            similarity_threshold: 0.0,
        });
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        // b has high similarity (same direction), c has lower.
        ig.add_symbol("b".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'b'");
        let partial: Vec<f64> = {
            let mut v = vec![0.0; 4];
            v[0] = 0.7;
            v[1] = 0.3;
            // normalise
            let norm = (0.7_f64 * 0.7 + 0.3_f64 * 0.3).sqrt();
            v.iter_mut().for_each(|x| *x /= norm);
            v
        };
        ig.add_symbol("c".into(), partial, 1.0)
            .expect("test setup: add symbol 'c'");
        let results = ig
            .similar_symbols(a, 10)
            .expect("test setup: similar symbols for 'a'");
        // Sorted descending: similarity of b > c.
        if results.len() >= 2 {
            assert!(results[0].1 >= results[1].1);
        }
    }

    // -----------------------------------------------------------------------
    // stats tests
    // -----------------------------------------------------------------------

    #[test]
    fn stats_empty_integrator() {
        let ig = default_integrator();
        let s = ig.stats();
        assert_eq!(s.symbol_count, 0);
        assert_eq!(s.rule_count, 0);
        assert_eq!(s.total_inferences, 0);
        assert_eq!(s.avg_embedding_norm, 0.0);
    }

    #[test]
    fn stats_counts_symbols_and_rules() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.9,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let s = ig.stats();
        assert_eq!(s.symbol_count, 2);
        assert_eq!(s.rule_count, 1);
    }

    #[test]
    fn stats_avg_norm_unit_vectors() {
        let mut ig = default_integrator();
        ig.add_symbol("a".into(), basis_emb(4, 0), 1.0)
            .expect("test setup: add symbol 'a'");
        ig.add_symbol("b".into(), basis_emb(4, 1), 1.0)
            .expect("test setup: add symbol 'b'");
        let s = ig.stats();
        // Both are unit vectors; average norm should be 1.0.
        assert!((s.avg_embedding_norm - 1.0).abs() < 1e-10);
    }

    #[test]
    fn stats_tracks_inferences() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.5)
            .expect("test setup: add symbol 'a'");
        let q = NsQuery {
            target: a,
            evidence: vec![],
            mode: InferenceMode::PureSymbolic,
        };
        ig.infer(&q).expect("test setup: first infer call");
        ig.infer(&q).expect("test setup: second infer call");
        ig.infer(&q).expect("test setup: third infer call");
        assert_eq!(ig.stats().total_inferences, 3);
    }

    // -----------------------------------------------------------------------
    // Integration / scenario tests
    // -----------------------------------------------------------------------

    #[test]
    fn scenario_chain_of_rules() {
        // a ← b ← c, with c in evidence.
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), uniform_emb(4, 1.0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), uniform_emb(4, 1.0), 0.0)
            .expect("test setup: add symbol 'b'");
        let c = ig
            .add_symbol("c".into(), uniform_emb(4, 1.0), 0.0)
            .expect("test setup: add symbol 'c'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.9,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        ig.add_rule(LogicalRule {
            head: b,
            body: vec![c],
            weight: 0.8,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule b <- c");
        let q = NsQuery {
            target: a,
            evidence: vec![(c, 1.0)],
            mode: InferenceMode::PureSymbolic,
        };
        let result = ig.infer(&q).expect("test setup: infer chain a <- b <- c");
        // Chain: 0.9 * (0.8 * 1.0) = 0.72
        assert!((result.confidence - 0.72).abs() < 1e-9);
    }

    #[test]
    fn scenario_multiple_rules_max_selected() {
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        let c = ig
            .add_symbol("c".into(), basis_emb(4, 2), 0.0)
            .expect("test setup: add symbol 'c'");
        // Two rules for a; one has higher confidence.
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.3,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add low-weight rule a <- b");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![c],
            weight: 0.9,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add high-weight rule a <- c");
        let q = NsQuery {
            target: a,
            evidence: vec![(b, 1.0), (c, 1.0)],
            mode: InferenceMode::PureSymbolic,
        };
        let result = ig
            .infer(&q)
            .expect("test setup: infer with competing rules");
        // Max of 0.3 and 0.9 → 0.9
        assert!((result.confidence - 0.9).abs() < 1e-9);
    }

    #[test]
    fn scenario_hybrid_blends_both() {
        let mut ig = default_integrator();
        // Target and evidence share the same embedding → neural=1*conf=0.6
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'b'"); // identical emb
                                                   // Symbolic: a ← b, weight=0.8
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 0.8,
            rule_type: RuleType::Definite,
        })
        .expect("test setup: add rule a <- b");
        let q = NsQuery {
            target: a,
            evidence: vec![(b, 0.6)],
            mode: InferenceMode::Hybrid { neural_weight: 0.4 },
        };
        let result = ig.infer(&q).expect("test setup: infer hybrid blend");
        // neural=0.6, symbolic=0.8*0.6=0.48
        // hybrid = 0.4*0.6 + 0.6*0.48 = 0.24 + 0.288 = 0.528
        assert!((result.confidence - 0.528).abs() < 1e-9);
    }

    #[test]
    fn scenario_soft_rule_low_temperature() {
        // At very low temperature, soft rule approaches a step function.
        let mut ig = default_integrator();
        let a = ig
            .add_symbol("a".into(), basis_emb(4, 0), 0.0)
            .expect("test setup: add symbol 'a'");
        let b = ig
            .add_symbol("b".into(), basis_emb(4, 1), 0.0)
            .expect("test setup: add symbol 'b'");
        ig.add_rule(LogicalRule {
            head: a,
            body: vec![b],
            weight: 1.0,
            rule_type: RuleType::Soft { temperature: 0.01 },
        })
        .expect("test setup: add soft rule a <- b");
        // Body sat = 1.0 → sigmoid(1.0/0.01)=sigmoid(100)≈1.0
        let conf = ig.symbolic_forward_chain(a, &[(b, 1.0)], 3);
        assert!(conf > 0.99, "expected ≈1.0, got {}", conf);
    }
}