vipune 0.2.5

A minimal memory layer for AI agents
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
//! Integration tests testing vipune library API from external crate perspective.

use std::env;
use std::path::PathBuf;

use vipune::errors::Error;
use vipune::{
    Config, IngestPolicy, MAX_INPUT_LENGTH, MAX_SEARCH_LIMIT, MemoryStore, detect_project,
};

/// Test basic memory add and search operations.
#[test]
fn test_memory_store_add_then_search_returns_matching_memory() {
    // Create a temporary database
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Add a memory
    let project_id = "test-project";
    let memory_id = match store
        .add_with_conflict(project_id, "Alice works at Microsoft", None, false)
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    assert!(!memory_id.is_empty());

    // Search for the memory
    let results = store
        .search(project_id, "where does alice work", 10, 0.0)
        .expect("Failed to search");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].content, "Alice works at Microsoft");
    // Similarity score is present (value depends on model)

    // Clean up
    std::fs::remove_file(db_path).ok();
}

/// Test that path traversal strings are rejected by MemoryStore::new().
#[test]
fn test_memory_store_new_with_path_traversal_returns_error() {
    let config = Config::default();

    // Try to create a store with path traversal
    let traversal_path = PathBuf::from("../../../etc/passwd");

    let result = MemoryStore::new(&traversal_path, &config.embedding_model, config.clone());

    assert!(result.is_err());
}

