semantic-memory 0.5.1

Local-first hybrid semantic search (SQLite + FTS5 + usearch 2.25) with bitemporal truth and typed receipts
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
//! Tests for V11 projection storage and import.
#![allow(clippy::expect_used)]
//!
//! Covers:
//! - Projection batch import (claim versions, relation versions, entity aliases, evidence refs)
//! - Idempotent re-import
//! - V11 schema migration from V10
//! - Projection import log tracking
//! - Preferred-open uniqueness
//! - Duplicate-but-not-identical envelopes
//! - Mid-import rollback (invalid record)
//! - Human-confirmed-final protection
//! - Legacy path still works (backward compatibility)

#![allow(deprecated)]

use forge_memory_bridge::PROJECTION_IMPORT_BATCH_V1_SCHEMA;
use semantic_memory::compat::compat_trace_id::TraceId;
use semantic_memory::compat::legacy_import_envelope::{ImportEnvelope, ImportRecord, ImportStatus};
use semantic_memory::{MemoryConfig, MemoryStore, MockEmbedder, ProjectionQuery};
use stack_ids::{ClaimId, ClaimVersionId, EnvelopeId, ScopeKey};
use tempfile::TempDir;
use tokio::time::{sleep, Duration};

fn test_store() -> (MemoryStore, TempDir) {
    let dir = TempDir::new().unwrap();
    let config = MemoryConfig {
        base_dir: dir.path().to_path_buf(),
        ..Default::default()
    };
    let store = MemoryStore::open_with_embedder(config, Box::new(MockEmbedder::new(768))).unwrap();
    (store, dir)
}

