shodh-memory 0.2.0

Persistent cognitive memory for AI agents and robots — Hebbian learning, knowledge graph, spatial recall. Zenoh/ROS2 native. Single binary, runs offline.
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
//! Comprehensive Integration Test Suite for Shodh-Memory
//!
//! Enterprise-grade testing demonstrating production readiness for:
//! - Robotics and autonomous systems
//! - Drone fleet management
//! - Edge AI deployments
//! - NER integration for entity extraction
//!
//! Run with: cargo test --test integration_tests -- --nocapture

use std::collections::HashMap;
use std::time::Instant;
use tempfile::TempDir;

use shodh_memory::embeddings::ner::{NerConfig, NeuralNer};
use shodh_memory::{
    memory::types::GeoFilter,
    memory::{Experience, ExperienceType, MemoryConfig, MemorySystem, Query, RetrievalMode},
};

/// Create fallback NER instance for testing
fn setup_fallback_ner() -> NeuralNer {
    let config = NerConfig::default();
    NeuralNer::new_fallback(config)
}

/// Create experience with NER-extracted entities
fn create_experience_with_ner(
    content: &str,
    exp_type: ExperienceType,
    ner: &NeuralNer,
) -> Experience {
    let entities = ner.extract(content).unwrap_or_default();
    let entity_names: Vec<String> = entities.iter().map(|e| e.text.clone()).collect();
    Experience {
        experience_type: exp_type,
        content: content.to_string(),
        entities: entity_names,
        ..Default::default()
    }
}

// ============================================================================
// TEST REPORTER - Professional output for enterprise demonstration
// ============================================================================

struct TestReporter {
    test_name: String,
    start_time: Instant,
    results: Vec<TestResult>,
}

struct TestResult {
    name: String,
    passed: bool,
    #[allow(unused)] // Used for reporting
    duration_ms: u128,
    details: String,
}

impl TestReporter {
    fn new(suite_name: &str) -> Self {
        println!("\n{}", "=".repeat(80));
        println!("  SHODH-MEMORY INTEGRATION TEST SUITE");
        println!("  {suite_name}");
        println!("{}", "=".repeat(80));
        println!("  Enterprise-grade AI Memory for Robotics & Autonomous Systems");
        println!("  Version: 0.1.0 | License: Commercial\n");

        Self {
            test_name: suite_name.to_string(),
            start_time: Instant::now(),
            results: Vec::new(),
        }
    }

    fn record(&mut self, name: &str, passed: bool, duration_ms: u128, details: &str) {
        let status = if passed { "[PASS]" } else { "[FAIL]" };
        println!("  {status} {name} ({duration_ms} ms)");
        if !details.is_empty() {
            println!("       {details}");
        }

        self.results.push(TestResult {
            name: name.to_string(),
            passed,
            duration_ms,
            details: details.to_string(),
        });
    }

    fn section(&self, name: &str) {
        println!("\n  --- {name} ---\n");
    }

