mempill-core 0.2.0

Core engine for mempill — a bi-temporal, append-only claim store with a deterministic adjudication gate and oracle resolution for temporally-correct AI-agent memory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
//! Shared persistence conformance harness.
//!
//! `run_persistence_conformance` exercises every `PersistencePort` method
//! and panics on any deviation from the expected contract.
//!
//! `run_history_conformance` exercises the history timeline logic against a real store.
//!
//! Both `mempill-sqlite` and `mempill-postgres` activate `mempill-core/test-support`
//! in dev-dependencies and call both functions to verify behavioral parity.
//!
//! Each sub-test uses DISTINCT agent_ids so they do not interfere on a shared store.

#[cfg(any(test, feature = "test-support"))]
use chrono::Utc;
#[cfg(any(test, feature = "test-support"))]
use uuid::Uuid;

#[cfg(any(test, feature = "test-support"))]
use mempill_types::{
    claim::{Cardinality, Claim, Confidence, Criticality, Fact},
    disposition::Disposition,
    edge::{ClaimEdge, EdgeKind},
    identity::{AgentId, ClaimRef},
    ledger::{LedgerEntry, LedgerEventKind},
    provenance::{ExternalAnchor, ExternalKind, ProvenanceLabel},
    time::{TransactionTime, ValidTime},
    validity::{AssertionKind, ValidityAssertion},
};

#[cfg(any(test, feature = "test-support"))]
use crate::ports::persistence::PersistencePort;

// ── Builder helpers ───────────────────────────────────────────────────────────

#[cfg(any(test, feature = "test-support"))]
fn make_claim(agent_id: &AgentId, subject: &str, predicate: &str) -> Claim {
    Claim::new(
        ClaimRef::new_random(),
        agent_id.clone(),
        Fact {
            subject: subject.to_owned(),
            predicate: predicate.to_owned(),
            value: serde_json::json!("test-value"),
        },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(Utc::now()),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    )
}

#[cfg(any(test, feature = "test-support"))]
fn make_ledger_entry(agent_id: &AgentId, claim_ref: &ClaimRef) -> LedgerEntry {
    LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent_id.clone(),
        claim_ref: claim_ref.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(Utc::now()),
    }
}

#[cfg(any(test, feature = "test-support"))]
fn make_validity_assertion(agent_id: &AgentId, claim_ref: &ClaimRef) -> ValidityAssertion {
    ValidityAssertion {
        assertion_ref: Uuid::new_v4(),
        agent_id: agent_id.clone(),
        target_claim: claim_ref.clone(),
        kind: AssertionKind::Bound { bound_at: Utc::now() },
        provenance: ProvenanceLabel::External(ExternalKind::UserAsserted),
        confidence: Confidence { value_confidence: 0.9, valid_time_confidence: 0.9 },
        asserted_at: TransactionTime(Utc::now()),
    }
}

#[cfg(any(test, feature = "test-support"))]
fn make_edge(agent_id: &AgentId, from: ClaimRef, to: ClaimRef, kind: EdgeKind) -> ClaimEdge {
    ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent_id.clone(),
        from_claim: from,
        to_claim: to,
        kind,
        created_at: TransactionTime(Utc::now()),
    }
}

// ── Public entry point ────────────────────────────────────────────────────────

/// Run the full persistence conformance suite against `store`.
///
/// Each sub-test uses a distinct `AgentId` to avoid cross-contamination on a shared store.
/// Panics on any contract violation with a descriptive message.
#[cfg(any(test, feature = "test-support"))]
pub fn run_persistence_conformance<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    test_begin_commit_roundtrip(store);
    test_append_all_four_tables(store);
    test_rollback_leaves_zero_rows(store);
    test_load_subject_line_ordering(store);
    test_load_lineage_multi_hop(store);
    test_load_edges_for_ordering(store);
    test_edge_uniqueness_constraint(store);
    test_load_validity_assertions_ordering(store);
    test_load_ledger_with_from(store);
    test_load_injected_claims(store);
    test_load_claim_missing(store);
    test_load_edges_for_empty(store);
    test_load_ledger_for_claims_scoped(store);
}

/// Run the disposition-scope correctness suite.
///
/// Proves that `load_ledger_for_claims` returns complete dispositions for the
/// queried claims, and that `query_memory` returns the correct live belief on a
/// subject-line whose superseded claim has a disposition event that would fall
/// outside a small agent-wide cap — the silent-wrong-belief-at-scale bug.
#[cfg(any(test, feature = "test-support"))]
pub fn run_disposition_scope_conformance<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    test_superseded_claim_excluded_despite_large_agent_ledger(store);
}

// ── Sub-tests ─────────────────────────────────────────────────────────────────

/// begin_atomic → append_claim → commit → load_claim returns Some with fields intact.
#[cfg(any(test, feature = "test-support"))]
fn test_begin_commit_roundtrip<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t1".into());
    let claim = make_claim(&agent, "user", "favourite_colour");
    let claim_ref = claim.claim_ref().clone();

    let mut txn = store
        .begin_atomic(&agent)
        .expect("conformance[t1]: begin_atomic must succeed");
    store
        .append_claim(&mut txn, &claim)
        .expect("conformance[t1]: append_claim must succeed");
    store.commit(txn).expect("conformance[t1]: commit must succeed");

    let loaded = store
        .load_claim(&agent, &claim_ref)
        .expect("conformance[t1]: load_claim must not error");
    let loaded = loaded.expect("conformance[t1]: load_claim must return Some after commit");

    assert_eq!(
        loaded.claim_ref(),
        &claim_ref,
        "conformance[t1]: claim_ref must round-trip"
    );
    assert_eq!(
        loaded.fact().subject,
        "user",
        "conformance[t1]: subject must be preserved"
    );
    assert_eq!(
        loaded.fact().predicate,
        "favourite_colour",
        "conformance[t1]: predicate must be preserved"
    );
}