/// Test that empty input is rejected by add().
#[test]
fn test_add_with_empty_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let result = store.add_with_conflict("test", "", None, false);
    assert!(result.is_err());
    if !matches!(result.as_ref().unwrap_err(), Error::EmptyInput) {
        panic!("Expected EmptyInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that oversized input is rejected by add().
#[test]
fn test_add_with_oversized_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Create input longer than MAX_INPUT_LENGTH
    let long_text = "x".repeat(MAX_INPUT_LENGTH + 1);
    let result = store.add_with_conflict("test", &long_text, None, false);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that empty input is rejected by search().
#[test]
fn test_search_with_empty_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let result = store.search("test", "", 10, 0.0);
    assert!(result.is_err());
    if !matches!(result.as_ref().unwrap_err(), Error::EmptyInput) {
        panic!("Expected EmptyInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that oversized input is rejected by search().
#[test]
fn test_search_with_oversized_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Create input longer than MAX_INPUT_LENGTH
    let long_query = "x".repeat(MAX_INPUT_LENGTH + 1);
    let result = store.search("test", &long_query, 10, 0.0);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that Config::default() works without environment variables.
#[test]
fn test_config_default_with_no_env_vars_returns_valid_config() {
    // Clear environment variables that might affect config
    unsafe {
        env::remove_var("VIPUNE_DATABASE_PATH");
        env::remove_var("VIPUNE_EMBEDDING_MODEL");
        env::remove_var("VIPUNE_MODEL_CACHE");
        env::remove_var("VIPUNE_SIMILARITY_THRESHOLD");
        env::remove_var("VIPUNE_RECENCY_WEIGHT");
    }

    let config = Config::default();

    assert!(config.database_path.ends_with(".vipune/memories.db"));
    assert_eq!(config.embedding_model, "BAAI/bge-small-en-v1.5");
    assert!(config.model_cache.ends_with(".vipune/models"));
    assert_eq!(config.similarity_threshold, 0.85);
    assert_eq!(config.recency_weight, 0.3);
}

/// Test that detect_project returns a non-empty string.
#[test]
fn test_detect_project_in_git_repo_returns_project_id() {
    let project_id = detect_project(None);
    assert!(!project_id.is_empty());

    // Test with explicit override
    let project_id_override = detect_project(Some("my-custom-project"));
    assert_eq!(project_id_override, "my-custom-project");
}

/// Test that Memory::fields are accessible.
#[test]
fn test_memory_with_stored_content_returns_expected_fields() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Add memory with metadata
    let memory_id = match store
        .add_with_conflict(
            "test-project",
            "Test content",
            Some(r#"{"key": "value"}"#),
            false,
        )
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Get the memory
    let memory = store
        .get(&memory_id)
        .expect("Failed to get memory")
        .expect("Memory not found");

    assert_eq!(memory.id, memory_id);
    assert_eq!(memory.project_id, "test-project");
    assert_eq!(memory.content, "Test content");
    assert_eq!(memory.metadata, Some(r#"{"key": "value"}"#.to_string()));
    assert!(!memory.created_at.is_empty());
    assert!(!memory.updated_at.is_empty());
    // similarity is None when getting directly
    assert!(memory.similarity.is_none());

    std::fs::remove_file(db_path).ok();
}

/// Test hybrid search functionality.
#[test]
fn test_search_hybrid_with_test_memories_returns_fused_results() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-hybrid";

    // Add multiple memories
    match store
        .add_with_conflict(project_id, "Authentication uses JWT tokens", None, false)
        .expect("Failed to add memory 1")
    {
        vipune::AddResult::Added { .. } => {}
        _ => panic!("Expected AddResult::Added"),
    }
    match store
        .add_with_conflict(project_id, "User management system", None, false)
        .expect("Failed to add memory 2")
    {
        vipune::AddResult::Added { .. } => {}
        _ => panic!("Expected AddResult::Added"),
    }

    // Search using hybrid
    let results = store
        .search_hybrid(project_id, "auth token", 10, 0.0)
        .expect("Failed to search hybrid");

    assert!(!results.is_empty());
    assert_eq!(results[0].project_id, project_id);

    std::fs::remove_file(db_path).ok();
}

/// Test that update() validates empty input.
#[test]
fn test_update_with_empty_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let memory_id = match store
        .add_with_conflict("test", "Original content", None, false)
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Try to update with empty string
    let result = store.update(&memory_id, "");
    assert!(result.is_err());
    if !matches!(result.as_ref().unwrap_err(), Error::EmptyInput) {
        panic!("Expected EmptyInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that update() validates oversized input.
#[test]
fn test_update_with_oversized_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let memory_id = match store
        .add_with_conflict("test", "Original content", None, false)
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Try to update with oversized content
    let long_text = "x".repeat(MAX_INPUT_LENGTH + 1);
    let result = store.update(&memory_id, &long_text);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that search() validates limit=0.
#[test]
fn test_search_with_zero_limit_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Try to search with limit=0
    let result = store.search("test", "query", 0, 0.0);
    assert!(result.is_err());
    if let Error::InvalidInput(msg) = &result.as_ref().unwrap_err() {
        assert!(msg.contains("Limit must be greater than 0"));
    } else {
        panic!("Expected InvalidInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that search() validates limit maximum.
#[test]
fn test_search_with_limit_over_max_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Try to search with excessively large limit
    let result = store.search("test", "query", 10_001, 0.0);
    assert!(result.is_err());
    if let Error::InvalidInput(msg) = &result.as_ref().unwrap_err() {
        assert!(msg.contains("exceeds maximum allowed"));
    } else {
        panic!("Expected InvalidInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that whitespace-only input is rejected.
#[test]
fn test_add_with_whitespace_only_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Try to add whitespace-only content
    let result = store.add_with_conflict("test", "   ", None, false);
    assert!(result.is_err());
    assert!(matches!(result.as_ref().unwrap_err(), Error::EmptyInput));

    // Try to search with whitespace-only query
    let result = store.search("test", "\t\n", 10, 0.0);
    assert!(result.is_err());
    assert!(matches!(result.as_ref().unwrap_err(), Error::EmptyInput));

    std::fs::remove_file(db_path).ok();
}

/// Test that symlink pointing outside temp dir is handled correctly.
#[cfg(unix)]
#[test]
fn test_memory_store_new_with_symlink_traversal_returns_error() {
    use std::os::unix::fs;

    let temp_dir = env::temp_dir();
    let test_dir = temp_dir.join(format!("vipune_symlink_test_{}", uuid::Uuid::new_v4()));
    std::fs::create_dir_all(&test_dir).expect("Failed to create test directory");

    let config = Config::default();

    // Create a symlink to a non-existent path outside the test dir
    let symlink_path = test_dir.join("symlink.db");
    let target_path = PathBuf::from("/nonexistent/path/database.db");
    fs::symlink(&target_path, &symlink_path).expect("Failed to create symlink");

    // Try to create store with symlink path
    // Path traversal guard rejects paths with parent-dir components before any filesystem access
    let result = MemoryStore::new(&symlink_path, &config.embedding_model, config.clone());

    // Clean up (always runs even if assertion fails)
    std::fs::remove_file(&symlink_path).ok();
    std::fs::remove_dir(&test_dir).ok();

    // Should fail (path traversal prevention or database open failure)
    assert!(
        result.is_err(),
        "MemoryStore creation should fail for inaccessible symlink"
    );
}

/// Test that path with parent-dir component is rejected.
#[test]
fn test_memory_store_new_with_parent_dir_component_returns_error() {
    let config = Config::default();

    // Use a path with parent-dir component
    let traversal_path = PathBuf::from("/tmp/../etc/evil.db");

    let result = MemoryStore::new(&traversal_path, &config.embedding_model, config.clone());

    // Should be rejected with parent dir error message
    match result {
        Err(Error::Config(msg)) => {
            assert!(
                msg.contains("..") || msg.contains("escape"),
                "Expected parent directory rejection message, got: {}",
                msg
            );
        }
        Err(e) => {
            panic!(
                "Expected Config error with parent dir rejection, got: {}",
                e
            );
        }
        Ok(_) => {
            panic!("MemoryStore creation should fail for path with parent directory component");
        }
    }
}

/// Test that MAX_SEARCH_LIMIT constant is accessible from library API.
#[test]
fn test_constant_max_search_limit_is_accessible() {
    assert_eq!(MAX_SEARCH_LIMIT, 10_000);
}

/// Test that list() validates limit=0.
#[test]
fn test_list_with_zero_limit_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Try to list with limit=0
    let result = store.list("test", 0);
    assert!(result.is_err());
    if let Error::InvalidInput(msg) = &result.as_ref().unwrap_err() {
        assert!(msg.contains("Limit must be greater than 0"));
    } else {
        panic!("Expected InvalidInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that list() validates limit maximum.
#[test]
fn test_list_with_limit_over_max_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Try to list with excessively large limit
    let result = store.list("test", 10_001);
    assert!(result.is_err());
    if let Error::InvalidInput(msg) = &result.as_ref().unwrap_err() {
        assert!(msg.contains("exceeds maximum allowed"));
    } else {
        panic!("Expected InvalidInput error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test list() regression coverage for existing behavior.
#[test]
fn test_list_regression_coverage() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    // Add multiple memories
    let _id1 = store
        .add_with_conflict(project_id, "first memory", None, true)
        .expect("Failed to add memory");
    let _id2 = store
        .add_with_conflict(project_id, "second memory", None, true)
        .expect("Failed to add memory");
    let _id3 = store
        .add_with_conflict(project_id, "third memory", None, true)
        .expect("Failed to add memory");

    // Test ordering (newest first)
    let results = store.list(project_id, 10).expect("Failed to list");
    assert_eq!(results.len(), 3);
    assert_eq!(results[0].content, "third memory");
    assert_eq!(results[1].content, "second memory");
    assert_eq!(results[2].content, "first memory");

    // Test limit
    let results = store.list(project_id, 2).expect("Failed to list");
    assert_eq!(results.len(), 2);
    assert_eq!(results[0].content, "third memory");

    // Test project isolation
    let _id4 = store
        .add_with_conflict("other-project", "other memory", None, true)
        .expect("Failed to add memory");
    let project1_results = store.list(project_id, 10).expect("Failed to list");
    assert_eq!(project1_results.len(), 3);

    // Test empty project
    let empty_results = store
        .list("nonexistent_project", 10)
        .expect("Failed to list");
    assert_eq!(empty_results.len(), 0);

    std::fs::remove_file(db_path).ok();
}

/// Test list_since() with timezone offset RFC3339 timestamps.
#[test]
fn test_list_since_with_timezone_offset() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    // Add memories with controlled timestamps
    let _old = store
        .add_with_conflict(project_id, "old memory", None, true)
        .expect("Failed to add memory");

    // Wait at least 1ms to ensure different timestamps
    std::thread::sleep(std::time::Duration::from_millis(10));

    let _new = store
        .add_with_conflict(project_id, "new memory", None, true)
        .expect("Failed to add memory");

    // Test with UTC timestamp (should succeed and only return newer)
    let now = chrono::Utc::now();
    let one_minute_ago = (now - chrono::Duration::minutes(1)).to_rfc3339();
    let results = store
        .list_since(project_id, &one_minute_ago, 10)
        .expect("Failed to list");
    // Should only return "new memory" as it's more recent than one minute ago
    assert!(results.len() >= 1);
    assert!(results.iter().any(|m| m.content == "new memory"));

    std::fs::remove_file(db_path).ok();
}

/// Test list_since() timestamp precision equivalence.
#[test]
fn test_list_since_timestamp_precision_equivalence() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    let _id = store
        .add_with_conflict(project_id, "test memory", None, true)
        .expect("Failed to add memory");

    // Wait to ensure timestamp difference
    std::thread::sleep(std::time::Duration::from_millis(10));

    // Query with and without fractional seconds - should behave identically
    let now = chrono::Utc::now();
    let two_seconds_ago = (now - chrono::Duration::seconds(2)).to_rfc3339();

    let results1 = store
        .list_since(project_id, &two_seconds_ago, 10)
        .expect("Failed to list");

    let results2 = store
        .list_since(project_id, &two_seconds_ago, 10)
        .expect("Failed to list");

    // Results should be identical (same query, same results)
    assert_eq!(results1.len(), results2.len());
    if results1.len() > 0 && results2.len() > 0 {
        assert_eq!(results1[0].id, results2[0].id);
    }

    std::fs::remove_file(db_path).ok();
}

/// Test get_many() with duplicate IDs returns stable behavior.
#[test]
fn test_get_many_with_duplicate_ids() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    let id1 = match store
        .add_with_conflict(project_id, "first", None, true)
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    let id2 = match store
        .add_with_conflict(project_id, "second", None, true)
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Query with duplicate IDs
    let results = store
        .get_many(&[&id1, &id2, &id1, &id2])
        .expect("Failed to get many");
    assert_eq!(results.len(), 4);
    assert_eq!(results[0].as_ref().unwrap().id, id1);
    assert_eq!(results[1].as_ref().unwrap().id, id2);
    assert_eq!(results[2].as_ref().unwrap().id, id1);
    assert_eq!(results[3].as_ref().unwrap().id, id2);

    std::fs::remove_file(db_path).ok();
}

/// Test that add() succeeds at exactly MAX_INPUT_LENGTH.
#[test]
fn test_add_at_exactly_max_input_length_returns_success() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Create input exactly at MAX_INPUT_LENGTH
    let exact_text = "x".repeat(MAX_INPUT_LENGTH);
    let result = store.add_with_conflict("test", &exact_text, None, false);
    assert!(
        result.is_ok(),
        "Should accept input at exactly MAX_INPUT_LENGTH"
    );

    std::fs::remove_file(db_path).ok();
}

/// Test that add() rejects input one character over MAX_INPUT_LENGTH.
#[test]
fn test_add_one_over_max_input_length_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Create input one character over MAX_INPUT_LENGTH
    let too_long_text = "x".repeat(MAX_INPUT_LENGTH + 1);
    let result = store.add_with_conflict("test", &too_long_text, None, false);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that search_hybrid() validates empty input.
#[test]
fn test_search_hybrid_with_empty_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let result = store.search_hybrid("test", "", 10, 0.0);
    assert!(result.is_err());
    assert!(matches!(result.as_ref().unwrap_err(), Error::EmptyInput));

    std::fs::remove_file(db_path).ok();
}

/// Test that search_hybrid() validates oversized input.
#[test]
fn test_search_hybrid_with_oversized_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let long_query = "x".repeat(MAX_INPUT_LENGTH + 1);
    let result = store.search_hybrid("test", &long_query, 10, 0.0);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that ingest with ConflictAware policy maps to existing conflict behavior.
#[test]
fn test_ingest_conflict_aware_policy_maps_to_existing_behavior() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    // Add first memory
    let result = store
        .ingest(
            project_id,
            "Alice works at Microsoft",
            None,
            IngestPolicy::ConflictAware,
        )
        .expect("Failed to add memory");
    assert!(
        matches!(result, vipune::AddResult::Added { .. }),
        "First add should succeed with ConflictAware policy"
    );

    // Add duplicate content - should detect conflict
    let result = store
        .ingest(
            project_id,
            "Alice works at Microsoft",
            None,
            IngestPolicy::ConflictAware,
        )
        .expect("Failed to check conflicts");
    assert!(
        matches!(result, vipune::AddResult::Conflicts { .. }),
        "Duplicate content should return conflicts with ConflictAware policy"
    );

    std::fs::remove_file(db_path).ok();
}

/// Test that ingest with Force policy bypasses conflict detection.
#[test]
fn test_ingest_force_policy_bypasses_conflicts() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let project_id = "test-project";

    // Add first memory
    let _id1 = match store
        .ingest(
            project_id,
            "Alice works at Microsoft",
            None,
            IngestPolicy::ConflictAware,
        )
        .expect("Failed to add memory")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("First add should succeed"),
    };

    // Add duplicate content with Force - should succeed regardless
    let id2 = match store
        .ingest(
            project_id,
            "Alice works at Microsoft",
            None,
            IngestPolicy::Force,
        )
        .expect("Failed to force add")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Force policy should always return Added"),
    };

    // Verify both memories exist
    let results = store.list(project_id, 10).expect("Failed to list memories");
    assert_eq!(
        results.len(),
        2,
        "Both memories should exist after Force add"
    );
    assert!(
        results.iter().any(|m| m.id == id2),
        "Second memory should be stored with Force policy"
    );

    std::fs::remove_file(db_path).ok();
}

/// Test that ingest validates empty input.
#[test]
fn test_ingest_with_empty_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Test both policies reject empty input
    let result = store.ingest("test", "", None, IngestPolicy::ConflictAware);
    assert!(result.is_err());
    assert!(matches!(result.as_ref().unwrap_err(), Error::EmptyInput));

    let result = store.ingest("test", "", None, IngestPolicy::Force);
    assert!(result.is_err());
    assert!(matches!(result.as_ref().unwrap_err(), Error::EmptyInput));

    std::fs::remove_file(db_path).ok();
}

/// Test that ingest validates oversized input.
#[test]
fn test_ingest_with_oversized_input_returns_error() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    let long_text = "x".repeat(MAX_INPUT_LENGTH + 1);

    // Test both policies reject oversized input
    let result = store.ingest("test", &long_text, None, IngestPolicy::ConflictAware);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    let result = store.ingest("test", &long_text, None, IngestPolicy::Force);
    assert!(result.is_err());
    if let Error::InputTooLong {
        max_length,
        actual_length,
    } = &result.as_ref().unwrap_err()
    {
        assert_eq!(*max_length, MAX_INPUT_LENGTH);
        assert_eq!(*actual_length, MAX_INPUT_LENGTH + 1);
    } else {
        panic!("Expected InputTooLong error");
    }

    std::fs::remove_file(db_path).ok();
}

/// Test that ingest works with metadata.
#[test]
fn test_ingest_with_metadata_succeeds() {
    let temp_dir = env::temp_dir();
    let db_path = temp_dir.join(format!("vipune_test_{}.db", uuid::Uuid::new_v4()));

    let config = Config::default();
    let mut store = MemoryStore::new(db_path.as_path(), &config.embedding_model, config.clone())
        .expect("Failed to create store");

    // Test ConflictAware with metadata
    let id1 = match store
        .ingest(
            "test-project",
            "Test content",
            Some(r#"{"source": "manual"}"#),
            IngestPolicy::ConflictAware,
        )
        .expect("Failed to ingest")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Test Force with metadata
    let id2 = match store
        .ingest(
            "test-project",
            "Another test",
            Some(r#"{"source": "import"}"#),
            IngestPolicy::Force,
        )
        .expect("Failed to ingest")
    {
        vipune::AddResult::Added { id } => id,
        _ => panic!("Expected AddResult::Added"),
    };

    // Verify metadata was stored
    let memory1 = store.get(&id1).expect("Failed to get").expect("Not found");
    assert_eq!(
        memory1.metadata.as_ref().unwrap(),
        r#"{"source": "manual"}"#
    );

    let memory2 = store.get(&id2).expect("Failed to get").expect("Not found");
    assert_eq!(
        memory2.metadata.as_ref().unwrap(),
        r#"{"source": "import"}"#
    );

    std::fs::remove_file(db_path).ok();
}