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
//! Bug Regression Tests - 2025-12-07 Audit
//!
//! Tests to prevent regression of all bugs fixed during the 2025-12-07 audit.
//! Each test documents the original bug and verifies the fix.
//!
//! Run with: cargo test --test bug_regression_tests

use chrono::{Duration, Utc};
use std::time::Instant;
use tempfile::TempDir;

use shodh_memory::embeddings::ner::{NerConfig, NeuralNer};
use shodh_memory::memory::types::{
    geohash_decode, geohash_encode, geohash_neighbors, geohash_precision_for_radius, Experience,
    ExperienceType, GeoFilter, Query,
};
use shodh_memory::memory::{MemoryConfig, MemorySystem};

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

/// Create fallback NER for testing (rule-based, no ONNX required)
fn setup_fallback_ner() -> NeuralNer {
    let config = NerConfig::default();
    NeuralNer::new_fallback(config)
}

/// Create experience with NER entity extraction
fn create_experience_with_ner(content: &str, 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 {
        content: content.to_string(),
        experience_type: ExperienceType::Observation,
        entities: entity_names,
        ..Default::default()
    }
}

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: false,
        compression_age_days: 30,
        importance_threshold: 0.3,
    }
}

fn create_experience(content: &str) -> Experience {
    Experience {
        content: content.to_string(),
        experience_type: ExperienceType::Observation,
        entities: vec!["test".to_string()],
        ..Default::default()
    }
}

fn create_geo_experience(content: &str, lat: f64, lon: f64) -> Experience {
    Experience {
        content: content.to_string(),
        experience_type: ExperienceType::Observation,
        geo_location: Some([lat, lon, 0.0]),
        entities: vec!["geo_test".to_string()],
        ..Default::default()
    }
}

// ============================================================================
// BUG-001: DATE INDEX KEY UNIQUENESS
// Original: Only last memory per day survived due to key collision
// Fix: Include memory_id in date index key
// ============================================================================

#[test]
fn test_bug001_multiple_memories_same_day_all_retrievable() {
    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");

    // Record 10 memories on the same day
    let mut memory_ids = Vec::new();
    for i in 0..10 {
        let exp = Experience {
            content: format!("Memory {} created at the same moment", i),
            experience_type: ExperienceType::Observation,
            entities: vec![format!("entity_{}", i)],
            ..Default::default()
        };
        let id = system.remember(exp, None).expect("Failed to record memory");
        memory_ids.push(id);
    }

    // Verify all 10 memories exist and are retrievable
    let stats = system.stats();
    assert!(
        stats.total_memories >= 10,
        "BUG-001 REGRESSION: Expected at least 10 memories, got {}. \
         Date index key collision causing overwrites!",
        stats.total_memories
    );

    // Retrieve each memory by searching for its unique content
    for i in 0..10 {
        let query = Query {
            query_text: Some(format!("Memory {} created", i)),
            max_results: 5,
            ..Default::default()
        };
        let results = system.recall(&query).expect("Failed to retrieve");
        assert!(
            !results.is_empty(),
            "BUG-001 REGRESSION: Memory {} not found. Date index overwrite!",
            i
        );
    }
}

#[test]
fn test_bug001_date_search_returns_all_memories() {
    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");

    // Record 5 memories
    for i in 0..5 {
        let exp = create_experience(&format!("Date search test memory {}", i));
        system.remember(exp, None).expect("Failed to record");
    }

    // Search by date range (today)
    let today = Utc::now();
    let query = Query {
        time_range: Some((today - Duration::hours(1), today + Duration::hours(1))),
        max_results: 100,
        ..Default::default()
    };

    let results = system.recall(&query).expect("Failed to retrieve");
    assert!(
        results.len() >= 5,
        "BUG-001 REGRESSION: Date search returned {} memories, expected >= 5",
        results.len()
    );
}

// ============================================================================
// BUG-003: GEOHASH PRECISION (11m -> 1.2m)
// Original: 7-char geohash had ~11m precision, too coarse for dense areas
// Fix: Use 10-char geohash for ~1.2m precision
// ============================================================================

#[test]
fn test_bug003_geohash_uses_10_char_precision() {
    // Encode a specific location
    let lat = 37.7749;
    let lon = -122.4194;

    let hash = geohash_encode(lat, lon, 10);

    assert_eq!(
        hash.len(),
        10,
        "BUG-003 REGRESSION: Geohash should be 10 chars for 1.2m precision, got {} chars",
        hash.len()
    );
}

