mati 0.1.2

An enforcement layer for codebase knowledge: confirmed gotchas gate what AI agents read and edit at the hook level. Not a passive memory store.
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
//! Enforcement event recording integration tests.
//!
//! These are acceptance criteria for the enforcement event foundation.
//! Every test must pass before the feature is considered complete.

use std::path::PathBuf;

use tempfile::TempDir;

use mati_core::store::db::Store;
use mati_core::store::enforcement::{
    canonicalize_file_key, scan_enforcement_events, EnforcementEventType, EnforcementEventWriter,
    EnforcementMode, GapCause, GapCertainty, MissedEventCount, SeqAllocator, SubjectKind,
    SCHEMA_VERSION,
};

async fn temp_store() -> (TempDir, Store) {
    let dir = TempDir::new().expect("tempdir");
    let store = Store::open(dir.path()).await.expect("open store");
    (dir, store)
}

// ─────────────────────────────────────────────
// Test 1: Concurrent writes produce unique seq_nos
// ─────────────────────────────────────────────

#[tokio::test]
async fn concurrent_writes_produce_unique_seq_nos() {
    let (_dir, store) = temp_store().await;
    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    let mut seq_nos = Vec::with_capacity(100);
    for _ in 0..100 {
        let event = writer
            .write(
                &store,
                EnforcementEventType::Deny,
                SubjectKind::File,
                "file:src/test.rs".to_string(),
                "claude".to_string(),
                None,
                "gotcha_above_threshold".to_string(),
                None,
            )
            .await
            .expect("write event");
        seq_nos.push(event.seq_no);
    }

    // No duplicates
    let mut deduped = seq_nos.clone();
    deduped.sort();
    deduped.dedup();
    assert_eq!(
        deduped.len(),
        100,
        "all 100 seq_nos must be unique, got {} unique",
        deduped.len()
    );

    // Ascending order
    for window in seq_nos.windows(2) {
        assert!(
            window[0] < window[1],
            "seq_nos must be strictly ascending: {} >= {}",
            window[0],
            window[1]
        );
    }
}

// ─────────────────────────────────────────────
// Test 2: Crash between seq allocation and commit
// ─────────────────────────────────────────────

#[tokio::test]
async fn seq_gap_after_simulated_crash() {
    let (_dir, store) = temp_store().await;
    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // Write event 1 (seq 1) — succeeds
    let event1 = writer
        .write(
            &store,
            EnforcementEventType::Deny,
            SubjectKind::File,
            "file:src/a.rs".to_string(),
            "claude".to_string(),
            None,
            "gotcha_above_threshold".to_string(),
            None,
        )
        .await
        .expect("write event 1");
    assert_eq!(event1.seq_no, 1);

    // Simulate crash: manually advance the seq counter to 5
    // (simulating seq 2-5 were allocated but events never written)
    store
        .put_raw("enforcement:seq", &5u64.to_be_bytes())
        .await
        .expect("advance seq");

    // Create a NEW writer (simulates restart after crash)
    let mut writer2 = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer after crash");

    // Writer should have loaded seq=5 as current
    assert_eq!(writer2.current_seq(), 5);

    // Next event should get seq 6 (5+1)
    let event2 = writer2
        .write(
            &store,
            EnforcementEventType::Deny,
            SubjectKind::File,
            "file:src/b.rs".to_string(),
            "claude".to_string(),
            None,
            "gotcha_above_threshold".to_string(),
            None,
        )
        .await
        .expect("write event after crash");
    assert_eq!(event2.seq_no, 6);

    // The gap (seq 2-5) exists: no events stored for those seqs
    let all_events = scan_enforcement_events(&store, 1, 10).await.expect("scan");
    assert_eq!(all_events.len(), 2, "only 2 events should exist");
    assert_eq!(all_events[0].seq_no, 1);
    assert_eq!(all_events[1].seq_no, 6);

    // Hash chain is still intact: event2.prev_hash == event1.event_hash
    // (the writer loaded last hash from store on init)
    assert_eq!(event2.prev_hash, event1.event_hash);
}

// ─────────────────────────────────────────────
// Test 3: Export while writes are active (snapshot consistency)
// ─────────────────────────────────────────────