fn make_claim_batch(envelope_id: &str, claim_id: &str, content: &str) -> String {
    serde_json::json!({
        "source_envelope_id": envelope_id,
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": format!("digest-{envelope_id}"),
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "trace_ctx": { "trace_id": "trace-001" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [
            {
                "kind": "claim_version",
                "claim_id": claim_id,
                "claim_version_id": format!("{claim_id}-v1"),
                "claim_state": "active",
                "projection_family": "forge_verification",
                "subject_entity_id": "ent-1",
                "predicate": "has_type",
                "object_anchor": "function",
                "scope_key": { "namespace": "test-ns" },
                "valid_from": "2026-01-01T00:00:00Z",
                "valid_to": null,
                "preferred_open": true,
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "contradiction_status": "none",
                "content": content,
                "confidence": 0.95
            }
        ]
    })
    .to_string()
}

fn make_multi_record_batch(envelope_id: &str) -> String {
    serde_json::json!({
        "source_envelope_id": envelope_id,
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": format!("digest-multi-{envelope_id}"),
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [
            {
                "kind": "claim_version",
                "claim_id": "claim-1",
                "claim_version_id": "claim-1-v1",
                "claim_state": "active",
                "projection_family": "forge",
                "subject_entity_id": "ent-1",
                "predicate": "p1",
                "object_anchor": "v1",
                "preferred_open": true,
                "freshness": "current",
                "contradiction_status": "none",
                "content": "claim one",
                "confidence": 0.9
            },
            {
                "kind": "relation_version",
                "relation_version_id": "rel-1-v1",
                "subject_entity_id": "ent-1",
                "predicate": "depends_on",
                "object_anchor": "ent-2",
                "preferred_open": true,
                "source_confidence": 0.8,
                "projection_family": "forge",
                "freshness": "current",
                "contradiction_status": "none"
            },
            {
                "kind": "entity_alias",
                "canonical_entity_id": "ent-1",
                "alias_text": "Entity One",
                "alias_source": "forge_extraction",
                "confidence": 0.9,
                "merge_decision": { "automated": { "algorithm": "bridge_default" } },
                "scope": { "namespace": "test-ns" },
                "review_state": "unreviewed",
                "is_human_confirmed": false,
                "is_human_confirmed_final": false
            },
            {
                "kind": "evidence_ref",
                "claim_id": "claim-1",
                "fetch_handle": "forge://evidence/run-42/artifact-7",
                "source_authority": "forge"
            },
            {
                "kind": "episode",
                "episode_id": "episode-1",
                "document_id": "doc-1",
                "cause_ids": ["claim-1"],
                "effect_type": "code_change",
                "outcome": "success",
                "confidence": 0.7,
                "experiment_id": "exp-1"
            }
        ]
    })
    .to_string()
}

fn make_multi_record_batch_collision(
    envelope_id: &str,
    content_digest: &str,
    marker: &str,
    source_exported_at: &str,
    transformed_at: &str,
) -> String {
    serde_json::json!({
        "source_envelope_id": envelope_id,
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": content_digest,
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": source_exported_at,
        "transformed_at": transformed_at,
        "records": [
            {
                "kind": "claim_version",
                "claim_id": format!("claim-{marker}"),
                "claim_version_id": format!("claim-{marker}-v1"),
                "claim_state": "active",
                "projection_family": "forge",
                "subject_entity_id": "ent-collision",
                "predicate": "has_type",
                "object_anchor": format!("function-{marker}"),
                "preferred_open": true,
                "freshness": "current",
                "contradiction_status": "none",
                "content": format!("claim content {marker}"),
                "confidence": 0.9
            },
            {
                "kind": "relation_version",
                "relation_version_id": format!("rel-{marker}-v1"),
                "subject_entity_id": "ent-collision",
                "predicate": "depends_on",
                "object_anchor": format!("ent-collision-target-{marker}"),
                "preferred_open": true,
                "source_confidence": 0.8,
                "projection_family": "forge",
                "freshness": "current",
                "contradiction_status": "none"
            },
            {
                "kind": "entity_alias",
                "canonical_entity_id": format!("ent-{marker}"),
                "alias_text": format!("Entity {marker}"),
                "alias_source": "forge_extraction",
                "confidence": 0.9,
                "merge_decision": { "automated": { "algorithm": "bridge_default" } },
                "scope": { "namespace": "test-ns" },
                "review_state": "unreviewed",
                "is_human_confirmed": false,
                "is_human_confirmed_final": false
            },
            {
                "kind": "evidence_ref",
                "claim_id": format!("claim-{marker}"),
                "fetch_handle": format!("forge://evidence/{marker}"),
                "source_authority": "forge"
            },
            {
                "kind": "episode",
                "episode_id": format!("episode-{marker}"),
                "document_id": format!("doc-{marker}"),
                "cause_ids": [format!("claim-{marker}")],
                "effect_type": "code_change",
                "outcome": "success",
                "confidence": 0.7,
                "experiment_id": null
            }
        ]
    })
    .to_string()
}

#[allow(clippy::too_many_arguments)]
fn make_scoped_claim_batch(
    envelope_id: &str,
    scope_key: &ScopeKey,
    claim_id: &str,
    claim_version_id: &str,
    content: &str,
    valid_from: &str,
    valid_to: Option<&str>,
    preferred_open: bool,
) -> String {
    serde_json::json!({
        "source_envelope_id": envelope_id,
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": format!("digest-{envelope_id}"),
        "source_authority": "forge",
        "scope_key": scope_key,
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [{
            "kind": "claim_version",
            "claim_id": claim_id,
            "claim_version_id": claim_version_id,
            "claim_state": "active",
            "projection_family": "forge_verification",
            "subject_entity_id": "ent-scope",
            "predicate": "has_type",
            "object_anchor": "function",
            "scope_key": scope_key,
            "valid_from": valid_from,
            "valid_to": valid_to,
            "preferred_open": preferred_open,
            "source_envelope_id": envelope_id,
            "source_authority": "forge",
            "freshness": "current",
            "contradiction_status": "none",
            "content": content,
            "confidence": 0.95
        }]
    })
    .to_string()
}

fn make_verification_relation_batch(
    envelope_id: &str,
    source_exported_at: &str,
    transformed_at: &str,
) -> String {
    serde_json::json!({
        "source_envelope_id": envelope_id,
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": format!("digest-{envelope_id}"),
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": source_exported_at,
        "transformed_at": transformed_at,
        "records": [
            {
                "kind": "relation_version",
                "relation_version_id": "rel-baseline-v1",
                "subject_entity_id": "ent-verification",
                "predicate": "verification_trial_baseline",
                "object_anchor": {
                    "trial_id": "trial-baseline-1",
                    "attempt_id": "attempt-verification-1",
                    "baseline_or_patch": "Baseline",
                    "completed": true
                },
                "scope_key": { "namespace": "test-ns" },
                "preferred_open": true,
                "contradiction_status": "none",
                "source_confidence": 0.9,
                "projection_family": "forge_verification",
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "metadata": {
                    "bundle_id": "bundle-verification-1",
                    "attempt_id": "attempt-verification-1",
                    "trial_id": "trial-baseline-1",
                    "baseline_or_patch": "Baseline"
                }
            },
            {
                "kind": "relation_version",
                "relation_version_id": "rel-patched-v1",
                "subject_entity_id": "ent-verification",
                "predicate": "verification_trial_patched",
                "object_anchor": {
                    "trial_id": "trial-patched-1",
                    "attempt_id": "attempt-verification-1",
                    "baseline_or_patch": "Patched",
                    "completed": true
                },
                "scope_key": { "namespace": "test-ns" },
                "preferred_open": true,
                "contradiction_status": "none",
                "source_confidence": 0.91,
                "projection_family": "forge_verification",
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "metadata": {
                    "bundle_id": "bundle-verification-1",
                    "attempt_id": "attempt-verification-1",
                    "trial_id": "trial-patched-1",
                    "baseline_or_patch": "Patched"
                }
            },
            {
                "kind": "relation_version",
                "relation_version_id": "rel-placebo-v1",
                "subject_entity_id": "ent-verification",
                "predicate": "verification_refutation_placebo",
                "object_anchor": {
                    "artifact_id": "ref-placebo-1",
                    "artifact_type": "Placebo",
                    "outcome": "passed",
                    "details": "no effect for placebo"
                },
                "scope_key": { "namespace": "test-ns" },
                "preferred_open": true,
                "contradiction_status": "none",
                "source_confidence": 0.92,
                "projection_family": "forge_verification",
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "metadata": {
                    "bundle_id": "bundle-verification-1",
                    "artifact_id": "ref-placebo-1",
                    "outcome": "passed"
                }
            },
            {
                "kind": "relation_version",
                "relation_version_id": "rel-dummy-v1",
                "subject_entity_id": "ent-verification",
                "predicate": "verification_refutation_dummy_outcome",
                "object_anchor": {
                    "artifact_id": "ref-dummy-1",
                    "artifact_type": "DummyOutcome",
                    "outcome": "inconclusive",
                    "details": "outcome nullification check incomplete"
                },
                "scope_key": { "namespace": "test-ns" },
                "preferred_open": true,
                "contradiction_status": "none",
                "source_confidence": 0.93,
                "projection_family": "forge_verification",
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "metadata": {
                    "bundle_id": "bundle-verification-1",
                    "artifact_id": "ref-dummy-1",
                    "outcome": "inconclusive"
                }
            },
            {
                "kind": "relation_version",
                "relation_version_id": "rel-subsample-v1",
                "subject_entity_id": "ent-verification",
                "predicate": "verification_refutation_subsample_stability",
                "object_anchor": {
                    "artifact_id": "ref-subsample-1",
                    "artifact_type": "SubsampleStability",
                    "outcome": "failed",
                    "details": "instability across folds"
                },
                "scope_key": { "namespace": "test-ns" },
                "preferred_open": true,
                "contradiction_status": "none",
                "source_confidence": 0.93,
                "projection_family": "forge_verification",
                "source_envelope_id": envelope_id,
                "source_authority": "forge",
                "freshness": "current",
                "metadata": {
                    "bundle_id": "bundle-verification-1",
                    "artifact_id": "ref-subsample-1",
                    "outcome": "failed"
                }
            }
        ]
    })
    .to_string()
}

#[tokio::test]
async fn import_claim_version_succeeds() {
    let (store, _dir) = test_store();
    let batch = make_claim_batch("env-001", "claim-1", "Test claim content");
    let result = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();

    assert_eq!(result.status, "complete");
    assert_eq!(result.record_count, 1);
    assert!(!result.was_duplicate);
    assert_eq!(result.source_envelope_id, "env-001");
}

#[tokio::test]
async fn import_is_idempotent() {
    let (store, _dir) = test_store();
    let batch = make_claim_batch("env-002", "claim-2", "Idempotent claim");

    let r1 = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();
    assert_eq!(r1.status, "complete");
    assert!(!r1.was_duplicate);

    let r2 = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();
    assert_eq!(r2.status, "already_imported");
    assert!(r2.was_duplicate);
}

#[tokio::test]
async fn import_multi_record_batch() {
    let (store, _dir) = test_store();
    let batch = make_multi_record_batch("env-multi");
    let result = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();

    assert_eq!(result.status, "complete");
    assert_eq!(result.record_count, 5);
    assert!(!result.was_duplicate);
}

#[tokio::test]
async fn public_projection_queries_read_imported_rows() {
    let (store, _dir) = test_store();
    let batch = make_multi_record_batch("env-queryable");
    store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();

    let query = ProjectionQuery::new(ScopeKey::namespace_only("test-ns"));
    let claims = store.query_claim_versions(query.clone()).await.unwrap();
    let relations = store.query_relation_versions(query.clone()).await.unwrap();
    let episodes = store.query_episodes(query.clone()).await.unwrap();
    let aliases = store.query_entity_aliases(query.clone()).await.unwrap();
    let evidence = store.query_evidence_refs(query).await.unwrap();

    assert_eq!(claims.len(), 1);
    assert_eq!(relations.len(), 1);
    assert_eq!(episodes.len(), 1);
    assert_eq!(aliases.len(), 1);
    assert_eq!(evidence.len(), 1);
    assert_eq!(claims[0].content, "claim one");
    assert_eq!(relations[0].predicate, "depends_on");
    assert!(
        relations[0].claim_id.is_none(),
        "missing relation claim_id must remain absent, not become an empty identifier"
    );
    assert!(
        relations[0].source_episode_id.is_none(),
        "missing relation source_episode_id must remain absent, not become an empty identifier"
    );
    assert_eq!(episodes[0].effect_type, "code_change");
    assert_eq!(aliases[0].alias_text, "Entity One");
    assert_eq!(
        evidence[0].fetch_handle,
        "forge://evidence/run-42/artifact-7"
    );
    assert!(
        evidence[0].claim_version_id.is_none(),
        "missing evidence claim_version_id must remain absent, not become an empty identifier"
    );
    assert_eq!(
        claims[0].source_exported_at.as_deref(),
        Some("2026-03-07T00:00:00Z")
    );
    assert_eq!(
        claims[0].transformed_at.as_deref(),
        Some("2026-03-07T00:00:01Z")
    );
}

#[tokio::test]
async fn projection_queries_enforce_full_scope() {
    let (store, _dir) = test_store();
    let matching_scope = ScopeKey {
        namespace: "test-ns".into(),
        domain: Some("code".into()),
        workspace_id: Some("ws-1".into()),
        repo_id: Some("repo-1".into()),
    };
    let other_scope = ScopeKey {
        namespace: "test-ns".into(),
        domain: Some("docs".into()),
        workspace_id: Some("ws-2".into()),
        repo_id: Some("repo-2".into()),
    };

    for batch in [
        make_scoped_claim_batch(
            "env-scope-hit",
            &matching_scope,
            "claim-scope-hit",
            "claim-scope-hit-v1",
            "scoped projection hit",
            "2026-01-01T00:00:00Z",
            None,
            true,
        ),
        make_scoped_claim_batch(
            "env-scope-miss",
            &other_scope,
            "claim-scope-miss",
            "claim-scope-miss-v1",
            "scoped projection miss",
            "2026-01-01T00:00:00Z",
            None,
            true,
        ),
    ] {
        store
            .import_projection_batch_json_compat(&batch)
            .await
            .unwrap();
    }

    let mut query = ProjectionQuery::new(matching_scope.clone());
    query.text_query = Some("scoped projection".into());
    let claims = store.query_claim_versions(query).await.unwrap();

    assert_eq!(claims.len(), 1);
    assert_eq!(claims[0].content, "scoped projection hit");
    assert_eq!(claims[0].scope_key, matching_scope);
}

#[tokio::test]
async fn claim_query_filters_by_recorded_at_cutoff() {
    let (store, _dir) = test_store();
    let scope_key = ScopeKey::namespace_only("test-ns");

    let batch_old = make_scoped_claim_batch(
        "env-bitemporal-old",
        &scope_key,
        "claim-bitemporal-old",
        "claim-bitemporal-old-v1",
        "recorded-at cutoff claim historical",
        "2026-01-01T00:00:00Z",
        None,
        true,
    );
    let batch_new = make_scoped_claim_batch(
        "env-bitemporal-new",
        &scope_key,
        "claim-bitemporal-new",
        "claim-bitemporal-new-v1",
        "recorded-at cutoff claim updated",
        "2026-02-01T00:00:00Z",
        None,
        true,
    );

    store
        .import_projection_batch_json_compat(&batch_old)
        .await
        .unwrap();
    sleep(Duration::from_secs(1)).await;
    store
        .import_projection_batch_json_compat(&batch_new)
        .await
        .unwrap();

    let import_log = store
        .query_projection_imports(Some("test-ns"), 10)
        .await
        .unwrap();
    assert!(import_log.len() >= 2, "expected two projection imports");
    let oldest_imported_at = import_log
        .iter()
        .map(|entry| entry.imported_at.clone())
        .min()
        .expect("at least one projection import");
    let latest_imported_at = import_log
        .iter()
        .map(|entry| entry.imported_at.clone())
        .max()
        .expect("at least one projection import");

    let mut historical = ProjectionQuery::new(scope_key.clone());
    historical.text_query = Some("recorded-at cutoff claim".into());
    historical.valid_at = Some("2026-03-01T00:00:00Z".into());
    historical.recorded_at_or_before = Some(oldest_imported_at);
    let historical_claims = store.query_claim_versions(historical).await.unwrap();

    assert_eq!(
        historical_claims.len(),
        1,
        "earliest recorded-at cutoff should exclude claims imported later"
    );
    assert_eq!(
        historical_claims[0].content,
        "recorded-at cutoff claim historical"
    );

    let mut current = ProjectionQuery::new(scope_key);
    current.text_query = Some("recorded-at cutoff claim".into());
    current.valid_at = Some("2026-03-01T00:00:00Z".into());
    current.recorded_at_or_before = Some(latest_imported_at);
    let current_claims = store.query_claim_versions(current).await.unwrap();

    assert_eq!(
        current_claims.len(),
        2,
        "latest recorded-at cutoff should include both rows"
    );
    assert!(
        current_claims
            .iter()
            .any(|claim| claim.content == "recorded-at cutoff claim historical"),
        "historical row should remain visible at a later cutoff"
    );
    assert!(
        current_claims
            .iter()
            .any(|claim| claim.content == "recorded-at cutoff claim updated"),
        "latest row should be visible at the later cutoff"
    );
}

#[tokio::test]
async fn claim_query_valid_at_filters_versions() {
    let (store, _dir) = test_store();
    let scope_key = ScopeKey::namespace_only("test-ns");

    for batch in [
        make_scoped_claim_batch(
            "env-claim-old",
            &scope_key,
            "claim-versioned",
            "claim-versioned-v1",
            "versioned claim old state",
            "2026-01-01T00:00:00Z",
            Some("2026-02-01T00:00:00Z"),
            false,
        ),
        make_scoped_claim_batch(
            "env-claim-current",
            &scope_key,
            "claim-versioned",
            "claim-versioned-v2",
            "versioned claim current state",
            "2026-02-01T00:00:00Z",
            None,
            true,
        ),
    ] {
        store
            .import_projection_batch_json_compat(&batch)
            .await
            .unwrap();
    }

    let mut historical = ProjectionQuery::new(scope_key.clone());
    historical.text_query = Some("versioned claim".into());
    historical.valid_at = Some("2026-01-15T00:00:00Z".into());
    let historical_claims = store.query_claim_versions(historical).await.unwrap();

    let mut current = ProjectionQuery::new(scope_key);
    current.text_query = Some("versioned claim".into());
    current.valid_at = Some("2026-03-15T00:00:00Z".into());
    let current_claims = store.query_claim_versions(current).await.unwrap();

    assert_eq!(historical_claims.len(), 1);
    assert_eq!(historical_claims[0].content, "versioned claim old state");
    assert_eq!(current_claims.len(), 1);
    assert_eq!(current_claims[0].content, "versioned claim current state");
}

#[tokio::test]
async fn claim_query_filters_by_claim_version_id() {
    let (store, _dir) = test_store();
    let scope_key = ScopeKey::namespace_only("test-ns");

    for batch in [
        make_scoped_claim_batch(
            "env-claim-version-filter-old",
            &scope_key,
            "claim-version-filter",
            "claim-version-filter-v1",
            "claim version filter old",
            "2026-01-01T00:00:00Z",
            Some("2026-02-01T00:00:00Z"),
            false,
        ),
        make_scoped_claim_batch(
            "env-claim-version-filter-current",
            &scope_key,
            "claim-version-filter",
            "claim-version-filter-v2",
            "claim version filter current",
            "2026-02-01T00:00:00Z",
            None,
            true,
        ),
    ] {
        store
            .import_projection_batch_json_compat(&batch)
            .await
            .unwrap();
    }

    let mut query = ProjectionQuery::new(scope_key);
    query.claim_id = Some(ClaimId::new("claim-version-filter"));
    query.claim_version_id = Some(ClaimVersionId::new("claim-version-filter-v1"));
    let claims = store.query_claim_versions(query).await.unwrap();

    assert_eq!(
        claims.len(),
        1,
        "claim_version_id filter should narrow to the requested imported version"
    );
    assert_eq!(
        claims[0].claim_version_id.as_str(),
        "claim-version-filter-v1"
    );
    assert_eq!(claims[0].content, "claim version filter old");
}

#[tokio::test]
async fn duplicate_but_different_digest_both_import() {
    let (store, _dir) = test_store();

    let batch1 = make_claim_batch("env-dup", "claim-a", "Content A");
    let r1 = store
        .import_projection_batch_json_compat(&batch1)
        .await
        .unwrap();
    assert_eq!(r1.status, "complete");

    // Same envelope_id but different content_digest
    let batch2 = serde_json::json!({
        "source_envelope_id": "env-dup",
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": "different-digest",
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [{
            "kind": "claim_version",
            "claim_id": "claim-b",
            "claim_version_id": "claim-b-v1",
            "claim_state": "active",
            "projection_family": "forge",
            "subject_entity_id": "ent-2",
            "predicate": "p2",
            "object_anchor": "v2",
            "preferred_open": true,
            "freshness": "current",
            "contradiction_status": "none",
            "content": "Content B",
            "confidence": 0.8
        }]
    })
    .to_string();

    let r2 = store
        .import_projection_batch_json_compat(&batch2)
        .await
        .unwrap();
    assert_eq!(r2.status, "complete");
    assert!(!r2.was_duplicate);
}

#[tokio::test]
async fn duplicate_envelope_id_different_digests_do_not_duplicate_queries() {
    let (store, _dir) = test_store();

    let batch_a = make_multi_record_batch_collision(
        "env-dup-overlap",
        "digest-dup-a",
        "A",
        "2026-03-07T00:00:00Z",
        "2026-03-07T00:00:01Z",
    );
    let batch_b = make_multi_record_batch_collision(
        "env-dup-overlap",
        "digest-dup-b",
        "B",
        "2026-03-08T00:00:00Z",
        "2026-03-08T00:00:01Z",
    );

    store
        .import_projection_batch_json_compat(&batch_a)
        .await
        .unwrap();
    sleep(Duration::from_secs(1)).await;
    store
        .import_projection_batch_json_compat(&batch_b)
        .await
        .unwrap();

    let query = ProjectionQuery::new(ScopeKey::namespace_only("test-ns"));
    let claims = store.query_claim_versions(query.clone()).await.unwrap();
    let relations = store.query_relation_versions(query.clone()).await.unwrap();
    let episodes = store.query_episodes(query.clone()).await.unwrap();
    let aliases = store.query_entity_aliases(query.clone()).await.unwrap();
    let evidence = store.query_evidence_refs(query).await.unwrap();

    assert_eq!(claims.len(), 2);
    assert_eq!(relations.len(), 2);
    assert_eq!(episodes.len(), 2);
    assert_eq!(aliases.len(), 2);
    assert_eq!(evidence.len(), 2);

    let claim_a = claims
        .iter()
        .find(|row| row.claim_id.as_str() == "claim-A")
        .expect("claim-A should be present");
    let claim_b = claims
        .iter()
        .find(|row| row.claim_id.as_str() == "claim-B")
        .expect("claim-B should be present");
    assert_eq!(
        claim_a.source_exported_at.as_deref(),
        Some("2026-03-07T00:00:00Z")
    );
    assert_eq!(
        claim_b.source_exported_at.as_deref(),
        Some("2026-03-08T00:00:00Z")
    );

    let alias_a = aliases
        .iter()
        .find(|row| row.alias_text == "Entity A")
        .expect("alias A should be present");
    let alias_b = aliases
        .iter()
        .find(|row| row.alias_text == "Entity B")
        .expect("alias B should be present");
    assert_eq!(
        alias_a.source_exported_at.as_deref(),
        Some("2026-03-07T00:00:00Z")
    );
    assert_eq!(
        alias_b.source_exported_at.as_deref(),
        Some("2026-03-08T00:00:00Z")
    );

    let evidence_a = evidence
        .iter()
        .find(|row| row.fetch_handle == "forge://evidence/A")
        .expect("evidence A should be present");
    let evidence_b = evidence
        .iter()
        .find(|row| row.fetch_handle == "forge://evidence/B")
        .expect("evidence B should be present");
    assert_eq!(
        evidence_a.source_exported_at.as_deref(),
        Some("2026-03-07T00:00:00Z")
    );
    assert_eq!(
        evidence_b.source_exported_at.as_deref(),
        Some("2026-03-08T00:00:00Z")
    );
}

#[tokio::test]
async fn invalid_batch_json_rejected() {
    let (store, _dir) = test_store();
    let err = store
        .import_projection_batch_json_compat("not valid json")
        .await
        .unwrap_err();
    assert_eq!(err.kind(), "import_invalid");
}

#[tokio::test]
async fn missing_required_fields_rejected() {
    let (store, _dir) = test_store();
    let batch = serde_json::json!({
        "source_envelope_id": "env-bad",
        "records": []
    })
    .to_string();

    let err = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), "import_invalid");
}