#[test]
fn test_bug003_geohash_distinguishes_close_points() {
    // Two points 5 meters apart should have different 10-char geohashes
    let lat1 = 37.7749000;
    let lon1 = -122.4194000;

    // Move ~5m east (about 0.00005 degrees longitude at this latitude)
    let lat2 = 37.7749000;
    let lon2 = -122.4193500;

    let hash1 = geohash_encode(lat1, lon1, 10);
    let hash2 = geohash_encode(lat2, lon2, 10);

    // With 10-char precision (~1.2m), 5m separation should produce different hashes
    assert_ne!(
        hash1, hash2,
        "BUG-003 REGRESSION: 10-char geohash should distinguish points 5m apart"
    );
}

#[test]
fn test_bug003_geohash_encode_decode_accuracy() {
    let lat = 37.7749;
    let lon = -122.4194;

    let hash = geohash_encode(lat, lon, 10);
    let (decoded_lat, decoded_lon, _, _) = geohash_decode(&hash);

    // With 10-char precision, error should be < 2m
    let lat_error = (lat - decoded_lat).abs();
    let lon_error = (lon - decoded_lon).abs();

    // At 37.7749 latitude, 1 degree longitude = ~87km, so 2m = ~0.000023 degrees
    assert!(
        lat_error < 0.00003,
        "BUG-003 REGRESSION: Latitude error {} exceeds 2m threshold",
        lat_error
    );
    assert!(
        lon_error < 0.00003,
        "BUG-003 REGRESSION: Longitude error {} exceeds 2m threshold",
        lon_error
    );
}

// ============================================================================
// BUG-005: INDEX REMOVAL PERFORMANCE (O(n) -> O(k))
// Original: Index removal scanned all keys with contains()
// Fix: Direct key reconstruction for O(k) deletion
// ============================================================================

#[test]
fn test_bug005_index_removal_is_fast() {
    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");

    // Record 100 memories to populate indices
    for i in 0..100 {
        let exp = create_experience(&format!("Index removal test memory {}", i));
        system.remember(exp, None).expect("Failed to record");
    }

    // Now measure time to flush (which triggers index cleanup)
    let start = Instant::now();
    system.flush_storage().expect("Failed to flush");
    let duration = start.elapsed();

    // With O(k) removal, 100 memories should complete in < 100ms
    assert!(
        duration.as_millis() < 500,
        "BUG-005 REGRESSION: Index operations took {}ms, expected < 500ms. \
         Possible O(n) scan regression!",
        duration.as_millis()
    );
}

// ============================================================================
// BUG-007: COMBINED SEARCH PERFORMANCE (O(n*m) -> O(n))
// Original: Vec::contains() for intersection was O(n)
// Fix: HashSet for O(1) lookups
// ============================================================================

#[test]
fn test_bug007_combined_search_scales_linearly() {
    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");

    // Record 50 memories with various entities
    for i in 0..50 {
        let exp = Experience {
            content: format!("Combined search test memory {} with multiple criteria", i),
            experience_type: ExperienceType::Observation,
            entities: vec![
                format!("entity_{}", i % 5),
                format!("category_{}", i % 3),
                "common_tag".to_string(),
            ],
            robot_id: Some(format!("robot_{}", i % 10)),
            ..Default::default()
        };
        system.remember(exp, None).expect("Failed to record");
    }

    // Run combined search with multiple criteria (semantic + robot_id filter)
    let start = Instant::now();
    let query = Query {
        query_text: Some("Combined search test".to_string()),
        robot_id: Some("robot_0".to_string()),
        max_results: 100,
        ..Default::default()
    };

    let results = system.recall(&query).expect("Failed to retrieve");
    let duration = start.elapsed();

    // Combined search should complete in < 500ms for 50 memories
    assert!(
        duration.as_millis() < 500,
        "BUG-007 REGRESSION: Combined search took {}ms, expected < 500ms. \
         Possible O(n*m) regression!",
        duration.as_millis()
    );

    // Should find at least some results (robot_0 appears in ~5 memories)
    // Note: Results may be empty if semantic search doesn't match well
}

// ============================================================================
// BUG-009: GEOHASH INVALID CHARACTER HANDLING
// Original: Invalid chars defaulted to index 0, producing wrong decode
// Fix: Skip invalid characters during decode
// ============================================================================