/// append claim + validity + ledger + edge in ONE txn, commit, read each back.
#[cfg(any(test, feature = "test-support"))]
fn test_append_all_four_tables<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t2".into());
    let claim = make_claim(&agent, "user", "language");
    let claim_ref = claim.claim_ref().clone();
    let validity = make_validity_assertion(&agent, &claim_ref);
    let ledger = make_ledger_entry(&agent, &claim_ref);
    let claim2 = make_claim(&agent, "user", "location");
    let claim2_ref = claim2.claim_ref().clone();
    let edge = make_edge(&agent, claim_ref.clone(), claim2_ref.clone(), EdgeKind::DependsOn);

    let mut txn = store
        .begin_atomic(&agent)
        .expect("conformance[t2]: begin_atomic must succeed");

    // Must insert claim2 before the edge (FK constraint)
    store
        .append_claim(&mut txn, &claim)
        .expect("conformance[t2]: append_claim must succeed");
    store
        .append_claim(&mut txn, &claim2)
        .expect("conformance[t2]: append_claim2 must succeed");
    store
        .append_validity_assertion(&mut txn, &validity)
        .expect("conformance[t2]: append_validity_assertion must succeed");
    store
        .append_ledger_entry(&mut txn, &ledger)
        .expect("conformance[t2]: append_ledger_entry must succeed");
    store
        .append_claim_edge(&mut txn, &edge)
        .expect("conformance[t2]: append_claim_edge must succeed");

    store.commit(txn).expect("conformance[t2]: commit must succeed");

    // Read back claim
    let loaded_claim = store
        .load_claim(&agent, &claim_ref)
        .expect("conformance[t2]: load_claim must not error")
        .expect("conformance[t2]: load_claim must return Some");
    assert_eq!(loaded_claim.claim_ref(), &claim_ref, "conformance[t2]: claim_ref must match");

    // Read back validity assertions
    let assertions = store
        .load_validity_assertions_for(&agent, &claim_ref)
        .expect("conformance[t2]: load_validity_assertions_for must not error");
    assert_eq!(
        assertions.len(),
        1,
        "conformance[t2]: must have 1 validity assertion"
    );
    assert_eq!(
        assertions[0].assertion_ref, validity.assertion_ref,
        "conformance[t2]: assertion_ref must match"
    );

    // Read back ledger entries
    let entries = store
        .load_ledger(&agent, None, 100)
        .expect("conformance[t2]: load_ledger must not error");
    assert_eq!(entries.len(), 1, "conformance[t2]: must have 1 ledger entry");
    assert_eq!(
        entries[0].entry_id, ledger.entry_id,
        "conformance[t2]: entry_id must match"
    );

    // Read back edges
    let edges = store
        .load_edges_for(&agent, &claim_ref)
        .expect("conformance[t2]: load_edges_for must not error");
    assert_eq!(edges.len(), 1, "conformance[t2]: must have 1 edge");
    assert_eq!(edges[0].edge_id, edge.edge_id, "conformance[t2]: edge_id must match");
}

/// rollback leaves ZERO rows across all 4 tables (atomicity guarantee).
#[cfg(any(test, feature = "test-support"))]
fn test_rollback_leaves_zero_rows<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t3".into());
    let claim = make_claim(&agent, "subject-rb", "predicate-rb");
    let claim_ref = claim.claim_ref().clone();
    let validity = make_validity_assertion(&agent, &claim_ref);
    let ledger = make_ledger_entry(&agent, &claim_ref);

    let mut txn = store
        .begin_atomic(&agent)
        .expect("conformance[t3]: begin_atomic must succeed");
    store
        .append_claim(&mut txn, &claim)
        .expect("conformance[t3]: append_claim must succeed");
    store
        .append_validity_assertion(&mut txn, &validity)
        .expect("conformance[t3]: append_validity_assertion must succeed");
    store
        .append_ledger_entry(&mut txn, &ledger)
        .expect("conformance[t3]: append_ledger_entry must succeed");

    store.rollback(txn).expect("conformance[t3]: rollback must succeed");

    // All reads must return empty after rollback
    let loaded_claim = store
        .load_claim(&agent, &claim_ref)
        .expect("conformance[t3]: load_claim must not error after rollback");
    assert!(
        loaded_claim.is_none(),
        "conformance[t3]: claim must be absent after rollback"
    );

    let assertions = store
        .load_validity_assertions_for(&agent, &claim_ref)
        .expect("conformance[t3]: load_validity_assertions_for must not error");
    assert!(
        assertions.is_empty(),
        "conformance[t3]: validity assertions must be absent after rollback"
    );

    let ledger_entries = store
        .load_ledger(&agent, None, 100)
        .expect("conformance[t3]: load_ledger must not error");
    assert!(
        ledger_entries.is_empty(),
        "conformance[t3]: ledger entries must be absent after rollback"
    );

    let edges = store
        .load_edges_for(&agent, &claim_ref)
        .expect("conformance[t3]: load_edges_for must not error");
    assert!(
        edges.is_empty(),
        "conformance[t3]: edges must be absent after rollback"
    );
}