#[tokio::test]
async fn export_snapshot_consistency() {
    let (_dir, store) = temp_store().await;
    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // Write 50 events
    for i in 0..50 {
        writer
            .write(
                &store,
                EnforcementEventType::Deny,
                SubjectKind::File,
                format!("file:src/file_{i}.rs"),
                "claude".to_string(),
                None,
                "gotcha_above_threshold".to_string(),
                None,
            )
            .await
            .expect("write event");
    }

    // Take a snapshot: scan seq 1 to 50
    let snapshot = scan_enforcement_events(&store, 1, 50)
        .await
        .expect("snapshot scan");
    assert_eq!(
        snapshot.len(),
        50,
        "snapshot must contain exactly 50 events"
    );

    // Write 10 more events (seq 51-60)
    for i in 50..60 {
        writer
            .write(
                &store,
                EnforcementEventType::Deny,
                SubjectKind::File,
                format!("file:src/file_{i}.rs"),
                "claude".to_string(),
                None,
                "gotcha_above_threshold".to_string(),
                None,
            )
            .await
            .expect("write event");
    }

    // The original snapshot range still returns exactly 50
    let snapshot_again = scan_enforcement_events(&store, 1, 50)
        .await
        .expect("snapshot scan again");
    assert_eq!(snapshot_again.len(), 50);

    // A full scan shows all 60
    let full = scan_enforcement_events(&store, 1, 60)
        .await
        .expect("full scan");
    assert_eq!(full.len(), 60);
}

// ─────────────────────────────────────────────
// Test 4: Prune/export race
// ─────────────────────────────────────────────

#[tokio::test]
async fn prune_does_not_corrupt_concurrent_export() {
    let (_dir, store) = temp_store().await;
    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // Write 100 events
    for i in 0..100 {
        writer
            .write(
                &store,
                EnforcementEventType::Deny,
                SubjectKind::File,
                format!("file:src/file_{i}.rs"),
                "claude".to_string(),
                None,
                "gotcha_above_threshold".to_string(),
                None,
            )
            .await
            .expect("write event");
    }

    // Simulate pruning: delete events with seq < 50
    for seq in 1..50 {
        let key = format!("enforcement:event:{:020}", seq);
        store.delete(&key).await.expect("delete pruned event");
    }

    // Export scan of remaining range
    let remaining = scan_enforcement_events(&store, 1, 100)
        .await
        .expect("scan after prune");

    // Only seq 50-100 should remain (51 events)
    assert_eq!(remaining.len(), 51);
    assert_eq!(remaining[0].seq_no, 50);
    assert_eq!(remaining[50].seq_no, 100);

    // Verify no corrupted hashes — each event's hash is self-consistent
    for event in &remaining {
        let recomputed = event.compute_hash();
        assert_eq!(
            event.event_hash, recomputed,
            "event {} has corrupted hash",
            event.seq_no
        );
    }
}

// ─────────────────────────────────────────────
// Test 5: Gap detection and recovery
// ─────────────────────────────────────────────

#[tokio::test]
async fn gap_detection_on_recovery() {
    let (_dir, store) = temp_store().await;
    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // Write event 1
    let event1 = writer
        .write(
            &store,
            EnforcementEventType::Deny,
            SubjectKind::File,
            "file:src/main.rs".to_string(),
            "claude".to_string(),
            None,
            "gotcha_above_threshold".to_string(),
            None,
        )
        .await
        .expect("write event 1");
    assert_eq!(event1.seq_no, 1);

    // Simulate daemon going unreachable: advance seq counter manually
    store
        .put_raw("enforcement:seq", &3u64.to_be_bytes())
        .await
        .expect("advance seq to simulate crash");

    // Create new writer (simulates recovery)
    let mut writer2 = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer for recovery");

    // Emit a RecordingGap event
    let gap_event = writer2
        .detect_and_record_gap(
            &store,
            1700000000000,
            1700000060000,
            GapCause::DaemonUnreachable,
        )
        .await
        .expect("record gap");

    // Verify the gap event structure
    assert_eq!(gap_event.seq_no, 4); // seq was at 3, next is 4
    assert_eq!(gap_event.subject_kind, SubjectKind::System);
    assert_eq!(gap_event.decision_reason_code, "recording_gap_detected");

    match &gap_event.event_type {
        EnforcementEventType::RecordingGap {
            gap_start_ms,
            gap_end_ms,
            cause,
            enforcement_mode_during_gap,
            missed_event_count,
            certainty,
        } => {
            assert_eq!(*gap_start_ms, 1700000000000);
            assert_eq!(*gap_end_ms, 1700000060000);
            assert_eq!(*cause, GapCause::DaemonUnreachable);
            assert_eq!(*enforcement_mode_during_gap, EnforcementMode::Advisory);
            assert_eq!(*missed_event_count, MissedEventCount::Unknown);
            assert_eq!(*certainty, GapCertainty::Inferred);
        }
        other => panic!("expected RecordingGap, got {:?}", other),
    }

    // Hash chain from event1 to gap_event is intact
    assert_eq!(gap_event.prev_hash, event1.event_hash);
}