#[tokio::test]
async fn unknown_record_kind_rejected() {
    let (store, _dir) = test_store();
    let batch = serde_json::json!({
        "source_envelope_id": "env-unknown",
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": "digest-unknown",
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [{
            "kind": "unknown_type",
            "data": "foo"
        }]
    })
    .to_string();

    let err = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap_err();
    assert_eq!(err.kind(), "import_invalid");
}

#[tokio::test]
async fn legacy_import_envelope_still_works() {
    // Backward compatibility: the old import_envelope() path must still function
    let (store, _dir) = test_store();

    let envelope = ImportEnvelope {
        envelope_id: EnvelopeId::new("legacy-env-001"),
        schema_version: "1.0".into(),
        content_digest: "legacy-digest-001".into(),
        source_authority: "forge".into(),
        trace_id: Some(TraceId::new("trace-legacy")),
        namespace: "test-ns".into(),
        records: vec![ImportRecord::Fact {
            content: "Legacy fact content".into(),
            source: Some("test".into()),
            metadata: None,
        }],
    };

    let receipt = store.import_envelope(&envelope).await.unwrap();
    assert_eq!(receipt.status, ImportStatus::Complete);
    assert_eq!(receipt.record_count, 1);
    assert!(!receipt.was_duplicate);
}