/// load_subject_line ORDER BY tx_time ASC (≥2 claims).
#[cfg(any(test, feature = "test-support"))]
fn test_load_subject_line_ordering<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t4".into());

    // Create two claims with distinct tx_times (use slightly different times via sleep-free approach:
    // we can't sleep, but we can use slightly different timestamps by constructing them explicitly)
    let t1 = chrono::DateTime::<chrono::Utc>::from_timestamp(1_000_000, 0).unwrap();
    let t2 = chrono::DateTime::<chrono::Utc>::from_timestamp(1_000_001, 0).unwrap();

    let claim1 = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        Fact { subject: "user".into(), predicate: "job".into(), value: serde_json::json!("engineer") },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(t1),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );
    let claim2 = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        Fact { subject: "user".into(), predicate: "job".into(), value: serde_json::json!("architect") },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(t2),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );

    let ref1 = claim1.claim_ref().clone();
    let ref2 = claim2.claim_ref().clone();

    let mut txn = store
        .begin_atomic(&agent)
        .expect("conformance[t4]: begin_atomic must succeed");
    store.append_claim(&mut txn, &claim1).expect("conformance[t4]: append claim1");
    store.append_claim(&mut txn, &claim2).expect("conformance[t4]: append claim2");
    store.commit(txn).expect("conformance[t4]: commit");

    let line = store
        .load_subject_line(&agent, "user", "job")
        .expect("conformance[t4]: load_subject_line must not error");

    assert_eq!(line.len(), 2, "conformance[t4]: must have 2 claims on subject line");
    assert_eq!(
        line[0].claim_ref(),
        &ref1,
        "conformance[t4]: first claim must have earliest tx_time (ASC order)"
    );
    assert_eq!(
        line[1].claim_ref(),
        &ref2,
        "conformance[t4]: second claim must have latest tx_time"
    );
}

/// load_lineage multi-hop (A→B→C DerivedFrom/DependsOn chain) returns the chain.
#[cfg(any(test, feature = "test-support"))]
fn test_load_lineage_multi_hop<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t5".into());

    let claim_a = make_claim(&agent, "topic", "summary");
    let claim_b = make_claim(&agent, "topic", "detail");
    let claim_c = make_claim(&agent, "topic", "inference");

    let ref_a = claim_a.claim_ref().clone();
    let ref_b = claim_b.claim_ref().clone();
    let ref_c = claim_c.claim_ref().clone();

    // Chain: A --DerivedFrom--> B --DerivedFrom--> C
    let t_base = chrono::DateTime::<chrono::Utc>::from_timestamp(2_000_000, 0).unwrap();
    let edge_ab = ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        from_claim: ref_a.clone(),
        to_claim: ref_b.clone(),
        kind: EdgeKind::DerivedFrom,
        created_at: TransactionTime(t_base),
    };
    let edge_bc = ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        from_claim: ref_b.clone(),
        to_claim: ref_c.clone(),
        kind: EdgeKind::DerivedFrom,
        created_at: TransactionTime(t_base + chrono::Duration::seconds(1)),
    };

    let mut txn = store.begin_atomic(&agent).expect("conformance[t5]: begin_atomic");
    store.append_claim(&mut txn, &claim_a).expect("conformance[t5]: append A");
    store.append_claim(&mut txn, &claim_b).expect("conformance[t5]: append B");
    store.append_claim(&mut txn, &claim_c).expect("conformance[t5]: append C");
    store.append_claim_edge(&mut txn, &edge_ab).expect("conformance[t5]: append edge A→B");
    store.append_claim_edge(&mut txn, &edge_bc).expect("conformance[t5]: append edge B→C");
    store.commit(txn).expect("conformance[t5]: commit");

    // load_lineage starting from A should return [A→B, B→C] ordered by depth ASC
    let lineage = store
        .load_lineage(&agent, &ref_a)
        .expect("conformance[t5]: load_lineage must not error");

    assert_eq!(
        lineage.len(),
        2,
        "conformance[t5]: lineage from A must have 2 edges (A→B at depth 1, B→C at depth 2)"
    );
    assert_eq!(
        lineage[0].from_claim, ref_a,
        "conformance[t5]: first edge must start from A (depth 1)"
    );
    assert_eq!(
        lineage[0].to_claim, ref_b,
        "conformance[t5]: first edge must point to B"
    );
    assert_eq!(
        lineage[1].from_claim, ref_b,
        "conformance[t5]: second edge must start from B (depth 2)"
    );
    assert_eq!(
        lineage[1].to_claim, ref_c,
        "conformance[t5]: second edge must point to C"
    );
}

/// load_edges_for ORDER BY created_at ASC.
#[cfg(any(test, feature = "test-support"))]
fn test_load_edges_for_ordering<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t6".into());

    let claim_hub = make_claim(&agent, "hub", "central");
    let claim_x = make_claim(&agent, "spoke", "x");
    let claim_y = make_claim(&agent, "spoke", "y");

    let hub_ref = claim_hub.claim_ref().clone();
    let x_ref = claim_x.claim_ref().clone();
    let y_ref = claim_y.claim_ref().clone();

    let t1 = chrono::DateTime::<chrono::Utc>::from_timestamp(3_000_000, 0).unwrap();
    let t2 = chrono::DateTime::<chrono::Utc>::from_timestamp(3_000_001, 0).unwrap();

    // edge1: hub→x (created earlier)
    let edge1 = ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        from_claim: hub_ref.clone(),
        to_claim: x_ref.clone(),
        kind: EdgeKind::DependsOn,
        created_at: TransactionTime(t1),
    };
    // edge2: hub→y (created later)
    let edge2 = ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        from_claim: hub_ref.clone(),
        to_claim: y_ref.clone(),
        kind: EdgeKind::DependsOn,
        created_at: TransactionTime(t2),
    };

    let mut txn = store.begin_atomic(&agent).expect("conformance[t6]: begin_atomic");
    store.append_claim(&mut txn, &claim_hub).expect("conformance[t6]: append hub");
    store.append_claim(&mut txn, &claim_x).expect("conformance[t6]: append x");
    store.append_claim(&mut txn, &claim_y).expect("conformance[t6]: append y");
    store.append_claim_edge(&mut txn, &edge1).expect("conformance[t6]: append edge1");
    store.append_claim_edge(&mut txn, &edge2).expect("conformance[t6]: append edge2");
    store.commit(txn).expect("conformance[t6]: commit");

    let edges = store
        .load_edges_for(&agent, &hub_ref)
        .expect("conformance[t6]: load_edges_for must not error");

    assert_eq!(edges.len(), 2, "conformance[t6]: hub must have 2 edges");
    assert_eq!(
        edges[0].to_claim, x_ref,
        "conformance[t6]: first edge (ASC created_at) must point to x"
    );
    assert_eq!(
        edges[1].to_claim, y_ref,
        "conformance[t6]: second edge must point to y"
    );
}