// ─────────────────────────────────────────────
// Test 6: Strict mode write failure
// ─────────────────────────────────────────────

#[tokio::test]
async fn strict_mode_blocks_on_write_failure() {
    // Use a store where we can verify write failure propagation.
    // We'll test by allocating a seq, then verifying that if the event
    // write were to fail, the error propagates correctly.
    //
    // Since we can't easily inject a store failure with the real store,
    // we verify the invariant differently: write to a closed/invalid store path.
    let dir = TempDir::new().expect("tempdir");
    let store = Store::open(dir.path()).await.expect("open store");

    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // First write should succeed
    let event = writer
        .write(
            &store,
            EnforcementEventType::Deny,
            SubjectKind::File,
            "file:src/test.rs".to_string(),
            "claude".to_string(),
            None,
            "gotcha_above_threshold".to_string(),
            None,
        )
        .await
        .expect("first write succeeds");
    assert_eq!(event.seq_no, 1);
    assert_eq!(event.schema_version, SCHEMA_VERSION);

    // Verify the event was actually persisted
    let loaded = scan_enforcement_events(&store, 1, 1).await.expect("scan");
    assert_eq!(loaded.len(), 1);
    assert_eq!(loaded[0].event_hash, event.event_hash);

    // Verify that the seq counter advanced durably
    let seq2 = SeqAllocator::load(&store).await;
    assert_eq!(seq2.current(), 1, "seq must be persisted durably");
}

// ─────────────────────────────────────────────
// Test 7: Canonical path aliasing
// ─────────────────────────────────────────────

#[test]
fn canonical_path_aliasing_produces_same_key() {
    // Use a path that exists on disk for canonicalize_file_key
    // (it needs to resolve against a real repo_root for symlink resolution)
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));

    // These relative paths should all normalize to the same key
    let paths = [
        "src/store/enforcement.rs",
        "./src/store/enforcement.rs",
        "src/store/../store/enforcement.rs",
        "src/./store/enforcement.rs",
    ];

    let canonical_keys: Vec<String> = paths
        .iter()
        .map(|p| canonicalize_file_key(p, &repo_root))
        .collect();

    // All must be identical
    for (i, key) in canonical_keys.iter().enumerate() {
        assert_eq!(
            key, &canonical_keys[0],
            "Path '{}' produced different key '{}' vs '{}'",
            paths[i], key, canonical_keys[0]
        );
    }

    // The canonical key should be the normalized form (possibly lowercased on macOS)
    let expected = if cfg!(target_os = "macos") || cfg!(target_os = "windows") {
        "src/store/enforcement.rs".to_lowercase()
    } else {
        "src/store/enforcement.rs".to_string()
    };
    assert_eq!(canonical_keys[0], expected);
}

// ─────────────────────────────────────────────
// Test 8: Full enforcement lifecycle
// ─────────────────────────────────────────────

#[tokio::test]
async fn full_enforcement_lifecycle_records_all_events() {
    use mati_core::store::enforcement::record_event;

    let (_dir, store) = temp_store().await;

    // 1. Simulate a DENY decision
    let deny_result = record_event(
        &store,
        EnforcementEventType::Deny,
        SubjectKind::File,
        "file:src/billing/charges.rs".to_string(),
        "claude".to_string(),
        None,
        "gotcha_above_threshold".to_string(),
        Some("basis_hash_1".to_string()),
    )
    .await
    .expect("record deny");
    assert!(deny_result.is_some());
    let deny_event = deny_result.unwrap();

    // 2. Simulate a consultation (ReceiptMinted)
    let receipt_result = record_event(
        &store,
        EnforcementEventType::ReceiptMinted,
        SubjectKind::File,
        "file:src/billing/charges.rs".to_string(),
        "claude".to_string(),
        Some("receipt-001".to_string()),
        "consultation_requested".to_string(),
        None,
    )
    .await
    .expect("record receipt");
    assert!(receipt_result.is_some());
    let receipt_event = receipt_result.unwrap();

    // 3. Simulate AllowAfterReceipt
    let allow_result = record_event(
        &store,
        EnforcementEventType::AllowAfterReceipt,
        SubjectKind::File,
        "file:src/billing/charges.rs".to_string(),
        "claude".to_string(),
        Some("receipt-001".to_string()),
        "receipt_valid".to_string(),
        None,
    )
    .await
    .expect("record allow");
    assert!(allow_result.is_some());
    let allow_event = allow_result.unwrap();

    // 4. Read all enforcement events
    let all = scan_enforcement_events(&store, 1, 10).await.expect("scan");
    assert_eq!(all.len(), 3, "expected 3 events");

    // 5. Verify correct types and order
    assert!(matches!(all[0].event_type, EnforcementEventType::Deny));
    assert!(matches!(
        all[1].event_type,
        EnforcementEventType::ReceiptMinted
    ));
    assert!(matches!(
        all[2].event_type,
        EnforcementEventType::AllowAfterReceipt
    ));

    // 6. Verify hash chain
    assert_eq!(deny_event.prev_hash, "", "first event has empty prev_hash");
    assert_eq!(
        receipt_event.prev_hash, deny_event.event_hash,
        "receipt's prev_hash must equal deny's event_hash"
    );
    assert_eq!(
        allow_event.prev_hash, receipt_event.event_hash,
        "allow's prev_hash must equal receipt's event_hash"
    );

    // 7. Verify all hashes are self-consistent
    for event in &all {
        assert_eq!(event.event_hash, event.compute_hash());
    }
}