#[test]
fn test_bug009_geohash_skips_invalid_chars() {
    // Valid geohash with some invalid characters inserted
    let valid_hash = geohash_encode(37.7749, -122.4194, 10);

    // Insert some invalid characters (not in base32 alphabet)
    let invalid_hash = format!("{}@#!", &valid_hash[..5]);

    // Decode should skip invalid chars and still work (partial decode)
    let (lat, lon, _, _) = geohash_decode(&invalid_hash);

    // With partial decode (5 valid chars), we should still get reasonable coordinates
    // The key is that it doesn't crash or produce wildly wrong results
    assert!(
        lat.abs() < 90.0,
        "BUG-009 REGRESSION: Latitude {} is invalid after invalid char handling",
        lat
    );
    assert!(
        lon.abs() < 180.0,
        "BUG-009 REGRESSION: Longitude {} is invalid after invalid char handling",
        lon
    );
}

#[test]
fn test_bug009_geohash_empty_string() {
    // Empty string returns the midpoint of initial ranges (-90,90) and (-180,180)
    // which is (0, 0) or the corner (-90, -180) depending on implementation
    let (lat, lon, _, _) = geohash_decode("");

    // The actual behavior is to return valid coordinates within bounds
    assert!(
        lat >= -90.0 && lat <= 90.0 && lon >= -180.0 && lon <= 180.0,
        "BUG-009: Empty geohash should decode to valid coordinates, got ({}, {})",
        lat,
        lon
    );
}

#[test]
fn test_bug009_geohash_all_invalid() {
    // All invalid characters
    let (lat, lon, _, _) = geohash_decode("@#$%^&*!");

    // Should produce valid coordinates (likely center)
    assert!(
        lat.abs() <= 90.0 && lon.abs() <= 180.0,
        "BUG-009: All-invalid geohash should still produce valid coords"
    );
}

// ============================================================================
// BUG-010: GEOHASH RADIUS VALIDATION
// Original: No validation for NaN, infinity, negative, huge values
// Fix: Validate and clamp input values
// ============================================================================

#[test]
fn test_bug010_radius_nan_handled() {
    let precision = geohash_precision_for_radius(f64::NAN);

    // NaN should produce valid precision (default to small precision)
    assert!(
        precision >= 1 && precision <= 12,
        "BUG-010 REGRESSION: NaN radius produced invalid precision {}",
        precision
    );
}

#[test]
fn test_bug010_radius_infinity_handled() {
    let precision = geohash_precision_for_radius(f64::INFINITY);

    // Infinity should produce valid precision (low precision for large area)
    assert!(
        precision >= 1 && precision <= 12,
        "BUG-010 REGRESSION: Infinity radius produced invalid precision {}",
        precision
    );
}

#[test]
fn test_bug010_radius_negative_handled() {
    let precision = geohash_precision_for_radius(-100.0);

    // Negative should produce valid precision
    assert!(
        precision >= 1 && precision <= 12,
        "BUG-010 REGRESSION: Negative radius produced invalid precision {}",
        precision
    );
}

#[test]
fn test_bug010_radius_zero_handled() {
    let precision = geohash_precision_for_radius(0.0);

    // Zero should produce valid precision (high precision for small area)
    assert!(
        precision >= 1 && precision <= 12,
        "BUG-010 REGRESSION: Zero radius produced invalid precision {}",
        precision
    );
}

#[test]
fn test_bug010_radius_huge_handled() {
    // Larger than Earth's circumference
    let precision = geohash_precision_for_radius(50_000_000.0);

    // Huge radius should produce valid low precision
    assert!(
        precision >= 1 && precision <= 12,
        "BUG-010 REGRESSION: Huge radius produced invalid precision {}",
        precision
    );
}

#[test]
fn test_bug010_radius_normal_values() {
    // Test normal radius values produce expected precisions
    let test_cases = [
        (1.0, 12),      // 1m -> highest precision
        (10.0, 10),     // 10m
        (100.0, 8),     // 100m
        (1000.0, 6),    // 1km
        (10000.0, 5),   // 10km
        (100000.0, 4),  // 100km
        (1000000.0, 2), // 1000km
    ];

    for (radius, expected_min_precision) in test_cases {
        let precision = geohash_precision_for_radius(radius);
        assert!(
            precision >= 1 && precision <= 12,
            "Radius {} produced invalid precision {}",
            radius,
            precision
        );
    }
}

// ============================================================================
// ALGO-004: IMPORTANCE INDEX RE-INDEXING
// Original: Old importance bucket index orphaned when importance changed
// Fix: Remove old indices before storing updated memory
// ============================================================================