/// edge uniqueness: duplicate (agent_id, from, to, kind) → Err.
#[cfg(any(test, feature = "test-support"))]
fn test_edge_uniqueness_constraint<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t7".into());

    let claim_a = make_claim(&agent, "dup-from", "p");
    let claim_b = make_claim(&agent, "dup-to", "p");

    let ref_a = claim_a.claim_ref().clone();
    let ref_b = claim_b.claim_ref().clone();

    // Insert both claims and the first edge
    let edge1 = ClaimEdge {
        edge_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        from_claim: ref_a.clone(),
        to_claim: ref_b.clone(),
        kind: EdgeKind::DependsOn,
        created_at: TransactionTime(Utc::now()),
    };

    let mut txn = store.begin_atomic(&agent).expect("conformance[t7]: begin_atomic");
    store.append_claim(&mut txn, &claim_a).expect("conformance[t7]: append A");
    store.append_claim(&mut txn, &claim_b).expect("conformance[t7]: append B");
    store.append_claim_edge(&mut txn, &edge1).expect("conformance[t7]: append first edge");
    store.commit(txn).expect("conformance[t7]: first commit");

    // Now attempt to insert a duplicate edge in a new transaction
    let edge_dup = ClaimEdge {
        edge_id: Uuid::new_v4(), // different edge_id, same (agent, from, to, kind)
        agent_id: agent.clone(),
        from_claim: ref_a.clone(),
        to_claim: ref_b.clone(),
        kind: EdgeKind::DependsOn,
        created_at: TransactionTime(Utc::now()),
    };

    let mut txn2 = store.begin_atomic(&agent).expect("conformance[t7]: begin_atomic txn2");
    let result = store.append_claim_edge(&mut txn2, &edge_dup);
    // Must error due to UNIQUE(agent_id, from_claim_id, to_claim_id, edge_kind)
    // Roll back regardless
    let _ = store.rollback(txn2);

    assert!(
        result.is_err(),
        "conformance[t7]: duplicate edge insert must return Err (UNIQUE constraint)"
    );
}

/// load_validity_assertions_for ORDER BY asserted_at ASC.
#[cfg(any(test, feature = "test-support"))]
fn test_load_validity_assertions_ordering<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t8".into());
    let claim = make_claim(&agent, "food", "allergy");
    let claim_ref = claim.claim_ref().clone();

    let t1 = chrono::DateTime::<chrono::Utc>::from_timestamp(4_000_000, 0).unwrap();
    let t2 = chrono::DateTime::<chrono::Utc>::from_timestamp(4_000_001, 0).unwrap();

    let va1 = ValidityAssertion {
        assertion_ref: Uuid::new_v4(),
        agent_id: agent.clone(),
        target_claim: claim_ref.clone(),
        kind: AssertionKind::Bound { bound_at: t1 },
        provenance: ProvenanceLabel::External(ExternalKind::UserAsserted),
        confidence: Confidence { value_confidence: 0.9, valid_time_confidence: 0.9 },
        asserted_at: TransactionTime(t1),
    };
    let va2 = ValidityAssertion {
        assertion_ref: Uuid::new_v4(),
        agent_id: agent.clone(),
        target_claim: claim_ref.clone(),
        kind: AssertionKind::Reopen { reopen_at: t2 },
        provenance: ProvenanceLabel::External(ExternalKind::UserAsserted),
        confidence: Confidence { value_confidence: 0.8, valid_time_confidence: 0.8 },
        asserted_at: TransactionTime(t2),
    };

    let ref1 = va1.assertion_ref;
    let ref2 = va2.assertion_ref;

    let mut txn = store.begin_atomic(&agent).expect("conformance[t8]: begin_atomic");
    store.append_claim(&mut txn, &claim).expect("conformance[t8]: append claim");
    // Insert in reverse order to prove ORDER BY overrides insertion order
    store.append_validity_assertion(&mut txn, &va2).expect("conformance[t8]: append va2 first");
    store.append_validity_assertion(&mut txn, &va1).expect("conformance[t8]: append va1 second");
    store.commit(txn).expect("conformance[t8]: commit");

    let assertions = store
        .load_validity_assertions_for(&agent, &claim_ref)
        .expect("conformance[t8]: load_validity_assertions_for must not error");

    assert_eq!(assertions.len(), 2, "conformance[t8]: must have 2 assertions");
    assert_eq!(
        assertions[0].assertion_ref, ref1,
        "conformance[t8]: first assertion must be the earliest asserted_at (ASC)"
    );
    assert_eq!(
        assertions[1].assertion_ref, ref2,
        "conformance[t8]: second assertion must be the later asserted_at"
    );
}