#[tokio::test]
async fn entity_alias_review_state_persisted() {
    let (store, _dir) = test_store();

    let batch = serde_json::json!({
        "source_envelope_id": "env-alias",
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": "digest-alias",
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [{
            "kind": "entity_alias",
            "canonical_entity_id": "ent-1",
            "alias_text": "Entity One",
            "alias_source": "forge_extraction",
            "confidence": 0.85,
            "merge_decision": { "automated": { "algorithm": "exact_match" } },
            "scope": { "namespace": "test-ns" },
            "review_state": "pending_review",
            "is_human_confirmed": false,
            "is_human_confirmed_final": false
        }]
    })
    .to_string();

    let result = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();
    assert_eq!(result.status, "complete");
    // The alias is imported with pending_review state (durable, survives restart)
    // Re-opening the store should still find it
}

#[tokio::test]
async fn evidence_ref_audit_only() {
    let (store, _dir) = test_store();

    let batch = serde_json::json!({
        "source_envelope_id": "env-evidence",
        "schema_version": PROJECTION_IMPORT_BATCH_V1_SCHEMA,
        "export_schema_version": "export_envelope_v1",
        "content_digest": "digest-evidence",
        "source_authority": "forge",
        "scope_key": { "namespace": "test-ns" },
        "source_exported_at": "2026-03-07T00:00:00Z",
        "transformed_at": "2026-03-07T00:00:01Z",
        "records": [{
            "kind": "evidence_ref",
            "claim_id": "claim-x",
            "claim_version_id": "claim-x-v1",
            "fetch_handle": "forge://evidence/run-42/artifact-7",
            "source_authority": "forge"
        }]
    })
    .to_string();

    let result = store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();
    assert_eq!(result.status, "complete");
    assert_eq!(result.record_count, 1);
}