#[test]
fn test_algo004_importance_index_updates_after_change() {
    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");

    // Record a memory
    let exp = Experience {
        content: "Important discovery about neural networks".to_string(),
        experience_type: ExperienceType::Discovery,
        entities: vec!["neural_networks".to_string()],
        ..Default::default()
    };
    let memory_id = system.remember(exp, None).expect("Failed to record");

    // Retrieve it initially
    let query = Query {
        query_text: Some("neural networks".to_string()),
        max_results: 5,
        ..Default::default()
    };
    let initial_results = system.recall(&query).expect("Failed to retrieve");
    assert!(
        !initial_results.is_empty(),
        "Memory should be retrievable initially"
    );

    // Simulate Hebbian reinforcement by retrieving with positive outcome
    // (In real usage, this would be done via reinforce_recall)
    let memory_ids = vec![memory_id.clone()];
    let outcome = shodh_memory::memory::RetrievalOutcome::Helpful;
    system
        .reinforce_recall(&memory_ids, outcome)
        .expect("Failed to reinforce");

    // Retrieve again - should still find the memory
    let after_results = system
        .recall(&query)
        .expect("Failed to retrieve after reinforce");
    assert!(
        !after_results.is_empty(),
        "ALGO-004 REGRESSION: Memory not found after importance change. \
         Importance index not re-indexed!"
    );

    // Verify the memory's importance was boosted
    if let Some(mem) = after_results.first() {
        // Memory should have increased importance after positive reinforcement
        // (Initial importance is around 0.5-0.6 for Discovery type)
        // After Helpful reinforcement, it should be higher
        assert!(
            mem.importance() > 0.0,
            "Memory importance should be positive after reinforcement"
        );
    }
}

// ============================================================================
// BUG-006: EMPTY QUERY WARNING
// Original: Empty queries silently returned empty results
// Fix: Log warning for empty queries
// ============================================================================