// ─────────────────────────────────────────────
// Test 9: Control change events from gotcha CRUD
// ─────────────────────────────────────────────

#[tokio::test]
async fn gotcha_crud_records_control_changed_events() {
    use mati_core::store::enforcement::ControlChangeKind;
    use mati_core::store::gotcha_ops::{
        apply_gotcha_confirm, apply_gotcha_tombstone, apply_gotcha_write,
    };
    use mati_core::store::record::{
        Category, ConfidenceScore, GotchaRecord, Priority, QualityScore, Record, RecordLifecycle,
        RecordSource, RecordVersion, StalenessScore,
    };

    let (_dir, store) = temp_store().await;

    // Helper to build a gotcha record
    let make_gotcha = |key: &str, confirmed: bool| -> Record {
        let gotcha = GotchaRecord {
            rule: "test rule".into(),
            reason: "test reason".into(),
            severity: Priority::High,
            affected_files: vec!["src/test.rs".into()],
            ref_url: None,
            discovered_session: 1_000_000,
            confirmed,
        };
        Record {
            key: key.to_string(),
            value: "test rule because test reason".into(),
            payload: serde_json::to_value(&gotcha).ok(),
            category: Category::Gotcha,
            priority: Priority::High,
            tags: vec![],
            created_at: 1_000_000,
            updated_at: 1_000_000,
            ref_url: None,
            staleness: StalenessScore::fresh(),
            lifecycle: RecordLifecycle::Active,
            version: RecordVersion {
                device_id: uuid::Uuid::new_v4(),
                logical_clock: 1,
                wall_clock: 1_000_000,
            },
            quality: QualityScore::layer0_default(),
            access_count: 0,
            last_accessed: 0,
            source: RecordSource::DeveloperManual,
            confidence: ConfidenceScore::for_new_record(&RecordSource::DeveloperManual),
            gap_analysis_score: 0.0,
        }
    };

    // 1. Create a gotcha → ControlChanged::Created
    let record = make_gotcha("gotcha:test-crud", false);
    apply_gotcha_write(&store, &record, &[], &["src/test.rs".into()], true)
        .await
        .expect("create gotcha");

    // 2. Confirm the gotcha → ControlChanged::Confirmed
    let confirmed_record = make_gotcha("gotcha:test-crud", true);
    apply_gotcha_confirm(&store, &confirmed_record, &["src/test.rs".into()])
        .await
        .expect("confirm gotcha");

    // 3. Update the gotcha → ControlChanged::Updated
    let mut record2 = make_gotcha("gotcha:test-crud", true);
    record2.value = "updated rule".into();
    apply_gotcha_write(
        &store,
        &record2,
        &["src/test.rs".into()],
        &["src/test.rs".into()],
        false,
    )
    .await
    .expect("update gotcha");

    // 4. Delete the gotcha → ControlChanged::Deleted
    apply_gotcha_tombstone(&store, "gotcha:test-crud", &["src/test.rs".into()])
        .await
        .expect("delete gotcha");

    // Read all enforcement events
    let events = scan_enforcement_events(&store, 1, 100).await.expect("scan");

    // Filter ControlChanged events — seq_no is monotonic so this preserves order.
    let control_events: Vec<_> = events
        .iter()
        .filter(|e| matches!(e.event_type, EnforcementEventType::ControlChanged { .. }))
        .collect();

    assert_eq!(
        control_events.len(),
        4,
        "expected exactly 4 ControlChanged events (Created, Confirmed, Updated, Deleted), got {}: {:?}",
        control_events.len(),
        control_events
            .iter()
            .map(|e| &e.event_type)
            .collect::<Vec<_>>()
    );

    // Verify the change kinds fired in the exact CRUD order.
    let kinds: Vec<ControlChangeKind> = control_events
        .iter()
        .map(|e| match &e.event_type {
            EnforcementEventType::ControlChanged { change_kind } => *change_kind,
            _ => unreachable!(),
        })
        .collect();
    assert_eq!(
        kinds,
        vec![
            ControlChangeKind::Created,
            ControlChangeKind::Confirmed,
            ControlChangeKind::Updated,
            ControlChangeKind::Deleted,
        ],
        "ControlChanged events must fire in CRUD order"
    );

    // Reason codes match the kinds.
    let reason_codes: Vec<&str> = control_events
        .iter()
        .map(|e| e.decision_reason_code.as_str())
        .collect();
    assert_eq!(
        reason_codes,
        vec![
            "control_created",
            "control_confirmed",
            "control_updated",
            "control_deleted",
        ],
    );

    // All events reference the correct subject and agent.
    for e in &control_events {
        assert_eq!(e.subject_key, "gotcha:test-crud");
        assert_eq!(e.subject_kind, SubjectKind::Control);
        assert_eq!(e.agent_type, "developer");
    }

    // Hash chain intact — seq_no is strictly increasing and prev_hash chains
    // forward across ALL events in the store, not just the ControlChanged
    // subset (other event types may interleave, but for this isolated test
    // only ControlChanged events are recorded).
    for window in control_events.windows(2) {
        assert!(
            window[1].seq_no > window[0].seq_no,
            "seq_no must be strictly increasing: {} → {}",
            window[0].seq_no,
            window[1].seq_no
        );
        assert_eq!(
            window[1].prev_hash, window[0].event_hash,
            "prev_hash must chain from previous event_hash"
        );
    }

    // Each event's computed hash must equal its stored event_hash.
    for e in &control_events {
        assert_eq!(
            e.event_hash,
            e.compute_hash(),
            "stored event_hash must match canonical re-computation"
        );
    }
}