#[tokio::test]
async fn relation_versions_query_verification_trials_and_refutations() {
    let (store, _dir) = test_store();
    let batch = make_verification_relation_batch(
        "env-verification-relations",
        "2026-03-07T00:00:00Z",
        "2026-03-07T00:00:01Z",
    );

    store
        .import_projection_batch_json_compat(&batch)
        .await
        .unwrap();

    let mut query = ProjectionQuery::new(ScopeKey::namespace_only("test-ns"));
    query.text_query = Some("verification".into());
    let relations = store.query_relation_versions(query).await.unwrap();

    assert_eq!(relations.len(), 5);
    assert!(
        relations
            .iter()
            .any(|relation| relation.predicate == "verification_trial_baseline"),
        "baseline trial relation should be present"
    );
    assert!(
        relations
            .iter()
            .any(|relation| relation.predicate == "verification_trial_patched"),
        "patched trial relation should be present"
    );
    assert!(
        relations
            .iter()
            .any(|relation| relation.predicate == "verification_refutation_placebo"),
        "placebo refutation relation should be present"
    );
    assert!(
        relations
            .iter()
            .any(|relation| relation.predicate == "verification_refutation_dummy_outcome"),
        "dummy outcome refutation relation should be present"
    );
    assert!(
        relations
            .iter()
            .any(|relation| relation.predicate == "verification_refutation_subsample_stability"),
        "subsample stability refutation relation should be present"
    );

    let baseline = relations
        .iter()
        .find(|relation| relation.predicate == "verification_trial_baseline")
        .expect("baseline trial relation should exist");
    let patched = relations
        .iter()
        .find(|relation| relation.predicate == "verification_trial_patched")
        .expect("patched trial relation should exist");
    let dummy = relations
        .iter()
        .find(|relation| relation.predicate == "verification_refutation_dummy_outcome")
        .expect("dummy outcome refutation relation should exist");
    let subsample = relations
        .iter()
        .find(|relation| relation.predicate == "verification_refutation_subsample_stability")
        .expect("subsample refutation relation should exist");

    assert_eq!(
        baseline
            .metadata
            .as_ref()
            .and_then(|m| m.get("attempt_id"))
            .and_then(|value| value.as_str()),
        Some("attempt-verification-1")
    );
    assert_eq!(
        baseline
            .metadata
            .as_ref()
            .and_then(|m| m.get("trial_id"))
            .and_then(|value| value.as_str()),
        Some("trial-baseline-1")
    );
    assert_eq!(
        patched
            .metadata
            .as_ref()
            .and_then(|m| m.get("trial_id"))
            .and_then(|value| value.as_str()),
        Some("trial-patched-1")
    );
    assert_eq!(
        dummy
            .metadata
            .as_ref()
            .and_then(|m| m.get("outcome"))
            .and_then(|value| value.as_str()),
        Some("inconclusive")
    );
    assert_eq!(
        subsample
            .metadata
            .as_ref()
            .and_then(|m| m.get("outcome"))
            .and_then(|value| value.as_str()),
        Some("failed")
    );
}