#[test]
fn test_bug006_empty_query_returns_gracefully() {
    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");

    // Record some memories
    for i in 0..5 {
        let exp = create_experience(&format!("Test memory {}", i));
        system.remember(exp, None).expect("Failed to record");
    }

    // Empty query should not crash, should return gracefully
    let query = Query {
        query_text: Some("".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let results = system.recall(&query);
    assert!(
        results.is_ok(),
        "BUG-006: Empty query should not crash: {:?}",
        results.err()
    );
}

// ============================================================================
// BUG-004: VAMANA QUALITY AFTER MANY INSERTS
// Original: Graph quality degraded after 10K+ inserts
// Fix: Distance-based neighbor pruning
// Note: Full test requires many inserts, so this is a smaller smoke test
// ============================================================================

#[test]
fn test_bug004_vamana_maintains_recall_after_inserts() {
    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");

    // Insert a batch of semantically similar memories
    let topics = [
        "machine learning",
        "deep learning",
        "neural networks",
        "AI models",
    ];
    for i in 0..20 {
        let topic = topics[i % topics.len()];
        let exp = Experience {
            content: format!(
                "{} research paper {} about transformers and attention",
                topic, i
            ),
            experience_type: ExperienceType::Learning,
            entities: vec![topic.to_string()],
            ..Default::default()
        };
        system.remember(exp, None).expect("Failed to record");
    }

    // Query should find relevant results
    let query = Query {
        query_text: Some("machine learning transformers".to_string()),
        max_results: 10,
        ..Default::default()
    };

    let results = system.recall(&query).expect("Failed to retrieve");

    assert!(
        results.len() >= 3,
        "BUG-004 REGRESSION: Expected at least 3 results for similar query, got {}. \
         Vamana graph quality may be degraded!",
        results.len()
    );
}

// ============================================================================
// GEOHASH NEIGHBORS TEST
// Verifies that neighbor calculation works correctly
// ============================================================================

#[test]
fn test_geohash_neighbors_returns_valid_hashes() {
    let center = geohash_encode(37.7749, -122.4194, 6);
    let neighbors = geohash_neighbors(&center);

    // Should return 8 neighbors (implementation may or may not include center)
    assert!(
        neighbors.len() >= 8,
        "geohash_neighbors should return at least 8 hashes, got {}",
        neighbors.len()
    );

    // All neighbors should be same length as center
    for neighbor in &neighbors {
        assert_eq!(
            neighbor.len(),
            center.len(),
            "Neighbor {} has wrong length",
            neighbor
        );
    }
}

// ============================================================================
// GEO FILTER INTEGRATION TEST
// Verifies that geo-based retrieval works correctly
// ============================================================================

#[test]
fn test_geo_filter_retrieval() {
    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");

    // Record memories at different locations
    let locations = [
        ("San Francisco downtown", 37.7749, -122.4194),
        ("San Francisco near", 37.7750, -122.4195), // ~10m away
        ("Oakland", 37.8044, -122.2712),            // ~15km away
        ("Los Angeles", 34.0522, -118.2437),        // ~600km away
    ];

    for (name, lat, lon) in locations {
        let exp = create_geo_experience(&format!("Location test: {}", name), lat, lon);
        system.remember(exp, None).expect("Failed to record");
    }

    // Query within 1km of SF downtown - should get SF memories
    let query = Query {
        query_text: Some("Location test".to_string()),
        geo_filter: Some(GeoFilter::new(37.7749, -122.4194, 1000.0)),
        max_results: 10,
        ..Default::default()
    };

    let results = system.recall(&query).expect("Failed to retrieve");

    // Should find SF downtown and nearby, but not Oakland or LA
    assert!(
        results.len() >= 1 && results.len() <= 3,
        "Geo filter should return 1-3 results within 1km, got {}",
        results.len()
    );
}

// ============================================================================
// SHO-48: FORGET ENDPOINT VECTOR INDEX DELETION
// Original: forget() returned success but memories remained in vector index
// Fix: Added soft-delete to VamanaIndex, remove_memory() to RetrievalEngine
// ============================================================================

#[test]
fn test_sho48_forget_removes_from_semantic_search() {
    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");

    // Record a unique memory
    let exp = Experience {
        content: "SHO48 test memory with unique quantum entanglement photonic crystal content"
            .to_string(),
        experience_type: ExperienceType::Discovery,
        entities: vec!["quantum".to_string(), "photonic".to_string()],
        ..Default::default()
    };
    let memory_id = system.remember(exp, None).expect("Failed to record memory");

    // Verify it's findable via semantic search
    let query = Query {
        query_text: Some("quantum entanglement photonic crystal".to_string()),
        max_results: 10,
        ..Default::default()
    };
    let results_before = system.recall(&query).expect("Failed to retrieve");
    assert!(
        !results_before.is_empty(),
        "Memory should be findable before forget"
    );

    // Forget the memory
    let forget_result = system
        .forget(shodh_memory::memory::ForgetCriteria::ById(
            memory_id.clone(),
        ))
        .expect("Failed to forget");
    assert_eq!(forget_result, 1, "Should have forgotten 1 memory");

    // Verify it's NO LONGER findable via semantic search
    let results_after = system.recall(&query).expect("Failed to retrieve");
    let found_deleted = results_after.iter().any(|m| m.id == memory_id);
    assert!(
        !found_deleted,
        "SHO-48 REGRESSION: Forgotten memory still found in semantic search! \
         Vector index not cleaned on delete."
    );
}

#[test]
fn test_sho48_forget_updates_stats() {
    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");

    // Record a memory
    let exp = create_experience("Stats tracking test memory for SHO-48");
    let memory_id = system.remember(exp, None).expect("Failed to record memory");

    let stats_before = system.stats();

    // Forget the memory
    system
        .forget(shodh_memory::memory::ForgetCriteria::ById(memory_id))
        .expect("Failed to forget");

    let stats_after = system.stats();

    // Stats should be decremented
    assert!(
        stats_after.total_memories < stats_before.total_memories,
        "SHO-48 REGRESSION: total_memories not decremented after forget"
    );
}

// ============================================================================
// SHO-49: LIST_MEMORIES DUPLICATE ENTRIES
// Original: Same memory appeared multiple times in list (from different tiers)
// Fix: Added HashSet deduplication in retrieve()
// ============================================================================

#[test]
fn test_sho49_no_duplicates_in_retrieve() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = 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: false,
        compression_age_days: 30,
        importance_threshold: 0.0, // Low threshold so memories go to session too
    };
    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    // Record memories with high importance (will be in both working and session)
    let mut recorded_ids = std::collections::HashSet::new();
    for i in 0..10 {
        let exp = Experience {
            content: format!("Important memory {} for deduplication test", i),
            experience_type: ExperienceType::Decision, // High importance type
            entities: vec!["dedup_test".to_string()],
            ..Default::default()
        };
        let id = system.remember(exp, None).expect("Failed to record");
        recorded_ids.insert(id);
    }

    // Retrieve without semantic query (uses tier-based retrieval)
    let query = Query {
        max_results: 100,
        ..Default::default()
    };
    let results = system.recall(&query).expect("Failed to retrieve");

    // Check for duplicates
    let mut seen_ids = std::collections::HashSet::new();
    for memory in &results {
        let is_new = seen_ids.insert(memory.id.clone());
        assert!(
            is_new,
            "SHO-49 REGRESSION: Duplicate memory ID {:?} in results! \
             Deduplication not working across tiers.",
            memory.id
        );
    }
}