// ─────────────────────────────────────────────
// Test 10: Retention pruning
// ─────────────────────────────────────────────

#[tokio::test]
async fn retention_prunes_old_events_and_records_prune_event() {
    use mati_core::store::enforcement::{enforce_retention, set_retention_days, PruneResult};

    let (_dir, store) = temp_store().await;

    // Set a very short retention (1 day) for testing
    set_retention_days(&store, 1).await.expect("set retention");

    // Write 5 events with old timestamps (simulate 400 days ago)
    // We do this by directly writing events with old recorded_at_ms
    let old_ms = {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;
        now.saturating_sub(400 * 86_400_000) // 400 days ago
    };

    let mut writer = EnforcementEventWriter::new(&store)
        .await
        .expect("create writer");

    // Write events that will have current timestamps
    for i in 0..5 {
        writer
            .write(
                &store,
                EnforcementEventType::Deny,
                SubjectKind::File,
                format!("file:old_{i}.rs"),
                "claude".to_string(),
                None,
                "gotcha_above_threshold".to_string(),
                None,
            )
            .await
            .expect("write old event");
    }

    // Manually patch these events to have old timestamps
    for seq in 1..=5u64 {
        let key = format!("enforcement:event:{:020}", seq);
        if let Ok(Some(bytes)) = store.get_raw_bytes(&key).await {
            if let Ok(mut event) =
                serde_json::from_slice::<mati_core::store::enforcement::EnforcementEvent>(&bytes)
            {
                event.recorded_at_ms = old_ms;
                let patched = serde_json::to_vec(&event).unwrap();
                store.put_raw(&key, &patched).await.unwrap();
            }
        }
    }

    // Write 3 recent events (these should survive pruning)
    for i in 0..3 {
        writer
            .write(
                &store,
                EnforcementEventType::AllowAfterReceipt,
                SubjectKind::File,
                format!("file:new_{i}.rs"),
                "claude".to_string(),
                None,
                "receipt_valid".to_string(),
                None,
            )
            .await
            .expect("write new event");
    }

    // Run retention
    let result = enforce_retention(&store).await.expect("enforce retention");

    match result {
        PruneResult::Pruned {
            count,
            oldest_seq,
            newest_seq,
        } => {
            assert_eq!(count, 5, "should prune 5 old events");
            assert_eq!(oldest_seq, 1);
            assert_eq!(newest_seq, 5);
        }
        PruneResult::NothingToPrune => panic!("expected pruning to happen"),
    }

    // Verify: old events are gone, new events remain
    let remaining = scan_enforcement_events(&store, 1, 100).await.expect("scan");

    // Should have 3 recent events + 1 RetentionPruned event = 4
    assert_eq!(
        remaining.len(),
        4,
        "expected 4 events (3 recent + 1 prune record)"
    );

    // The last event should be RetentionPruned
    let prune_events: Vec<_> = remaining
        .iter()
        .filter(|e| matches!(e.event_type, EnforcementEventType::RetentionPruned { .. }))
        .collect();
    assert_eq!(prune_events.len(), 1);
    if let EnforcementEventType::RetentionPruned {
        pruned_count,
        oldest_pruned_seq,
        newest_pruned_seq,
    } = &prune_events[0].event_type
    {
        assert_eq!(*pruned_count, 5);
        assert_eq!(*oldest_pruned_seq, 1);
        assert_eq!(*newest_pruned_seq, 5);
    }
}