    fn report(self) {
        let total = self.results.len();
        let passed = self.results.iter().filter(|r| r.passed).count();
        let failed = total - passed;
        let total_duration = self.start_time.elapsed().as_millis();

        println!("\n{}", "=".repeat(80));
        println!("  TEST SUITE SUMMARY: {}", self.test_name);
        println!("{}", "-".repeat(80));
        println!("  Total Tests:  {total}");
        println!(
            "  Passed:       {} ({:.1}%)",
            passed,
            (passed as f64 / total as f64) * 100.0
        );
        println!("  Failed:       {failed}");
        println!("  Duration:     {total_duration} ms");
        println!("{}", "=".repeat(80));

        if failed == 0 {
            println!("\n  [SUCCESS] All tests passed - System ready for production deployment\n");
        } else {
            println!("\n  [WARNING] {failed} tests failed - Review before deployment\n");
            for result in &self.results {
                if !result.passed {
                    println!("    - {}: {}", result.name, result.details);
                }
            }
        }
    }
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

fn create_test_config(temp_dir: &TempDir) -> MemoryConfig {
    MemoryConfig {
        storage_path: temp_dir.path().to_path_buf(),
        working_memory_size: 100,
        session_memory_size_mb: 50,
        max_heap_per_user_mb: 500,
        auto_compress: true,
        compression_age_days: 7,
        importance_threshold: 0.5,
    }
}

fn create_robotics_experience(content: &str, robot_id: &str, entities: Vec<&str>) -> Experience {
    let mut metadata = HashMap::new();
    metadata.insert("robot_id".to_string(), robot_id.to_string());

    Experience {
        experience_type: ExperienceType::Observation,
        content: content.to_string(),
        entities: entities.into_iter().map(|s| s.to_string()).collect(),
        metadata,
        robot_id: Some(robot_id.to_string()),
        ..Default::default()
    }
}

fn create_drone_experience(
    content: &str,
    drone_id: &str,
    mission_id: &str,
    geo_location: Option<[f64; 3]>,
    action_type: Option<&str>,
) -> Experience {
    let mut metadata = HashMap::new();
    metadata.insert("drone_id".to_string(), drone_id.to_string());
    metadata.insert("mission_id".to_string(), mission_id.to_string());

    Experience {
        experience_type: ExperienceType::Task,
        content: content.to_string(),
        entities: vec![drone_id.to_string(), mission_id.to_string()],
        metadata,
        robot_id: Some(drone_id.to_string()),
        mission_id: Some(mission_id.to_string()),
        geo_location,
        action_type: action_type.map(|s| s.to_string()),
        ..Default::default()
    }
}

// ============================================================================
// CORE FUNCTIONALITY TESTS
// ============================================================================

#[test]
fn test_core_memory_operations() {
    let mut reporter = TestReporter::new("Core Memory Operations");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    reporter.section("Memory System Initialization");

    // Test 1: System initialization
    let start = Instant::now();
    let system_result = MemorySystem::new(config, None);
    let init_duration = start.elapsed().as_millis();

    let system = match system_result {
        Ok(s) => {
            reporter.record(
                "Initialize memory system",
                true,
                init_duration,
                &format!("System initialized in {init_duration} ms"),
            );
            s
        }
        Err(e) => {
            reporter.record(
                "Initialize memory system",
                false,
                init_duration,
                &format!("Failed: {e}"),
            );
            reporter.report();
            panic!("Cannot continue without memory system");
        }
    };

    reporter.section("Record Operations");

    // Test 2: Record basic experience
    let start = Instant::now();
    let experience = Experience {
        experience_type: ExperienceType::Observation,
        content: "Robot arm successfully grasped object at position (10, 20, 5)".to_string(),
        entities: vec![
            "robot_arm".to_string(),
            "grasp".to_string(),
            "object".to_string(),
        ],
        robot_id: Some("arm_001".to_string()),
        local_position: Some([10.0, 20.0, 5.0]),
        action_type: Some("grasp".to_string()),
        reward: Some(0.95),
        ..Default::default()
    };

    let record_result = system.remember(experience, None);
    let record_duration = start.elapsed().as_millis();

    match record_result {
        Ok(memory_id) => {
            reporter.record(
                "Record experience",
                true,
                record_duration,
                &format!("Memory ID: {}", memory_id.0),
            );
        }
        Err(e) => {
            reporter.record(
                "Record experience",
                false,
                record_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    // Test 3: Record multiple experiences
    let start = Instant::now();
    let mut success_count = 0;
    for i in 0..10 {
        let exp = create_robotics_experience(
            &format!("Test observation {i} - sensor reading at waypoint"),
            "robot_001",
            vec!["sensor", "waypoint"],
        );
        if system.remember(exp, None).is_ok() {
            success_count += 1;
        }
    }
    let batch_duration = start.elapsed().as_millis();

    reporter.record(
        "Batch record (10 memories)",
        success_count == 10,
        batch_duration,
        &format!(
            "{}/10 successful, avg {} ms/record",
            success_count,
            batch_duration / 10
        ),
    );

    reporter.section("Retrieval Operations");

    // Test 4: Basic retrieval
    let start = Instant::now();
    let query = Query {
        query_text: Some("robot arm grasp object".to_string()),
        max_results: 5,
        ..Default::default()
    };

    let retrieve_result = system.recall(&query);
    let retrieve_duration = start.elapsed().as_millis();

    match retrieve_result {
        Ok(memories) => {
            reporter.record(
                "Semantic retrieval",
                !memories.is_empty(),
                retrieve_duration,
                &format!(
                    "Retrieved {} memories in {} ms",
                    memories.len(),
                    retrieve_duration
                ),
            );
        }
        Err(e) => {
            reporter.record(
                "Semantic retrieval",
                false,
                retrieve_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    // Test 5: Entity-based retrieval
    let start = Instant::now();
    let query = Query {
        query_text: Some("sensor".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let entity_result = system.recall(&query);
    let entity_duration = start.elapsed().as_millis();

    match entity_result {
        Ok(memories) => {
            reporter.record(
                "Entity-based retrieval",
                true,
                entity_duration,
                &format!("Found {} memories with sensor entity", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Entity-based retrieval",
                false,
                entity_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.report();
}

// ============================================================================
// ROBOTICS-SPECIFIC TESTS
// ============================================================================

#[test]
fn test_robotics_scenarios() {
    let mut reporter = TestReporter::new("Robotics & Autonomous Systems");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    reporter.section("Mission Memory Tracking");

    // Test 1: Mission-based memory organization
    let start = Instant::now();
    let missions = vec![
        (
            "mission_alpha",
            "patrol",
            vec![
                "Started patrol route at sector A",
                "Detected obstacle at coordinates (15, 30)",
                "Rerouted around obstacle via waypoint B",
                "Completed patrol - no anomalies detected",
            ],
        ),
        (
            "mission_beta",
            "inspection",
            vec![
                "Initiated inspection of equipment rack 1",
                "Found rust damage on component C-15",
                "Documented damage with visual capture",
                "Flagged for maintenance priority HIGH",
            ],
        ),
    ];

    let mut mission_success = true;
    for (mission_id, mission_type, events) in missions {
        for event in events {
            let exp = Experience {
                experience_type: ExperienceType::Task,
                content: event.to_string(),
                entities: vec![mission_type.to_string()],
                robot_id: Some("robot_001".to_string()),
                mission_id: Some(mission_id.to_string()),
                ..Default::default()
            };
            if system.remember(exp, None).is_err() {
                mission_success = false;
            }
        }
    }
    let mission_duration = start.elapsed().as_millis();

    reporter.record(
        "Mission memory tracking",
        mission_success,
        mission_duration,
        "2 missions with 4 events each recorded",
    );

    // Test 2: Retrieve mission-specific memories
    let start = Instant::now();
    let query = Query {
        query_text: Some("patrol obstacle".to_string()),
        mission_id: Some("mission_alpha".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let patrol_result = system.recall(&query);
    let patrol_duration = start.elapsed().as_millis();

    match patrol_result {
        Ok(memories) => {
            reporter.record(
                "Mission-filtered retrieval",
                true,
                patrol_duration,
                &format!("Found {} patrol memories", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Mission-filtered retrieval",
                false,
                patrol_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.section("Obstacle Detection & Memory");

    // Test 3: Obstacle memory
    let start = Instant::now();
    let obstacles = vec![
        ("Large rock", [10.0, 25.0, 0.0_f32]),
        ("Fallen tree", [35.0, 12.0, 0.0]),
        ("Water puddle", [22.0, 40.0, -0.5]),
    ];

    let mut obstacle_count = 0;
    for (desc, pos) in obstacles {
        let exp = Experience {
            experience_type: ExperienceType::Discovery,
            content: format!(
                "Obstacle detected: {} at position ({}, {}, {})",
                desc, pos[0], pos[1], pos[2]
            ),
            entities: vec!["obstacle".to_string(), desc.to_lowercase()],
            robot_id: Some("robot_001".to_string()),
            local_position: Some(pos),
            action_type: Some("obstacle_detection".to_string()),
            ..Default::default()
        };
        if system.remember(exp, None).is_ok() {
            obstacle_count += 1;
        }
    }
    let obstacle_duration = start.elapsed().as_millis();

    reporter.record(
        "Obstacle memory storage",
        obstacle_count == 3,
        obstacle_duration,
        &format!("{obstacle_count}/3 obstacles recorded"),
    );

    // Test 4: Query obstacles
    let start = Instant::now();
    let query = Query {
        query_text: Some("obstacle detected".to_string()),
        action_type: Some("obstacle_detection".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let obstacle_query_result = system.recall(&query);
    let obstacle_query_duration = start.elapsed().as_millis();

    match obstacle_query_result {
        Ok(memories) => {
            reporter.record(
                "Obstacle memory retrieval",
                true,
                obstacle_query_duration,
                &format!("Retrieved {} obstacle memories", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Obstacle memory retrieval",
                false,
                obstacle_query_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.section("Sensor Calibration Memory");

    // Test 5: Sensor calibration tracking
    let start = Instant::now();
    let sensors = vec![
        ("lidar_front", 0.98, "optimal"),
        ("camera_rgb", 0.95, "good"),
        ("imu_main", 0.99, "excellent"),
        ("ultrasonic_left", 0.85, "needs_recalibration"),
    ];

    let mut calibration_success = true;
    for (sensor, accuracy, status) in sensors {
        let mut sensor_data = HashMap::new();
        sensor_data.insert(format!("{sensor}_accuracy"), accuracy);

        let exp = Experience {
            experience_type: ExperienceType::Pattern,
            content: format!(
                "Sensor {sensor} calibration: accuracy {accuracy:.2}, status: {status}"
            ),
            entities: vec![
                "sensor".to_string(),
                "calibration".to_string(),
                sensor.to_string(),
            ],
            robot_id: Some("robot_001".to_string()),
            action_type: Some("calibration".to_string()),
            reward: Some(accuracy as f32),
            sensor_data,
            ..Default::default()
        };
        if system.remember(exp, None).is_err() {
            calibration_success = false;
        }
    }
    let calibration_duration = start.elapsed().as_millis();

    reporter.record(
        "Sensor calibration tracking",
        calibration_success,
        calibration_duration,
        "4 sensor calibrations recorded",
    );

    // Test 6: Find sensors needing recalibration
    let start = Instant::now();
    let query = Query {
        query_text: Some("needs recalibration".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let recal_result = system.recall(&query);
    let recal_duration = start.elapsed().as_millis();

    match recal_result {
        Ok(memories) => {
            reporter.record(
                "Recalibration needs query",
                true,
                recal_duration,
                &format!("Found {} sensors needing attention", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Recalibration needs query",
                false,
                recal_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.report();
}

// ============================================================================
// DRONE FLEET TESTS
// ============================================================================

#[test]
fn test_drone_fleet_operations() {
    let mut reporter = TestReporter::new("Drone Fleet Management");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    reporter.section("Multi-Drone Coordination");

    // Test 1: Multi-drone mission recording
    let start = Instant::now();
    let drones = ["drone_alpha", "drone_beta", "drone_gamma"];
    let mut success_count = 0;

    for (i, drone_id) in drones.iter().enumerate() {
        let lat = 37.7749 + (i as f64 * 0.001);
        let lon = -122.4194 + (i as f64 * 0.001);

        let exp = create_drone_experience(
            &format!(
                "{} initiated surveillance sweep at sector {}",
                drone_id,
                i + 1
            ),
            drone_id,
            "surveillance_mission_001",
            Some([lat, lon, 100.0]),
            Some("surveillance"),
        );
        if system.remember(exp, None).is_ok() {
            success_count += 1;
        }
    }
    let multi_drone_duration = start.elapsed().as_millis();

    reporter.record(
        "Multi-drone mission init",
        success_count == 3,
        multi_drone_duration,
        &format!("{success_count}/3 drones initialized"),
    );

    reporter.section("Geo-Spatial Memory");

    // Test 2: Record geo-tagged events
    let start = Instant::now();
    let events = vec![
        (
            "Target identified at construction site",
            37.7749,
            -122.4194,
            50.0,
        ),
        ("Weather station data collected", 37.7850, -122.4094, 75.0),
        ("Traffic monitoring complete", 37.7650, -122.4294, 100.0),
        ("Emergency vehicle detected", 37.7749, -122.4194, 60.0),
    ];

    let mut geo_success = 0;
    for (desc, lat, lon, alt) in events {
        let exp = create_drone_experience(
            desc,
            "drone_alpha",
            "surveillance_mission_001",
            Some([lat, lon, alt]),
            Some("observation"),
        );
        if system.remember(exp, None).is_ok() {
            geo_success += 1;
        }
    }
    let geo_duration = start.elapsed().as_millis();

    reporter.record(
        "Geo-tagged event recording",
        geo_success == 4,
        geo_duration,
        &format!("{geo_success}/4 geo-tagged events recorded"),
    );

    // Test 3: Geo-spatial query
    let start = Instant::now();
    let query = Query {
        query_text: Some("target identified".to_string()),
        geo_filter: Some(GeoFilter::new(37.7749, -122.4194, 1000.0)), // 1km radius
        max_results: 10,
        ..Default::default()
    };

    let geo_query_result = system.recall(&query);
    let geo_query_duration = start.elapsed().as_millis();

    match geo_query_result {
        Ok(memories) => {
            reporter.record(
                "Geo-spatial retrieval",
                true,
                geo_query_duration,
                &format!("Found {} memories within 1km radius", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Geo-spatial retrieval",
                false,
                geo_query_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.section("Flight Path Memory");

    // Test 4: Record flight path
    let start = Instant::now();
    let waypoints = [
        ([37.7749, -122.4194, 100.0], 0.0_f32),
        ([37.7760, -122.4180, 105.0], 45.0),
        ([37.7775, -122.4160, 110.0], 60.0),
        ([37.7790, -122.4140, 115.0], 75.0),
        ([37.7800, -122.4130, 100.0], 90.0),
    ];

    let mut path_success = 0;
    for (i, (pos, heading)) in waypoints.iter().enumerate() {
        let exp = Experience {
            experience_type: ExperienceType::Task,
            content: format!(
                "Waypoint {} reached - altitude {}m, heading {}deg",
                i + 1,
                pos[2],
                heading
            ),
            entities: vec!["waypoint".to_string(), "flight_path".to_string()],
            robot_id: Some("drone_alpha".to_string()),
            mission_id: Some("flight_001".to_string()),
            geo_location: Some(*pos),
            heading: Some(*heading),
            action_type: Some("navigation".to_string()),
            reward: Some(1.0),
            ..Default::default()
        };
        if system.remember(exp, None).is_ok() {
            path_success += 1;
        }
    }
    let path_duration = start.elapsed().as_millis();

    reporter.record(
        "Flight path recording",
        path_success == 5,
        path_duration,
        &format!("{path_success}/5 waypoints recorded"),
    );

    // Test 5: Query flight path
    let start = Instant::now();
    let query = Query {
        query_text: Some("waypoint reached".to_string()),
        mission_id: Some("flight_001".to_string()),
        max_results: 10,
        retrieval_mode: RetrievalMode::Temporal,
        ..Default::default()
    };

    let path_query_result = system.recall(&query);
    let path_query_duration = start.elapsed().as_millis();

    match path_query_result {
        Ok(memories) => {
            reporter.record(
                "Flight path retrieval",
                true,
                path_query_duration,
                &format!("Retrieved {} waypoint memories", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Flight path retrieval",
                false,
                path_query_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.section("Battery & Telemetry");

    // Test 6: Battery state tracking
    let start = Instant::now();
    let battery_readings = vec![
        (100, "full", 0),
        (85, "good", 5),
        (65, "moderate", 12),
        (40, "low", 20),
        (20, "critical", 28),
    ];

    let mut battery_success = 0;
    for (level, status, flight_minutes) in battery_readings {
        let mut sensor_data = HashMap::new();
        sensor_data.insert("battery_percent".to_string(), level as f64);
        sensor_data.insert("flight_time_minutes".to_string(), flight_minutes as f64);

        let exp = Experience {
            experience_type: ExperienceType::Pattern,
            content: format!(
                "Battery at {level}% ({status}) after {flight_minutes} minutes of flight"
            ),
            entities: vec!["battery".to_string(), status.to_string()],
            robot_id: Some("drone_alpha".to_string()),
            mission_id: Some("flight_001".to_string()),
            action_type: Some("telemetry".to_string()),
            reward: Some((level as f32) / 100.0),
            sensor_data,
            ..Default::default()
        };
        if system.remember(exp, None).is_ok() {
            battery_success += 1;
        }
    }
    let battery_duration = start.elapsed().as_millis();

    reporter.record(
        "Battery telemetry tracking",
        battery_success == 5,
        battery_duration,
        &format!("{battery_success}/5 battery readings recorded"),
    );

    // Test 7: Critical battery query
    let start = Instant::now();
    let query = Query {
        query_text: Some("battery critical".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let critical_result = system.recall(&query);
    let critical_duration = start.elapsed().as_millis();

    match critical_result {
        Ok(memories) => {
            reporter.record(
                "Critical status retrieval",
                true,
                critical_duration,
                &format!("Found {} critical battery events", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "Critical status retrieval",
                false,
                critical_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.report();
}

// ============================================================================
// PERFORMANCE BENCHMARKS
// ============================================================================

#[test]
fn test_performance_benchmarks() {
    let mut reporter = TestReporter::new("Performance Benchmarks");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    reporter.section("Insertion Performance");

    // Benchmark 1: High-volume insertion
    let batch_sizes = [10, 50, 100];

    for batch_size in batch_sizes {
        let start = Instant::now();
        let mut success = 0;

        for i in 0..batch_size {
            let exp = create_robotics_experience(
                &format!("Performance test observation {i} with sensor data and position tracking"),
                &format!("perf_robot_{}", i % 5),
                vec!["performance", "benchmark", "sensor"],
            );
            if system.remember(exp, None).is_ok() {
                success += 1;
            }
        }

        let duration = start.elapsed().as_millis();
        let rate = if duration > 0 {
            (success as f64 / duration as f64) * 1000.0
        } else {
            0.0
        };

        reporter.record(
            &format!("Insert {batch_size} memories"),
            success == batch_size,
            duration,
            &format!(
                "{:.1} records/sec, avg {:.2} ms/record",
                rate,
                if success > 0 {
                    duration as f64 / success as f64
                } else {
                    0.0
                }
            ),
        );
    }

    reporter.section("Query Performance");

    // Benchmark 2: Query latency
    let queries = vec![
        ("Simple keyword", "sensor"),
        ("Multi-word", "performance test observation"),
        ("Entity-focused", "robot performance benchmark"),
    ];

    for (name, query_text) in queries {
        let mut total_duration = 0u128;
        let iterations = 5;

        for _ in 0..iterations {
            let start = Instant::now();
            let query = Query {
                query_text: Some(query_text.to_string()),
                max_results: 10,
                ..Default::default()
            };
            let _ = system.recall(&query);
            total_duration += start.elapsed().as_millis();
        }

        let avg_duration = total_duration / iterations as u128;

        reporter.record(
            &format!("{name} query"),
            avg_duration < 500, // Target: <500ms average
            avg_duration,
            &format!("avg over {iterations} iterations"),
        );
    }

    reporter.section("Memory Efficiency");

    // Benchmark 3: Memory stats
    let start = Instant::now();
    let stats = system.stats();
    let stats_duration = start.elapsed().as_millis();

    reporter.record(
        "Stats retrieval",
        true,
        stats_duration,
        &format!(
            "Total memories: {}, Working: {}, Session: {}, Long-term: {}",
            stats.total_memories,
            stats.working_memory_count,
            stats.session_memory_count,
            stats.long_term_memory_count
        ),
    );

    reporter.report();
}

// ============================================================================
// RELIABILITY TESTS
// ============================================================================

#[test]
fn test_reliability_and_edge_cases() {
    let mut reporter = TestReporter::new("Reliability & Edge Cases");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    reporter.section("Input Validation");

    // Test 1: Empty content handling
    let start = Instant::now();
    let exp = Experience {
        content: "".to_string(), // Empty content
        ..Default::default()
    };

    let empty_result = system.remember(exp, None);
    let empty_duration = start.elapsed().as_millis();

    // Empty content should still be handled gracefully
    reporter.record(
        "Empty content handling",
        empty_result.is_ok(),
        empty_duration,
        "System handles empty content gracefully",
    );

    // Test 2: Very long content
    let start = Instant::now();
    let long_content = "x".repeat(10000); // 10KB of content
    let exp = Experience {
        content: long_content,
        ..Default::default()
    };

    let long_result = system.remember(exp, None);
    let long_duration = start.elapsed().as_millis();

    reporter.record(
        "Large content handling (10KB)",
        long_result.is_ok(),
        long_duration,
        &format!("Processed in {long_duration} ms"),
    );

    // Test 3: Special characters in content
    let start = Instant::now();
    let special_content = "Test with special chars: <>&\"' \n\t\r and unicode: 你好世界 🤖 λ∑∏";
    let exp = Experience {
        content: special_content.to_string(),
        entities: vec!["unicode".to_string(), "special_chars".to_string()],
        ..Default::default()
    };

    let special_result = system.remember(exp, None);
    let special_duration = start.elapsed().as_millis();

    reporter.record(
        "Special characters handling",
        special_result.is_ok(),
        special_duration,
        "Unicode and special characters handled correctly",
    );

    reporter.section("Query Edge Cases");

    // Test 4: Empty query
    let start = Instant::now();
    let query = Query {
        query_text: Some("".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let empty_query_result = system.recall(&query);
    let empty_query_duration = start.elapsed().as_millis();

    reporter.record(
        "Empty query handling",
        empty_query_result.is_ok(),
        empty_query_duration,
        "Empty query handled gracefully",
    );

    // Test 5: Query with no results
    let start = Instant::now();
    let query = Query {
        query_text: Some("nonexistent_query_that_should_match_nothing_xyz123".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let no_results = system.recall(&query);
    let no_results_duration = start.elapsed().as_millis();

    match no_results {
        Ok(memories) => {
            reporter.record(
                "No-match query",
                true,
                no_results_duration,
                &format!("Returned {} results (expected 0 or low)", memories.len()),
            );
        }
        Err(e) => {
            reporter.record(
                "No-match query",
                false,
                no_results_duration,
                &format!("Failed: {e}"),
            );
        }
    }

    reporter.section("Concurrent Access Simulation");

    // Test 6: Rapid sequential operations
    let start = Instant::now();
    let mut ops_success = 0;

    for i in 0..20 {
        // Alternate between record and retrieve
        if i % 2 == 0 {
            let exp = create_robotics_experience(
                &format!("Concurrent test {i}"),
                "robot_concurrent",
                vec!["concurrent"],
            );
            if system.remember(exp, None).is_ok() {
                ops_success += 1;
            }
        } else {
            let query = Query {
                query_text: Some("concurrent".to_string()),
                max_results: 5,
                ..Default::default()
            };
            if system.recall(&query).is_ok() {
                ops_success += 1;
            }
        }
    }
    let concurrent_duration = start.elapsed().as_millis();

    reporter.record(
        "Rapid sequential ops (20)",
        ops_success == 20,
        concurrent_duration,
        &format!("{ops_success}/20 operations successful"),
    );

    reporter.section("Data Persistence");

    // Test 7: Flush and verify
    let start = Instant::now();
    let flush_result = system.flush_storage();
    let flush_duration = start.elapsed().as_millis();

    reporter.record(
        "Storage flush",
        flush_result.is_ok(),
        flush_duration,
        "Data persisted to disk",
    );

    reporter.report();
}

// ============================================================================
// STRESS TEST
// ============================================================================

#[test]
fn test_stress_scenarios() {
    let mut reporter = TestReporter::new("Stress Testing");
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = create_test_config(&temp_dir);

    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    reporter.section("High Volume Operations");

    // Stress test: 500 rapid insertions
    let start = Instant::now();
    let target = 500;
    let mut success = 0;

    for i in 0..target {
        let exp = create_robotics_experience(
            &format!("Stress test record {i} - high frequency sensor data from multiple sources"),
            &format!("stress_robot_{}", i % 10),
            vec!["stress", "high_volume", "sensor"],
        );
        if system.remember(exp, None).is_ok() {
            success += 1;
        }
    }

    let stress_duration = start.elapsed().as_millis();
    let rate = if stress_duration > 0 {
        (success as f64 / stress_duration as f64) * 1000.0
    } else {
        0.0
    };

    reporter.record(
        &format!("{target} rapid insertions"),
        success >= (target * 95 / 100), // 95% success threshold
        stress_duration,
        &format!("{success}/{target} successful ({rate:.1} records/sec)"),
    );

    // Rapid queries after stress
    let start = Instant::now();
    let query_count = 50;
    let mut query_success = 0;

    for i in 0..query_count {
        let query = Query {
            query_text: Some(format!("stress test record {}", i * 10)),
            max_results: 5,
            ..Default::default()
        };
        if system.recall(&query).is_ok() {
            query_success += 1;
        }
    }

    let query_duration = start.elapsed().as_millis();

    reporter.record(
        &format!("{query_count} queries post-stress"),
        query_success == query_count,
        query_duration,
        &format!(
            "{}/{} successful, avg {:.1} ms/query",
            query_success,
            query_count,
            query_duration as f64 / query_count as f64
        ),
    );

    reporter.report();
}