/// load_ledger with a `from` bound returns only entries >= bound.
#[cfg(any(test, feature = "test-support"))]
fn test_load_ledger_with_from<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t9".into());

    let t_early = chrono::DateTime::<chrono::Utc>::from_timestamp(5_000_000, 0).unwrap();
    let t_late = chrono::DateTime::<chrono::Utc>::from_timestamp(5_000_002, 0).unwrap();

    let claim_early = make_claim(&agent, "ledger-sub", "early");
    let ref_early = claim_early.claim_ref().clone();
    let claim_late = make_claim(&agent, "ledger-sub", "late");
    let ref_late = claim_late.claim_ref().clone();

    let entry_early = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref_early.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(t_early),
    };
    let entry_late = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref_late.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(t_late),
    };

    let late_id = entry_late.entry_id;

    let mut txn = store.begin_atomic(&agent).expect("conformance[t9]: begin_atomic");
    store.append_claim(&mut txn, &claim_early).expect("conformance[t9]: append claim_early");
    store.append_claim(&mut txn, &claim_late).expect("conformance[t9]: append claim_late");
    store.append_ledger_entry(&mut txn, &entry_early).expect("conformance[t9]: append early entry");
    store.append_ledger_entry(&mut txn, &entry_late).expect("conformance[t9]: append late entry");
    store.commit(txn).expect("conformance[t9]: commit");

    // Query with from = t_late; should return only the late entry
    let from_time = TransactionTime(t_late);
    let entries = store
        .load_ledger(&agent, Some(&from_time), 100)
        .expect("conformance[t9]: load_ledger with from must not error");

    assert_eq!(
        entries.len(),
        1,
        "conformance[t9]: load_ledger with from=t_late must return 1 entry (not the earlier one)"
    );
    assert_eq!(
        entries[0].entry_id, late_id,
        "conformance[t9]: the returned entry must be the late one"
    );
}

/// load_injected_claims returns ServedAsInjected-origin claims.
#[cfg(any(test, feature = "test-support"))]
fn test_load_injected_claims<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t10".into());

    let claim1 = make_claim(&agent, "injected-sub", "p1");
    let ref1 = claim1.claim_ref().clone();
    let claim2 = make_claim(&agent, "injected-sub", "p2");
    let ref2 = claim2.claim_ref().clone();

    // claim1 gets a ServedAsInjected entry; claim2 gets ClaimCommitted (not injected)
    let entry_injected = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref1.clone(),
        event_kind: LedgerEventKind::ServedAsInjected,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(Utc::now()),
    };
    let entry_committed = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref2.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(Utc::now()),
    };

    let mut txn = store.begin_atomic(&agent).expect("conformance[t10]: begin_atomic");
    store.append_claim(&mut txn, &claim1).expect("conformance[t10]: append claim1");
    store.append_claim(&mut txn, &claim2).expect("conformance[t10]: append claim2");
    store.append_ledger_entry(&mut txn, &entry_injected).expect("conformance[t10]: append injected entry");
    store.append_ledger_entry(&mut txn, &entry_committed).expect("conformance[t10]: append committed entry");
    store.commit(txn).expect("conformance[t10]: commit");

    let injected = store
        .load_injected_claims(&agent)
        .expect("conformance[t10]: load_injected_claims must not error");

    assert_eq!(
        injected.len(),
        1,
        "conformance[t10]: must return exactly 1 injected claim (ServedAsInjected only)"
    );
    assert_eq!(
        injected[0], ref1,
        "conformance[t10]: injected claim ref must be ref1"
    );
}

/// load_claim missing → None.
#[cfg(any(test, feature = "test-support"))]
fn test_load_claim_missing<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t11".into());
    let nonexistent_ref = ClaimRef::new_random();

    let result = store
        .load_claim(&agent, &nonexistent_ref)
        .expect("conformance[t11]: load_claim for missing ref must not error");

    assert!(
        result.is_none(),
        "conformance[t11]: load_claim for nonexistent ClaimRef must return None"
    );
}

/// load_edges_for with no edges → empty vec.
#[cfg(any(test, feature = "test-support"))]
fn test_load_edges_for_empty<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-t12".into());
    let claim = make_claim(&agent, "isolated-sub", "p");
    let claim_ref = claim.claim_ref().clone();

    let mut txn = store.begin_atomic(&agent).expect("conformance[t12]: begin_atomic");
    store.append_claim(&mut txn, &claim).expect("conformance[t12]: append claim");
    store.commit(txn).expect("conformance[t12]: commit");

    let edges = store
        .load_edges_for(&agent, &claim_ref)
        .expect("conformance[t12]: load_edges_for must not error");

    assert!(
        edges.is_empty(),
        "conformance[t12]: load_edges_for must return empty vec when no edges exist"
    );
}

// ── History conformance harness ───────────────────────────────────────────────

/// Run the history timeline conformance suite against `store`.
///
/// Exercises `compute_effective_windows` (pure) and `truth_engine::fold` via the real
/// persistence backend. Uses DISTINCT agent_id namespace (`conformance-hist-*`).
///
/// Panics on any contract violation with a descriptive message.
#[cfg(any(test, feature = "test-support"))]
pub fn run_history_conformance<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    hist_empty_line(store);
    hist_single_claim(store);
    hist_succession_ordering(store);
    hist_current_agrees_with_fold(store);
}

/// Empty subject-line → `load_subject_line` returns empty (foundation for history).
#[cfg(any(test, feature = "test-support"))]
fn hist_empty_line<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-hist-t1".into());
    let claims = store
        .load_subject_line(&agent, "hist-nobody", "hist-nothing")
        .expect("conformance[hist-t1]: load_subject_line must not error");
    assert!(
        claims.is_empty(),
        "conformance[hist-t1]: unknown subject-line must return empty vec"
    );
}