// ─────────────────────────────────────────────
// Test 11: Strict mode end-to-end
// ─────────────────────────────────────────────

#[tokio::test]
async fn strict_mode_enforcement_config_records_change_event() {
    use mati_core::store::enforcement::{get_enforcement_mode, record_event, set_enforcement_mode};

    let (_dir, store) = temp_store().await;

    // Default mode is advisory
    let mode = get_enforcement_mode(&store).await;
    assert_eq!(mode, EnforcementMode::Advisory);

    // Switch to strict
    let old = set_enforcement_mode(&store, EnforcementMode::Strict)
        .await
        .expect("set strict");
    assert_eq!(old, EnforcementMode::Advisory);

    // Verify mode is now strict
    let mode = get_enforcement_mode(&store).await;
    assert_eq!(mode, EnforcementMode::Strict);

    // Switch back to advisory
    let old = set_enforcement_mode(&store, EnforcementMode::Advisory)
        .await
        .expect("set advisory");
    assert_eq!(old, EnforcementMode::Strict);

    // Verify EnforcementConfigChanged events were recorded
    let events = scan_enforcement_events(&store, 1, 100).await.expect("scan");

    let config_events: Vec<_> = events
        .iter()
        .filter(|e| {
            matches!(
                e.event_type,
                EnforcementEventType::EnforcementConfigChanged { .. }
            )
        })
        .collect();

    assert_eq!(
        config_events.len(),
        2,
        "expected 2 config change events (advisory→strict, strict→advisory)"
    );

    // Verify first change: advisory → strict
    if let EnforcementEventType::EnforcementConfigChanged {
        setting,
        old_value,
        new_value,
    } = &config_events[0].event_type
    {
        assert_eq!(setting, "audit.write_durability");
        assert_eq!(old_value, "best_effort");
        assert_eq!(new_value, "strict");
    }

    // Verify second change: strict → advisory
    if let EnforcementEventType::EnforcementConfigChanged {
        setting,
        old_value,
        new_value,
    } = &config_events[1].event_type
    {
        assert_eq!(setting, "audit.write_durability");
        assert_eq!(old_value, "strict");
        assert_eq!(new_value, "best_effort");
    }

    // In strict mode, record_event should propagate errors
    // First set to strict
    set_enforcement_mode(&store, EnforcementMode::Strict)
        .await
        .expect("set strict again");

    // Normal writes should still succeed in strict mode
    let result = record_event(
        &store,
        EnforcementEventType::Deny,
        SubjectKind::File,
        "file:test.rs".to_string(),
        "claude".to_string(),
        None,
        "gotcha_above_threshold".to_string(),
        None,
    )
    .await;
    assert!(result.is_ok(), "strict mode write should succeed");
    assert!(result.unwrap().is_some());
}

// ─────────────────────────────────────────────
// Test 12: Config set/get round-trips correctly
// ─────────────────────────────────────────────

#[tokio::test]
async fn record_event_with_session_attributes_event_v2() {
    use mati_core::store::enforcement::record_event_with_session;
    let (_dir, store) = temp_store().await;

    record_event_with_session(
        &store,
        EnforcementEventType::Deny,
        SubjectKind::File,
        "file:src/pay.rs".to_string(),
        "claude".to_string(),
        None,
        "edit_blocked_unconsulted".to_string(),
        None,
        Some("sess-xyz".to_string()),
    )
    .await
    .expect("record");

    let events = scan_enforcement_events(&store, 1, 100).await.expect("scan");
    let ev = events
        .iter()
        .find(|e| matches!(e.event_type, EnforcementEventType::Deny))
        .expect("deny event recorded");
    assert_eq!(
        ev.agent_session.as_deref(),
        Some("sess-xyz"),
        "the agent session must be recorded on the event"
    );
    assert_eq!(ev.schema_version, 2, "new events are schema_version 2");
    // The session is part of the v2 canonical form, so a recorded event
    // self-verifies (event_hash == compute_hash) — tamper-evident attribution.
    assert_eq!(
        ev.event_hash,
        ev.compute_hash(),
        "v2 event must self-verify"
    );
}