#[test]
fn test_sho49_retrieve_count_matches_unique() {
    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");

    // Record 5 unique memories
    for i in 0..5 {
        let exp = create_experience(&format!("Unique memory {} for count test", i));
        system.remember(exp, None).expect("Failed to record");
    }

    // Retrieve all
    let query = Query {
        max_results: 100,
        ..Default::default()
    };
    let results = system.recall(&query).expect("Failed to retrieve");

    // Count unique IDs
    let unique_count = results
        .iter()
        .map(|m| &m.id)
        .collect::<std::collections::HashSet<_>>()
        .len();

    assert_eq!(
        results.len(),
        unique_count,
        "SHO-49 REGRESSION: Result count ({}) != unique count ({}). Duplicates present!",
        results.len(),
        unique_count
    );
}

// ============================================================================
// SHO-50: MEMORY_STATS INCONSISTENT COUNTS
// Original: working_memory_count and session_memory_count always 0
// Fix: Update tier counts on add/delete operations
// ============================================================================

#[test]
fn test_sho50_stats_updated_on_add() {
    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");

    let stats_before = system.stats();

    // Record a memory
    let exp = create_experience("Stats test memory for SHO-50");
    system.remember(exp, None).expect("Failed to record");

    let stats_after = system.stats();

    // total_memories should increase
    assert_eq!(
        stats_after.total_memories,
        stats_before.total_memories + 1,
        "SHO-50 REGRESSION: total_memories not incremented on add"
    );

    // working_memory_count should increase (memory always goes to working first)
    assert!(
        stats_after.working_memory_count > stats_before.working_memory_count,
        "SHO-50 REGRESSION: working_memory_count not incremented on add"
    );

    // long_term_memory_count should increase (we store to long-term first)
    assert!(
        stats_after.long_term_memory_count > stats_before.long_term_memory_count,
        "SHO-50 REGRESSION: long_term_memory_count not incremented on add"
    );

    // vector_index_count should increase
    assert!(
        stats_after.vector_index_count > stats_before.vector_index_count,
        "SHO-50 REGRESSION: vector_index_count not incremented on add"
    );
}

#[test]
fn test_sho50_stats_updated_on_forget() {
    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");

    // Record a memory
    let exp = create_experience("Memory to forget for SHO-50 stats test");
    let memory_id = system.remember(exp, None).expect("Failed to record");

    let stats_before = system.stats();

    // Forget the memory
    system
        .forget(shodh_memory::memory::ForgetCriteria::ById(memory_id))
        .expect("Failed to forget");

    let stats_after = system.stats();

    // All counts should decrease
    assert!(
        stats_after.total_memories < stats_before.total_memories,
        "SHO-50 REGRESSION: total_memories not decremented on forget"
    );

    assert!(
        stats_after.long_term_memory_count < stats_before.long_term_memory_count,
        "SHO-50 REGRESSION: long_term_memory_count not decremented on forget"
    );
}

#[test]
fn test_sho50_high_importance_updates_session_count() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let config = 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: false,
        compression_age_days: 30,
        importance_threshold: 0.0, // Very low threshold - everything goes to session
    };
    let system = MemorySystem::new(config, None).expect("Failed to create memory system");

    let stats_before = system.stats();

    // Record a high-importance memory (should go to session)
    let exp = Experience {
        content: "Critical decision about system architecture".to_string(),
        experience_type: ExperienceType::Decision, // High importance type
        entities: vec!["architecture".to_string()],
        ..Default::default()
    };
    system.remember(exp, None).expect("Failed to record");

    let stats_after = system.stats();

    // session_memory_count should increase for high-importance memory
    assert!(
        stats_after.session_memory_count > stats_before.session_memory_count,
        "SHO-50 REGRESSION: session_memory_count not incremented for high-importance memory"
    );
}