/// Single committed claim → 1 entry, ordering key is tx_time (low confidence).
#[cfg(any(test, feature = "test-support"))]
fn hist_single_claim<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    use crate::application::query_history::compute_effective_windows;
    use crate::config::EngineConfig;

    let agent = AgentId("conformance-hist-t2".into());
    let tx = chrono::DateTime::<chrono::Utc>::from_timestamp(10_000_000, 0).unwrap();
    let claim = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        Fact { subject: "hist-acme".to_owned(), predicate: "ceo".to_owned(), value: serde_json::json!("Alice") },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(tx),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );

    let mut txn = store.begin_atomic(&agent).expect("conformance[hist-t2]: begin_atomic");
    store.append_claim(&mut txn, &claim).expect("conformance[hist-t2]: append_claim");
    store.commit(txn).expect("conformance[hist-t2]: commit");

    let claims = store
        .load_subject_line(&agent, "hist-acme", "ceo")
        .expect("conformance[hist-t2]: load_subject_line must not error");
    assert_eq!(claims.len(), 1, "conformance[hist-t2]: must have 1 claim");

    let config = EngineConfig::default();
    let refs: Vec<&Claim> = claims.iter().collect();
    let windows = compute_effective_windows(&refs, &config);
    assert_eq!(windows.len(), 1, "conformance[hist-t2]: 1 window");
    assert_eq!(windows[0], None, "conformance[hist-t2]: single claim has open-ended window");
}

/// CEO succession: Alice→John→Bob — 3 entries ordered oldest first, windows correct.
/// This is the canonical CEO-timeline scenario from the DESIGN.md.
#[cfg(any(test, feature = "test-support"))]
fn hist_succession_ordering<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    use crate::application::query_history::compute_effective_windows;
    use crate::config::EngineConfig;

    let agent = AgentId("conformance-hist-t3".into());

    let t_alice = chrono::DateTime::<chrono::Utc>::from_timestamp(11_000_000, 0).unwrap();
    let t_john  = chrono::DateTime::<chrono::Utc>::from_timestamp(11_000_001, 0).unwrap();
    let t_bob   = chrono::DateTime::<chrono::Utc>::from_timestamp(11_000_002, 0).unwrap();

    let make_c = |val: &str, tx: chrono::DateTime<chrono::Utc>| -> Claim {
        Claim::new(
            ClaimRef::new_random(),
            agent.clone(),
            Fact { subject: "hist-corp".to_owned(), predicate: "ceo".to_owned(), value: serde_json::json!(val) },
            Cardinality::Functional,
            ProvenanceLabel::External(ExternalKind::UserAsserted),
            ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
            TransactionTime(tx),
            ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
            Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
            Criticality::Low,
            vec![],
            None,
            None,
        )
    };

    let c_alice = make_c("Alice", t_alice);
    let c_john  = make_c("John",  t_john);
    let c_bob   = make_c("Bob",   t_bob);

    let mut txn = store.begin_atomic(&agent).expect("conformance[hist-t3]: begin_atomic");
    store.append_claim(&mut txn, &c_alice).expect("conformance[hist-t3]: append Alice");
    store.append_claim(&mut txn, &c_john).expect("conformance[hist-t3]: append John");
    store.append_claim(&mut txn, &c_bob).expect("conformance[hist-t3]: append Bob");
    store.commit(txn).expect("conformance[hist-t3]: commit");

    let mut claims = store
        .load_subject_line(&agent, "hist-corp", "ceo")
        .expect("conformance[hist-t3]: load_subject_line must not error");
    assert_eq!(claims.len(), 3, "conformance[hist-t3]: must have 3 claims (Alice, John, Bob)");

    let config = EngineConfig::default();
    // Sort by canonical ordering key (tx_time — all low confidence).
    claims.sort_by(|a, b| {
        a.transaction_time().0.cmp(&b.transaction_time().0)
            .then(a.claim_ref().0.as_u128().cmp(&b.claim_ref().0.as_u128()))
    });

    let refs: Vec<&Claim> = claims.iter().collect();
    let windows = compute_effective_windows(&refs, &config);

    // Windows: Alice closed by John's tx, John closed by Bob's tx, Bob open.
    assert_eq!(windows[0], Some(t_john), "conformance[hist-t3]: Alice's valid_until = John's ordering key");
    assert_eq!(windows[1], Some(t_bob),  "conformance[hist-t3]: John's valid_until = Bob's ordering key");
    assert_eq!(windows[2], None,          "conformance[hist-t3]: Bob is open-ended (current)");

    // Values in canonical order (oldest first).
    assert_eq!(claims[0].fact().value, serde_json::json!("Alice"), "conformance[hist-t3]: oldest is Alice");
    assert_eq!(claims[1].fact().value, serde_json::json!("John"),  "conformance[hist-t3]: middle is John");
    assert_eq!(claims[2].fact().value, serde_json::json!("Bob"),   "conformance[hist-t3]: newest is Bob");
}