#[tokio::test]
async fn config_enforcement_mode_round_trips() {
    use mati_core::store::enforcement::{get_enforcement_mode, set_enforcement_mode};

    let (_dir, store) = temp_store().await;

    // Default is advisory
    assert_eq!(
        get_enforcement_mode(&store).await,
        EnforcementMode::Advisory
    );

    // Set to strict and read back
    set_enforcement_mode(&store, EnforcementMode::Strict)
        .await
        .expect("set strict");
    assert_eq!(get_enforcement_mode(&store).await, EnforcementMode::Strict);

    // Set back to advisory and read back
    set_enforcement_mode(&store, EnforcementMode::Advisory)
        .await
        .expect("set advisory");
    assert_eq!(
        get_enforcement_mode(&store).await,
        EnforcementMode::Advisory
    );

    // Retention round-trip
    use mati_core::store::enforcement::{get_retention_days, set_retention_days};
    assert_eq!(get_retention_days(&store).await, 365); // default
    set_retention_days(&store, 90).await.expect("set 90");
    assert_eq!(get_retention_days(&store).await, 90);
}

// ─────────────────────────────────────────────
// Test 13: Config set records EnforcementConfigChanged
// ─────────────────────────────────────────────

#[tokio::test]
async fn config_set_enforcement_mode_records_event() {
    use mati_core::store::enforcement::set_enforcement_mode;

    let (_dir, store) = temp_store().await;

    // Change mode — should record an event
    set_enforcement_mode(&store, EnforcementMode::Strict)
        .await
        .expect("set strict");

    let events = scan_enforcement_events(&store, 1, 100).await.expect("scan");

    let config_events: Vec<_> = events
        .iter()
        .filter(|e| {
            matches!(
                e.event_type,
                EnforcementEventType::EnforcementConfigChanged { .. }
            )
        })
        .collect();

    assert_eq!(config_events.len(), 1, "expected 1 config change event");
    if let EnforcementEventType::EnforcementConfigChanged {
        setting,
        old_value,
        new_value,
    } = &config_events[0].event_type
    {
        assert_eq!(setting, "audit.write_durability");
        assert_eq!(old_value, "best_effort");
        assert_eq!(new_value, "strict");
    } else {
        panic!("expected EnforcementConfigChanged");
    }

    // Setting the same mode again should NOT record another event
    set_enforcement_mode(&store, EnforcementMode::Strict)
        .await
        .expect("set strict again");

    let events2 = scan_enforcement_events(&store, 1, 100).await.expect("scan");
    let config_events2: Vec<_> = events2
        .iter()
        .filter(|e| {
            matches!(
                e.event_type,
                EnforcementEventType::EnforcementConfigChanged { .. }
            )
        })
        .collect();
    assert_eq!(
        config_events2.len(),
        1,
        "setting same mode should not record another event"
    );
}

// ─────────────────────────────────────────────
// Derived metrics survive the real store round-trip
// ─────────────────────────────────────────────

/// Closes the gap unit tests can't: that `agent_session` recorded via the real
/// write path persists through a `scan_events_since` round-trip, so
/// `derive_enforcement_metrics` produces a NON-null `blocks_per_session` from
/// genuinely stored events (not hand-built ones). Also exercises Deny→consult
/// pairing against real `recorded_at_ms` stamping.
#[tokio::test]
async fn derived_metrics_from_real_store_roundtrip() {
    use mati_core::store::enforcement::{
        aggregate_event_counts, derive_enforcement_metrics, record_event_with_session,
        scan_events_since,
    };
    use mati_core::store::session::CONSULTED_RECENT_TTL_SECS;

    let (_dir, store) = temp_store().await;

    // sessA is blocked on two files; sessB on one → 3 denials across 2 sessions.
    let denials = [
        ("file:src/a.rs", "sessA"),
        ("file:src/b.rs", "sessA"),
        ("file:src/c.rs", "sessB"),
    ];
    for (subject, session) in denials {
        record_event_with_session(
            &store,
            EnforcementEventType::Deny,
            SubjectKind::File,
            subject.to_string(),
            "claude".to_string(),
            None,
            "gotcha_above_threshold".to_string(),
            None,
            Some(session.to_string()),
        )
        .await
        .expect("record sessioned deny");
    }

    // Consultation receipts (MCP path → no session id), recorded after the
    // denials so each receipt timestamp is >= its subject's deny timestamp.
    for subject in ["file:src/a.rs", "file:src/b.rs", "file:src/c.rs"] {
        record_event_with_session(
            &store,
            EnforcementEventType::ReceiptMinted,
            SubjectKind::File,
            subject.to_string(),
            "claude".to_string(),
            None,
            "consultation_requested".to_string(),
            None,
            None,
        )
        .await
        .expect("record receipt");
    }

    // Read back through the real scan path (the part pure unit tests skip).
    let events = scan_events_since(&store, 0).await.expect("scan events");
    let counts = aggregate_event_counts(&events);
    let derived = derive_enforcement_metrics(&events);

    // Counts survived the store round-trip.
    assert_eq!(counts.denials, 3, "three denials recorded");
    assert_eq!(counts.receipts_minted, 3, "three receipts recorded");

    // THE GAP CLOSER: session ids persisted through write+scan, so
    // blocks-per-session is attributable and non-null.
    assert_eq!(derived.blocked_sessions, 2, "sessA + sessB");
    assert_eq!(derived.attributed_denials, 3);
    assert_eq!(
        derived.blocks_per_session,
        Some(1.5),
        "3 denials / 2 sessions"
    );

    // Deny→consult pairs found via real recorded_at_ms; each delta within window.
    assert_eq!(derived.consult_pairs, 3, "one consult pair per subject");
    let median = derived
        .median_time_to_consult_ms
        .expect("median exists once pairs are found");
    assert!(
        median <= CONSULTED_RECENT_TTL_SECS * 1_000,
        "real-time deltas must fall inside the consult window (got {median}ms)"
    );
}