/// Current entry agrees with `truth_engine::fold` on which claim is live.
#[cfg(any(test, feature = "test-support"))]
fn hist_current_agrees_with_fold<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    use crate::config::EngineConfig;
    use crate::engine::truth_engine;
    use std::collections::HashMap;
    use mempill_types::disposition::Disposition;

    let agent = AgentId("conformance-hist-t4".into());

    let t1 = chrono::DateTime::<chrono::Utc>::from_timestamp(12_000_000, 0).unwrap();
    let t2 = chrono::DateTime::<chrono::Utc>::from_timestamp(12_000_001, 0).unwrap();

    let c = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        Fact { subject: "hist-org".to_owned(), predicate: "lead".to_owned(), value: serde_json::json!("Leader-A") },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(t1),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );

    let mut txn = store.begin_atomic(&agent).expect("conformance[hist-t4]: begin_atomic");
    store.append_claim(&mut txn, &c).expect("conformance[hist-t4]: append");
    store.commit(txn).expect("conformance[hist-t4]: commit");

    let claims = store
        .load_subject_line(&agent, "hist-org", "lead")
        .expect("conformance[hist-t4]: load_subject_line");
    assert_eq!(claims.len(), 1, "conformance[hist-t4]: one claim loaded");

    let config = EngineConfig::default();
    let latest_disposition: HashMap<_, Disposition> = HashMap::new();
    let now = t2;

    let fold = truth_engine::fold(
        claims.clone(),
        |_| vec![],
        now,
        &config,
        &latest_disposition,
    );

    assert_eq!(fold.live_claims.len(), 1, "conformance[hist-t4]: one live claim in fold");
    assert_eq!(
        fold.live_claims[0].claim.fact().value,
        serde_json::json!("Leader-A"),
        "conformance[hist-t4]: fold's live claim must match the single committed claim"
    );
}

// ── Disposition-scope conformance tests ───────────────────────────────────────

/// `load_ledger_for_claims` returns exactly the entries for the given claim refs.
///
/// Writes two claims each with a ledger entry, queries for only one, asserts only
/// one entry is returned — proving the method is correctly scoped to `claim_refs`.
#[cfg(any(test, feature = "test-support"))]
fn test_load_ledger_for_claims_scoped<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{
    let agent = AgentId("conformance-lfc-t1".into());

    let claim_a = make_claim(&agent, "scope-subj", "scope-pred");
    let claim_b = make_claim(&agent, "scope-subj", "scope-pred-b");
    let ref_a = claim_a.claim_ref().clone();
    let ref_b = claim_b.claim_ref().clone();

    let ledger_a = make_ledger_entry(&agent, &ref_a);
    let ledger_b = make_ledger_entry(&agent, &ref_b);

    let mut txn = store.begin_atomic(&agent).expect("conformance[lfc-t1]: begin_atomic");
    store.append_claim(&mut txn, &claim_a).expect("conformance[lfc-t1]: append_claim_a");
    store.append_claim(&mut txn, &claim_b).expect("conformance[lfc-t1]: append_claim_b");
    store.append_ledger_entry(&mut txn, &ledger_a).expect("conformance[lfc-t1]: append_ledger_a");
    store.append_ledger_entry(&mut txn, &ledger_b).expect("conformance[lfc-t1]: append_ledger_b");
    store.commit(txn).expect("conformance[lfc-t1]: commit");

    // Query for only claim_a — must not return claim_b's entry.
    let result = store
        .load_ledger_for_claims(&agent, &[ref_a.clone()])
        .expect("conformance[lfc-t1]: load_ledger_for_claims must not error");

    assert_eq!(result.len(), 1, "conformance[lfc-t1]: exactly one entry for claim_a");
    assert_eq!(result[0].claim_ref, ref_a, "conformance[lfc-t1]: entry must be for claim_a");

    // Empty input → empty result (no IN () SQL emitted).
    let empty = store
        .load_ledger_for_claims(&agent, &[])
        .expect("conformance[lfc-t1]: empty input must not error");
    assert!(empty.is_empty(), "conformance[lfc-t1]: empty input must return empty vec");
}