// ─────────────────────────────────────────────
// `gotcha add` on an un-indexed file must still wire the read gate
// ─────────────────────────────────────────────

/// Regression: `mati gotcha add` (→ `apply_gotcha_write`) on a file that
/// `init` never indexed must still wire the read gate. The gate (`hooks/decide.rs`)
/// finds gotchas via the file record's denormalized `payload.gotcha_keys`. The
/// create-on-write fix in `update_file_gotcha_key` persists a minimal layer-0
/// file stub carrying the gotcha key when no file record exists, so the gotcha
/// enforces immediately instead of staying inert until the next `mati init`.
#[tokio::test]
async fn gotcha_add_on_unindexed_file_wires_read_gate() {
    use mati_core::store::gotcha_ops::apply_gotcha_write;
    use mati_core::store::record::{
        Category, ConfidenceScore, FileRecord, GotchaRecord, Priority, QualityScore, Record,
        RecordLifecycle, RecordSource, RecordVersion, StalenessScore,
    };

    let (_dir, store) = temp_store().await;
    let file = "src/never_indexed_by_init.rs";
    let gkey = "gotcha:never-bypass-the-gate";

    let gotcha = GotchaRecord {
        rule: "Never bypass the gate".into(),
        reason: "It is load-bearing".into(),
        severity: Priority::Critical,
        affected_files: vec![file.into()],
        ref_url: None,
        discovered_session: 1_000_000,
        confirmed: true,
    };
    let record = Record {
        key: gkey.into(),
        value: "Never bypass the gate because it is load-bearing".into(),
        payload: serde_json::to_value(&gotcha).ok(),
        category: Category::Gotcha,
        priority: Priority::Critical,
        tags: vec![],
        created_at: 1_000_000,
        updated_at: 1_000_000,
        ref_url: None,
        staleness: StalenessScore::fresh(),
        lifecycle: RecordLifecycle::Active,
        version: RecordVersion {
            device_id: uuid::Uuid::new_v4(),
            logical_clock: 1,
            wall_clock: 1_000_000,
        },
        quality: QualityScore::developer_entry_default(),
        access_count: 0,
        last_accessed: 0,
        source: RecordSource::DeveloperManual,
        confidence: ConfidenceScore::for_new_record(&RecordSource::DeveloperManual),
        gap_analysis_score: 0.0,
    };

    // Exactly what `mati gotcha add <file>` does for a brand-new file.
    apply_gotcha_write(&store, &record, &[], &[file.to_string()], true)
        .await
        .expect("write gotcha");

    assert!(
        store.get(gkey).await.expect("get gotcha").is_some(),
        "gotcha record should exist"
    );

    // The fix: a file record is created carrying the gotcha key, so the read
    // gate can see it. (Previously, no file record existed → gate inert.)
    let file_record = store
        .get(&format!("file:{file}"))
        .await
        .expect("get file record")
        .expect("gotcha add must create a file record so the read gate fires");
    let fr: FileRecord = file_record
        .payload_as()
        .expect("file record payload is a FileRecord");
    assert!(
        fr.gotcha_keys.contains(&gkey.to_string()),
        "the created file record must carry the gotcha key in gotcha_keys (got {:?})",
        fr.gotcha_keys
    );
    // The created record must be Active + Fresh so the gate proceeds to check
    // gotchas rather than treating it as a stale/tombstoned passthrough.
    assert!(matches!(
        file_record.lifecycle,
        mati_core::store::RecordLifecycle::Active
    ));
}