/// Superseded claim is correctly excluded despite a large agent ledger.
///
/// Scenario: one agent accumulates many ledger entries across many subject-lines
/// (simulating a high-volume agent). On ONE subject-line, claim A is committed then
/// superseded by claim B (B's tx_time > A's). After supersession, `query_memory`
/// must return B as the live belief — not A (resurrected), not Contested.
///
/// Under the old agent-wide cap (10_000), if the supersession entry for A fell
/// outside the cap window it was missing from the disposition map and A defaulted
/// to live — this test would have returned Contested or "A" instead of "B".
#[cfg(any(test, feature = "test-support"))]
fn test_superseded_claim_excluded_despite_large_agent_ledger<P>(store: &P)
where
    P: PersistencePort,
    P::Error: std::fmt::Debug,
{

    let agent = AgentId("conformance-dscope-t1".into());

    // ── 1. Flood the agent ledger with entries on OTHER subject-lines ──────────
    // Use 50 noise claims with 2 ledger entries each = 100 total noise entries.
    // This is a focused correctness proof that would fail under a cap of e.g. 20.
    // (We don't literally write 10k rows; the unit test for load_ledger_for_claims
    //  above proves the scoping is correct; this test proves end-to-end correctness.)
    for i in 0..50u32 {
        let noise_claim = Claim::new(
            ClaimRef::new_random(),
            agent.clone(),
            mempill_types::claim::Fact {
                subject: format!("noise-subject-{i}"),
                predicate: "noise-predicate".to_owned(),
                value: serde_json::json!(i),
            },
            Cardinality::Functional,
            ProvenanceLabel::External(ExternalKind::UserAsserted),
            ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
            TransactionTime(Utc::now()),
            ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
            Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
            Criticality::Low,
            vec![],
            None,
            None,
        );
        let noise_ref = noise_claim.claim_ref().clone();
        let noise_ledger1 = make_ledger_entry(&agent, &noise_ref);
        let noise_ledger2 = LedgerEntry {
            entry_id: Uuid::new_v4(),
            agent_id: agent.clone(),
            claim_ref: noise_ref.clone(),
            event_kind: LedgerEventKind::ValidityAsserted,
            disposition: Disposition::CommittedCheap,
            rationale: None,
            recorded_at: TransactionTime(Utc::now()),
        };
        let mut txn = store.begin_atomic(&agent).expect("dscope[t1]: noise begin_atomic");
        store.append_claim(&mut txn, &noise_claim).expect("dscope[t1]: noise append_claim");
        store.append_ledger_entry(&mut txn, &noise_ledger1).expect("dscope[t1]: noise ledger1");
        store.append_ledger_entry(&mut txn, &noise_ledger2).expect("dscope[t1]: noise ledger2");
        store.commit(txn).expect("dscope[t1]: noise commit");
    }

    // ── 2. Ingest claim A on the test subject-line ────────────────────────────
    let t_a = chrono::DateTime::<Utc>::from_timestamp(1_000_000, 0).unwrap();
    let claim_a = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        mempill_types::claim::Fact {
            subject: "dscope-org".to_owned(),
            predicate: "ceo".to_owned(),
            value: serde_json::json!("Alice"),
        },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(t_a),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );
    let ref_a = claim_a.claim_ref().clone();

    // A is initially committed.
    let ledger_a_committed = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref_a.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(t_a),
    };

    let mut txn = store.begin_atomic(&agent).expect("dscope[t1]: claim_a begin");
    store.append_claim(&mut txn, &claim_a).expect("dscope[t1]: claim_a append");
    store.append_ledger_entry(&mut txn, &ledger_a_committed).expect("dscope[t1]: claim_a ledger");
    store.commit(txn).expect("dscope[t1]: claim_a commit");

    // ── 3. Ingest claim B (supersedes A) ─────────────────────────────────────
    let t_b = chrono::DateTime::<Utc>::from_timestamp(2_000_000, 0).unwrap();
    let claim_b = Claim::new(
        ClaimRef::new_random(),
        agent.clone(),
        mempill_types::claim::Fact {
            subject: "dscope-org".to_owned(),
            predicate: "ceo".to_owned(),
            value: serde_json::json!("Bob"),
        },
        Cardinality::Functional,
        ProvenanceLabel::External(ExternalKind::UserAsserted),
        ExternalAnchor { nearest_external_anchor: None, derivation_depth: 0 },
        TransactionTime(t_b),
        ValidTime { start: None, end: None, valid_time_confidence: 0.0 },
        Confidence { value_confidence: 0.9, valid_time_confidence: 0.0 },
        Criticality::Low,
        vec![],
        None,
        None,
    );
    let ref_b = claim_b.claim_ref().clone();

    // A is superseded; B is committed.
    let ledger_a_superseded = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref_a.clone(),
        event_kind: LedgerEventKind::ValidityAsserted,
        disposition: Disposition::Superseded,
        rationale: None,
        recorded_at: TransactionTime(t_b),
    };
    let ledger_b_committed = LedgerEntry {
        entry_id: Uuid::new_v4(),
        agent_id: agent.clone(),
        claim_ref: ref_b.clone(),
        event_kind: LedgerEventKind::ClaimCommitted,
        disposition: Disposition::CommittedCheap,
        rationale: None,
        recorded_at: TransactionTime(t_b),
    };

    let mut txn = store.begin_atomic(&agent).expect("dscope[t1]: claim_b begin");
    store.append_claim(&mut txn, &claim_b).expect("dscope[t1]: claim_b append");
    store.append_ledger_entry(&mut txn, &ledger_a_superseded).expect("dscope[t1]: ledger_a_superseded");
    store.append_ledger_entry(&mut txn, &ledger_b_committed).expect("dscope[t1]: ledger_b_committed");
    store.commit(txn).expect("dscope[t1]: claim_b commit");

    // ── 4. Verify load_ledger_for_claims returns both entries for both refs ───
    let scoped = store
        .load_ledger_for_claims(&agent, &[ref_a.clone(), ref_b.clone()])
        .expect("dscope[t1]: load_ledger_for_claims must not error");
    // Expect: ledger_a_committed + ledger_a_superseded + ledger_b_committed = 3 entries.
    assert_eq!(
        scoped.len(), 3,
        "dscope[t1]: load_ledger_for_claims must return all 3 entries for the 2 subject-line claims"
    );

    // ── 5. End-to-end: truth_engine fold must return only Bob (B) as live ───────
    // Mirrors exactly what query_memory does after load_ledger_for_claims.
    use crate::application::ingest_claim::build_latest_disposition_map;
    use crate::config::EngineConfig;
    use crate::engine::truth_engine;

    let subject_claims = store
        .load_subject_line(&agent, "dscope-org", "ceo")
        .expect("dscope[t1]: load_subject_line must not error");
    assert_eq!(subject_claims.len(), 2, "dscope[t1]: must have 2 claims on subject-line");

    let subject_refs: Vec<ClaimRef> = subject_claims.iter().map(|c| c.claim_ref().clone()).collect();
    let scoped_ledger = store
        .load_ledger_for_claims(&agent, &subject_refs)
        .expect("dscope[t1]: load_ledger_for_claims must not error after B committed");
    let latest_disposition = build_latest_disposition_map(&scoped_ledger);

    let now = chrono::DateTime::<Utc>::from_timestamp(3_000_000, 0).unwrap();
    let config = EngineConfig::default();
    let fold = truth_engine::fold(
        subject_claims,
        |_cref| vec![],
        now,
        &config,
        &latest_disposition,
    );

    // With correct disposition map: A is Superseded → not live; B is CommittedCheap → live.
    // fold.live_claims must be exactly [B].
    assert_eq!(
        fold.live_claims.len(), 1,
        "dscope[t1]: exactly one live claim (Bob/B); got {:?}",
        fold.live_claims.iter().map(|cs| &cs.claim.fact().value).collect::<Vec<_>>()
    );
    assert_eq!(
        fold.live_claims[0].claim.fact().value,
        serde_json::json!("Bob"),
        "dscope[t1]: the live claim must be Bob (B), not Alice (A — superseded)"
    );
}