quorum-cli 0.3.0

Quorum CLI: the quorum binary.
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
//! Phase 1B Stage 1 integration tests for the `LocalSqliteMemoryStore`.
//!
//! Drives the store end-to-end through a fresh tempdir-rooted git repo:
//! open + migrate, dismiss + AlreadyDismissed, record_seen idempotence per
//! session, delete idempotence on unknown ids, CHECK constraints fire,
//! pragmas applied, reopen integrity after WAL sidecars present.
//!
//! ACs covered: 60, 96, 97, 98, 103, 104, 105, 106, 107, 108, 109, 110,
//! 111, 113, 118.

use quorum_core::memory::identity::finding_identity_hash;
use quorum_core::memory::{
    DismissalReason, FindingIdentityHash, LocalSqliteMemoryStore, MemoryError, MemoryStore,
    PromotionState, ShortHashResolution, TransitionTrigger, BODY_SNAPSHOT_MAX_BYTES,
};
use quorum_core::review::{Finding, FindingSource, Severity};
use rusqlite::Connection;
use tempfile::TempDir;

fn init_repo() -> TempDir {
    let td = TempDir::new().unwrap();
    let _ = git2::Repository::init(td.path()).unwrap();
    td
}

fn sample_finding(title: &str, models: &[&str]) -> Finding {
    Finding {
        severity: Severity::High,
        title: title.to_string(),
        body: format!("Confidence: 0.90. Supported by: {}.", models.join(", ")),
        source: FindingSource::Divergence,
        supported_by: models.iter().map(|s| s.to_string()).collect(),
        confidence: Some(0.90),
    }
}

#[test]
fn opens_and_migrates_to_current_version() {
    // AC 104 (1B) + AC 145 (1C): schema_version row exists at the
    // current binary version after first open. Phase 1B asserted v=1;
    // Phase 1C bumps it to v=2 with the schema_meta forward-compat row.
    // AC 110: <repo_root>/.quorum/dismissals.sqlite created on first open.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    assert!(store.path().exists(), "sqlite file must exist after new()");
    let conn = Connection::open(store.path()).unwrap();
    let version: i64 = conn
        .query_row("SELECT version FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, 2);
    let fwd: String = conn
        .query_row(
            "SELECT value FROM schema_meta WHERE key = 'forward_compat_min_version'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(fwd, "2");
}

#[test]
fn reopen_is_idempotent() {
    // AC 105: re-opening the DB does not re-run version=1 DDL.
    let td = init_repo();
    drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    let conn = Connection::open(td.path().join(".quorum").join("dismissals.sqlite")).unwrap();
    let n: i64 = conn
        .query_row("SELECT COUNT(*) FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(n, 1);
}

#[test]
fn pragmas_applied() {
    // AC 111: journal_mode (WAL or fallback), foreign_keys=ON, busy_timeout=5000.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let conn = Connection::open(store.path()).unwrap();
    let journal_mode: String = conn
        .query_row("PRAGMA journal_mode", [], |r| r.get(0))
        .unwrap();
    // WAL is expected; rollback journal ("delete") is the documented
    // fallback for NFS/SMB filesystems. Either is acceptable.
    assert!(
        journal_mode.eq_ignore_ascii_case("wal") || journal_mode.eq_ignore_ascii_case("delete"),
        "unexpected journal_mode {journal_mode}"
    );
    let foreign_keys: i64 = conn
        .query_row("PRAGMA foreign_keys", [], |r| r.get(0))
        .unwrap();
    assert_eq!(foreign_keys, 1, "foreign_keys must be ON");
    let busy_timeout: i64 = conn
        .query_row("PRAGMA busy_timeout", [], |r| r.get(0))
        .unwrap();
    assert_eq!(busy_timeout, 5000, "busy_timeout must be 5000ms");
}

#[test]
fn dismiss_then_load_active_returns_row() {
    // AC 60 (default 365d) + AC 66 baseline (load reports the dismissal).
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("Critical bug", &["claude-sonnet", "gpt-4o"]);
    let id = store
        .dismiss(
            &f,
            "headsha",
            "main",
            DismissalReason::WontFix,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    assert!(id.0 > 0);
    let active = store.load_active_dismissals().unwrap();
    let h = finding_identity_hash(&f);
    let row = active.get(&h).expect("dismissal must be active");
    assert_eq!(row.recurrence_count, 1);
    assert!(row.expires_at.is_some());
    assert_eq!(row.promotion_state, PromotionState::Candidate);
    assert_eq!(row.reason, DismissalReason::WontFix);
}

#[test]
fn dismiss_duplicate_returns_already_dismissed() {
    // AC 107: duplicate finding_identity_hash → AlreadyDismissed.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("dup", &["m"]);
    store
        .dismiss(
            &f,
            "headsha",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    let err = store
        .dismiss(
            &f,
            "headsha",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap_err();
    assert!(matches!(err, MemoryError::AlreadyDismissed));
}

#[test]
fn record_seen_idempotent_per_session_and_bumps_per_new_session() {
    // AC 108: idempotent per (hash, session_id). AC 96: bumps once.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("ZZZ", &["m"]);
    store
        .dismiss(
            &f,
            "headsha",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    let h = finding_identity_hash(&f);
    let now = time::OffsetDateTime::now_utc();

    // Use a very high threshold so T1 doesn't fire in this Phase 1B
    // regression test — we're checking the per-session idempotency
    // contract, not the new auto-promote behavior.
    let high = 1_000_000u32;
    store.record_seen(&[h], "session-A", now, high).unwrap();
    store
        .record_seen(&[h], "session-A", now + time::Duration::seconds(1), high)
        .unwrap();
    let row = store.load_active_dismissals().unwrap()[&h].clone();
    assert_eq!(row.recurrence_count, 2, "session-A bumps once total");

    store
        .record_seen(&[h], "session-B", now + time::Duration::seconds(2), high)
        .unwrap();
    let row = store.load_active_dismissals().unwrap()[&h].clone();
    assert_eq!(row.recurrence_count, 3, "session-B bumps once more");
}

#[test]
fn delete_idempotent_on_unknown_and_known_ids() {
    // AC 109: delete returns Ok(false) on unknown, Ok(true) on known.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    assert!(!store
        .delete(quorum_core::memory::DismissalId(99_999))
        .unwrap());

    let f = sample_finding("D", &["m"]);
    let id = store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::Intentional,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    assert!(store.delete(id).unwrap());
    assert!(!store.delete(id).unwrap());
}

#[test]
fn permanent_dismissal_persists_indefinitely() {
    // AC 97: permanent (`expires_at=NULL`) still returned by load_active.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("permanent", &["m"]);
    store
        .dismiss(&f, "h", "main", DismissalReason::Intentional, None, None)
        .unwrap();
    let active = store.load_active_dismissals().unwrap();
    let row = active.get(&finding_identity_hash(&f)).unwrap();
    assert!(row.expires_at.is_none());
}

#[test]
fn expired_dismissal_not_returned() {
    // AC 97 negative: explicitly expired rows are filtered out.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("already-expired", &["m"]);
    store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::seconds(-1)),
        )
        .unwrap();
    let active = store.load_active_dismissals().unwrap();
    assert!(active.is_empty());
}

#[test]
fn check_constraints_fire() {
    // AC 106: CHECK constraints. We verify by talking to SQLite directly
    // via the store's file (the trait API guards these via validate_note,
    // so to exercise SQLite's CHECK we drop down to raw SQL here).
    let td = init_repo();
    drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    let conn = Connection::open(td.path().join(".quorum").join("dismissals.sqlite")).unwrap();

    let insert_with = |reason: &str, note: Option<&str>, promo: &str, count: i64| {
        conn.execute(
            "INSERT INTO dismissals (
                finding_identity_hash, title_snapshot, source_type_snapshot,
                models_snapshot, branch_snapshot, reason, note,
                dismissed_at, last_seen_at, recurrence_count,
                repo_head_sha_first, promotion_state
            ) VALUES (?1, 't', 'agreement', '[]', 'main', ?2, ?3, ?4, ?4, ?5, 'sha', ?6)",
            rusqlite::params![
                format!("{:064}", count), // unique per insert attempt
                reason,
                note,
                "2026-01-01T00:00:00Z",
                count,
                promo,
            ],
        )
    };

    assert!(
        insert_with("false_positive", None, "candidate", 0).is_err(),
        "recurrence_count = 0 must fail"
    );
    assert!(
        insert_with("bogus_reason", None, "candidate", 1).is_err(),
        "unknown reason must fail"
    );
    assert!(
        insert_with("other", None, "candidate", 1).is_err(),
        "reason=other without note must fail"
    );
    assert!(
        insert_with("false_positive", None, "bogus_promo", 1).is_err(),
        "unknown promotion_state must fail"
    );
    // Sanity: a fully valid row goes in.
    assert!(
        insert_with("false_positive", None, "candidate", 1).is_ok(),
        "valid row should succeed"
    );
}

#[test]
fn body_snapshot_bounded_to_2kb_at_codepoint_boundary() {
    // AC: bounded ≤2KB; body_snapshot is a prefix.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let huge = "ä".repeat(3000); // 6000 bytes — well above 2KB.
    let f = Finding {
        body: huge.clone(),
        ..sample_finding("BIG", &["m"])
    };
    let id = store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    let row = store.get(id).unwrap().unwrap();
    let body = row.body_snapshot.unwrap();
    assert!(body.len() <= BODY_SNAPSHOT_MAX_BYTES);
    assert!(huge.starts_with(&body));
}

#[test]
fn reopen_after_dropping_with_wal_sidecars() {
    // AC 118: SQLite reopen integrity. Replaces v0.1's WAL-cleanup AC.
    let td = init_repo();
    let f = sample_finding("preserved", &["m"]);
    let key: FindingIdentityHash;
    {
        let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
        key = finding_identity_hash(&f);
        store
            .dismiss(
                &f,
                "h",
                "main",
                DismissalReason::WontFix,
                None,
                Some(time::Duration::days(365)),
            )
            .unwrap();
        // Implicit drop simulates hard-kill (no explicit close).
    }
    let store2 = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let active = store2.load_active_dismissals().unwrap();
    assert!(active.contains_key(&key));
}

#[test]
fn other_without_note_rejected_at_trait_layer() {
    // AC: trait-layer validation of OtherWithoutNote.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("o", &["m"]);
    let err = store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::Other,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap_err();
    assert!(matches!(err, MemoryError::OtherWithoutNote));
}

#[test]
fn note_size_and_format_validated() {
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("n", &["m"]);
    let too_big = "x".repeat(quorum_core::memory::NOTE_MAX_BYTES + 1);
    let err = store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::FalsePositive,
            Some(too_big),
            Some(time::Duration::days(365)),
        )
        .unwrap_err();
    assert!(matches!(err, MemoryError::InvalidNote));

    let with_newline = "valid\nnope".to_string();
    let f2 = sample_finding("n2", &["m"]);
    let err = store
        .dismiss(
            &f2,
            "h",
            "main",
            DismissalReason::FalsePositive,
            Some(with_newline),
            Some(time::Duration::days(365)),
        )
        .unwrap_err();
    assert!(matches!(err, MemoryError::InvalidNote));
}

#[test]
fn gitignore_written_on_first_open() {
    // AC 98: .quorum/dismissals.sqlite* appended to .gitignore.
    let td = init_repo();
    let _store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let gi = std::fs::read_to_string(td.path().join(".gitignore")).unwrap();
    assert!(gi.contains(".quorum/dismissals.sqlite*"));
    assert!(gi.contains("Quorum dismissals store"));
}

// =================================================================
// Phase 1C Stage 1 — v2 migration, forward-compat, byte-count CHECK.
// =================================================================

/// Build a v1-shaped SQLite at `path`, with one Phase 1B dismissal row.
/// Mirrors the schema Phase 1B shipped, so we can verify the in-place
/// v1→v2 upgrade path.
fn build_v1_fixture(path: &std::path::Path) {
    let conn = Connection::open(path).unwrap();
    conn.execute_batch(
        "CREATE TABLE schema_version (
            version INTEGER PRIMARY KEY,
            applied_at TEXT NOT NULL
        );
        CREATE TABLE dismissals (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            finding_identity_hash TEXT NOT NULL UNIQUE,
            title_snapshot TEXT NOT NULL,
            body_snapshot TEXT,
            source_type_snapshot TEXT NOT NULL,
            models_snapshot TEXT NOT NULL,
            branch_snapshot TEXT NOT NULL,
            reason TEXT NOT NULL,
            note TEXT,
            dismissed_at TEXT NOT NULL,
            last_seen_at TEXT NOT NULL,
            last_seen_session_id TEXT,
            recurrence_count INTEGER NOT NULL DEFAULT 1,
            expires_at TEXT,
            repo_head_sha_first TEXT NOT NULL,
            promotion_state TEXT NOT NULL DEFAULT 'candidate',
            CHECK (recurrence_count >= 1),
            CHECK (reason IN ('false_positive','intentional','out_of_scope','wont_fix','other')),
            CHECK (reason != 'other' OR note IS NOT NULL),
            CHECK (promotion_state IN ('candidate','local_only','promoted_convention'))
        );
        CREATE INDEX idx_dismissals_expires_at ON dismissals(expires_at);
        INSERT INTO schema_version (version, applied_at) VALUES (1, '2026-01-01T00:00:00Z');",
    )
    .unwrap();
    conn.execute(
        "INSERT INTO dismissals (
            finding_identity_hash, title_snapshot, source_type_snapshot,
            models_snapshot, branch_snapshot, reason,
            dismissed_at, last_seen_at, recurrence_count, repo_head_sha_first
        ) VALUES (?1, 'preexisting', 'agreement', '[]', 'main', 'false_positive',
                  ?2, ?2, 2, 'sha')",
        rusqlite::params!["e".repeat(64), "2026-01-01T00:00:00Z"],
    )
    .unwrap();
}

#[test]
fn migrate_upgrades_v1_fixture_to_v2() {
    // AC 145: v1→v2 migration runs cleanly on a Phase 1B-shaped fixture.
    // Pre-existing dismissal row survives; schema_meta marker present;
    // schema_version bumped to 2.
    let td = init_repo();
    let quorum_dir = td.path().join(".quorum");
    std::fs::create_dir_all(&quorum_dir).unwrap();
    let db_path = quorum_dir.join("dismissals.sqlite");
    build_v1_fixture(&db_path);

    // Opening the store runs the v2 migration.
    let _store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let conn = Connection::open(&db_path).unwrap();

    let version: i64 = conn
        .query_row("SELECT version FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, 2, "schema_version must be bumped to 2");
    let n: i64 = conn
        .query_row("SELECT COUNT(*) FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(n, 1, "schema_version must remain a single row");
    let fwd: String = conn
        .query_row(
            "SELECT value FROM schema_meta WHERE key = 'forward_compat_min_version'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(fwd, "2");

    // Pre-existing dismissal row preserved.
    let surviving: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM dismissals WHERE title_snapshot = 'preexisting'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(surviving, 1);

    // No backfill of state_transitions for pre-v2 rows (spec §4.1).
    let st_count: i64 = conn
        .query_row("SELECT COUNT(*) FROM state_transitions", [], |r| r.get(0))
        .unwrap();
    assert_eq!(st_count, 0);
}

#[test]
fn migrate_is_idempotent_on_v2() {
    // AC 145: re-running the migration on a v2 DB is a no-op (no errors,
    // no duplicate rows, schema_meta unchanged).
    let td = init_repo();
    let db_path = {
        let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
        store.path().to_owned()
    };
    // Insert a dismissal so we can detect any accidental wipe.
    {
        let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
        let f = sample_finding("idempotency probe", &["m"]);
        store
            .dismiss(
                &f,
                "h",
                "main",
                DismissalReason::FalsePositive,
                None,
                Some(time::Duration::days(365)),
            )
            .unwrap();
    }
    // Re-open several times: the migration runs each time but is a no-op.
    for _ in 0..3 {
        drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    }
    let conn = Connection::open(&db_path).unwrap();
    let version: i64 = conn
        .query_row("SELECT version FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(version, 2);
    let n: i64 = conn
        .query_row("SELECT COUNT(*) FROM schema_version", [], |r| r.get(0))
        .unwrap();
    assert_eq!(n, 1, "no extra schema_version rows after re-open");
    let meta_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM schema_meta WHERE key = 'forward_compat_min_version'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(meta_count, 1);
    let dismissals: i64 = conn
        .query_row("SELECT COUNT(*) FROM dismissals", [], |r| r.get(0))
        .unwrap();
    assert_eq!(dismissals, 1, "existing dismissal preserved across re-open");
}

#[test]
fn state_transitions_fk_cascades_on_dismissal_delete() {
    // AC 146: ON DELETE CASCADE from dismissals(finding_identity_hash)
    // wipes the audit log when a candidate row is deleted.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("for cascade", &["m"]);
    let id = store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    let hash_hex = finding_identity_hash(&f).to_hex();

    // Hand-insert an audit row (Stage 1 does not yet expose a write API
    // for state_transitions, but FK semantics are testable directly).
    let conn = Connection::open(store.path()).unwrap();
    conn.pragma_update(None, "foreign_keys", "ON").unwrap();
    conn.execute(
        "INSERT INTO state_transitions
            (finding_identity_hash, from_state, to_state, trigger, ts,
             by_review_session_id, recurrence_at_transition)
         VALUES (?1, 'candidate', 'local_only', 'auto_recurrence', ?2, ?3, 3)",
        rusqlite::params![hash_hex, 1_700_000_000_000i64, "S-cascade-test"],
    )
    .unwrap();
    let pre: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM state_transitions WHERE finding_identity_hash = ?1",
            [&hash_hex],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(pre, 1);

    // Delete the dismissal via the trait (cascades through FK).
    assert!(store.delete(id).unwrap());
    let post: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM state_transitions WHERE finding_identity_hash = ?1",
            [&hash_hex],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(post, 0, "FK CASCADE must drop the audit log");
}

#[test]
fn forward_compat_rejects_future_schema_version() {
    // AC 174: a SQLite whose schema_version > CURRENT_VERSION is rejected
    // with SchemaTooNew. The store refuses to open even if the rest of
    // the file is well-formed.
    let td = init_repo();
    // First, normal open — bring it up to v2.
    drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    let db_path = td.path().join(".quorum").join("dismissals.sqlite");
    // Now hand-bump schema_version to 3.
    {
        let conn = Connection::open(&db_path).unwrap();
        conn.execute("UPDATE schema_version SET version = 3", [])
            .unwrap();
    }
    let err = match LocalSqliteMemoryStore::new(td.path()) {
        Ok(_) => panic!("expected SchemaTooNew error"),
        Err(e) => e,
    };
    match err {
        MemoryError::SchemaTooNew {
            schema_version,
            forward_compat_min,
        } => {
            assert_eq!(schema_version, 3);
            assert_eq!(forward_compat_min, 2);
        }
        other => panic!("expected SchemaTooNew, got {other:?}"),
    }
}

#[test]
fn forward_compat_rejects_future_min_version_marker() {
    // AC 174 — second arm: schema_version is OK (==2) but
    // schema_meta.forward_compat_min_version is > CURRENT_VERSION.
    // Simulates a future-binary upgrade-then-downgrade scenario where
    // the schema integers don't change but the floor does.
    let td = init_repo();
    drop(LocalSqliteMemoryStore::new(td.path()).unwrap());
    let db_path = td.path().join(".quorum").join("dismissals.sqlite");
    {
        let conn = Connection::open(&db_path).unwrap();
        conn.execute(
            "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('forward_compat_min_version', '3')",
            [],
        )
        .unwrap();
    }
    let err = match LocalSqliteMemoryStore::new(td.path()) {
        Ok(_) => panic!("expected SchemaTooNew error"),
        Err(e) => e,
    };
    match err {
        MemoryError::SchemaTooNew {
            schema_version,
            forward_compat_min,
        } => {
            assert_eq!(schema_version, 2);
            assert_eq!(forward_compat_min, 3);
        }
        other => panic!("expected SchemaTooNew, got {other:?}"),
    }
}

#[test]
fn conventions_text_byte_count_check_roundtrip() {
    // AC 151 — conventions.convention_text CHECK enforces 1..=4096 BYTES
    // (cast to BLOB), not codepoints. Stage 1 has no public write
    // surface for `conventions`, so insertions go through raw SQL.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    // We need a real dismissal row first (PK FK).
    let f = sample_finding("for-check-roundtrip", &["m"]);
    store
        .dismiss(
            &f,
            "h",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    let hash_hex = finding_identity_hash(&f).to_hex();
    let conn = Connection::open(store.path()).unwrap();
    conn.pragma_update(None, "foreign_keys", "ON").unwrap();

    let insert = |hash: &str, text: &str| -> rusqlite::Result<usize> {
        conn.execute(
            "INSERT INTO conventions
                (finding_identity_hash, convention_text, promoted_at, conventions_md_block_id)
             VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![hash, text, 1_700_000_000_000i64, "abcdef012345"],
        )
    };

    // 4096 bytes — passes.
    let ok_4096 = "a".repeat(4096);
    insert(&hash_hex, &ok_4096).expect("4096-byte text must pass");
    // Re-using the same PK requires deletion first.
    conn.execute(
        "DELETE FROM conventions WHERE finding_identity_hash = ?1",
        [&hash_hex],
    )
    .unwrap();

    // 4097 bytes — fails on CHECK.
    let too_big = "a".repeat(4097);
    assert!(
        insert(&hash_hex, &too_big).is_err(),
        "4097-byte text must fail byte-count CHECK"
    );

    // 1 byte — passes.
    insert(&hash_hex, "x").expect("1-byte text must pass");
    conn.execute(
        "DELETE FROM conventions WHERE finding_identity_hash = ?1",
        [&hash_hex],
    )
    .unwrap();

    // 0 bytes — fails (CHECK floor is 1).
    assert!(
        insert(&hash_hex, "").is_err(),
        "empty text must fail byte-count CHECK"
    );

    // Multi-byte UTF-8: the CHECK measures BYTES, not codepoints. Each
    // emoji is 4 bytes in UTF-8, so 1025 emojis = 4100 bytes > 4096
    // even though codepoint count is well under 4096.
    let mut emoji_overflow = String::with_capacity(4100);
    for _ in 0..1025 {
        emoji_overflow.push('\u{1F600}'); // 😀 — 4 UTF-8 bytes
    }
    assert_eq!(emoji_overflow.len(), 4100);
    assert!(
        insert(&hash_hex, &emoji_overflow).is_err(),
        "multi-byte text >4096 bytes must fail; CHECK is byte-count, not codepoint-count"
    );

    // 1024 emojis = 4096 bytes — passes.
    let mut emoji_ok = String::with_capacity(4096);
    for _ in 0..1024 {
        emoji_ok.push('\u{1F600}');
    }
    assert_eq!(emoji_ok.len(), 4096);
    insert(&hash_hex, &emoji_ok).expect("exactly-4096-byte UTF-8 text must pass");
}

#[test]
fn no_secret_material_persisted() {
    // AC 124: dump the DB and confirm no cookie / password / session id /
    // env var values leak. The dismissals row carries only metadata.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let f = sample_finding("Normal finding", &["claude-sonnet", "gpt-4o", "gemini-pro"]);
    store
        .dismiss(
            &f,
            "head-sha-abc",
            "main",
            DismissalReason::FalsePositive,
            Some("safe note about a code pattern".into()),
            Some(time::Duration::days(365)),
        )
        .unwrap();
    drop(store);
    let bytes = std::fs::read(td.path().join(".quorum").join("dismissals.sqlite")).unwrap();
    let dump = String::from_utf8_lossy(&bytes);
    for forbidden in [
        "QUORUM_LIPPA_SESSION",
        "QUORUM_LIPPA_PASSWORD",
        "session=",
        "@lippa", // common email-domain prefix; insufficient on its own but a defense-in-depth grep
        "Cookie:",
    ] {
        assert!(
            !dump.contains(forbidden),
            "dismissals.sqlite must not leak {forbidden}"
        );
    }
}

// ---------------------------------------------------------------------------
// Phase 1C Stage 3 — read-only query coverage.
//
// `list_by_state`, `find_by_short_hash`, `load_transitions` are the read
// surface used by `quorum convention list / show / history`. The CLI
// surface itself is tested in `convention_read.rs`; here we just confirm
// the storage-layer contract.

fn dismiss_with_state(
    store: &LocalSqliteMemoryStore,
    title: &str,
    models: &[&str],
    state: PromotionState,
) -> FindingIdentityHash {
    let f = sample_finding(title, models);
    let h = finding_identity_hash(&f);
    store
        .dismiss(
            &f,
            "head-sha",
            "main",
            DismissalReason::FalsePositive,
            None,
            Some(time::Duration::days(365)),
        )
        .unwrap();
    if state != PromotionState::Candidate {
        let conn = Connection::open(store.path()).unwrap();
        conn.execute(
            "UPDATE dismissals SET promotion_state = ?1 WHERE finding_identity_hash = ?2",
            rusqlite::params![state.as_db_str(), h.to_hex()],
        )
        .unwrap();
    }
    h
}

#[test]
fn list_by_state_filters_and_sorts() {
    // AC 162 storage-layer contract — sort = recurrence_count DESC,
    // last_seen_at DESC; `None` returns all states.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let _h_a = dismiss_with_state(&store, "alpha", &["m"], PromotionState::Candidate);
    let h_b = dismiss_with_state(&store, "bravo", &["m"], PromotionState::LocalOnly);
    let _h_c = dismiss_with_state(
        &store,
        "charlie",
        &["m"],
        PromotionState::PromotedConvention,
    );
    // Bump bravo's recurrence so it sorts first within local_only.
    {
        let conn = Connection::open(store.path()).unwrap();
        conn.execute(
            "UPDATE dismissals SET recurrence_count = 7 WHERE finding_identity_hash = ?1",
            [h_b.to_hex()],
        )
        .unwrap();
    }

    let all = store.list_by_state(None).unwrap();
    assert_eq!(all.len(), 3, "None returns every row");
    // Highest recurrence_count first.
    assert_eq!(all[0].title_snapshot, "bravo");

    let local = store
        .list_by_state(Some(PromotionState::LocalOnly))
        .unwrap();
    assert_eq!(local.len(), 1);
    assert_eq!(local[0].title_snapshot, "bravo");

    let cand = store
        .list_by_state(Some(PromotionState::Candidate))
        .unwrap();
    assert_eq!(cand.len(), 1);
    assert_eq!(cand[0].title_snapshot, "alpha");

    let prom = store
        .list_by_state(Some(PromotionState::PromotedConvention))
        .unwrap();
    assert_eq!(prom.len(), 1);
    assert_eq!(prom[0].title_snapshot, "charlie");
}

#[test]
fn find_by_short_hash_exact_ambiguous_notfound_and_full64() {
    // AC 163 storage-layer contract — exact, ambiguous, not-found,
    // full-64-hex always exact.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    // Two rows whose hashes collide on the first 8 hex chars but diverge
    // beyond. We can't pick those organically — patch the hash column
    // directly to a known prefix pair.
    let h1 = dismiss_with_state(&store, "row-1", &["m"], PromotionState::Candidate);
    let h2 = dismiss_with_state(&store, "row-2", &["m"], PromotionState::Candidate);
    let prefix = "deadbeef";
    let full1 = format!("{prefix}{}", &h1.to_hex()[8..]);
    let full2 = format!("{prefix}{}", &h2.to_hex()[8..]);
    {
        let conn = Connection::open(store.path()).unwrap();
        conn.execute(
            "UPDATE dismissals SET finding_identity_hash = ?1 WHERE title_snapshot = 'row-1'",
            [&full1],
        )
        .unwrap();
        conn.execute(
            "UPDATE dismissals SET finding_identity_hash = ?1 WHERE title_snapshot = 'row-2'",
            [&full2],
        )
        .unwrap();
    }

    let res = store.find_by_short_hash(prefix).unwrap();
    assert!(
        matches!(res, ShortHashResolution::Ambiguous(ref v) if v.len() == 2),
        "two rows sharing 8-hex prefix → Ambiguous"
    );

    // Lengthen the prefix into row-1 only.
    let exact_prefix = &full1[..16];
    let res = store.find_by_short_hash(exact_prefix).unwrap();
    assert!(matches!(res, ShortHashResolution::Exact(ref d) if d.title_snapshot == "row-1"));

    // Full 64-hex always Exact.
    let res = store.find_by_short_hash(&full1).unwrap();
    assert!(matches!(res, ShortHashResolution::Exact(_)));

    // Not-found.
    let res = store.find_by_short_hash("00000000").unwrap();
    assert!(matches!(res, ShortHashResolution::NotFound));
}

#[test]
fn find_by_short_hash_rejects_short_and_nonhex() {
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let err = store.find_by_short_hash("abcd").unwrap_err();
    assert!(matches!(err, MemoryError::Backend(_)));
    let err = store.find_by_short_hash("nothexpfx").unwrap_err();
    assert!(matches!(err, MemoryError::Backend(_)));
}

#[test]
fn load_transitions_for_v2_row_returns_audit_log_oldest_first() {
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let h = dismiss_with_state(&store, "audit-row", &["m"], PromotionState::Candidate);
    // Hand-insert two state_transitions rows for this hash with deliberate
    // timestamp spread (newer second).
    {
        let conn = Connection::open(store.path()).unwrap();
        conn.execute(
            "INSERT INTO state_transitions
                (finding_identity_hash, from_state, to_state, trigger, ts,
                 by_review_session_id, recurrence_at_transition)
             VALUES (?1, 'candidate', 'local_only', 'auto_recurrence', 1000, 'sess-1', 3)",
            [h.to_hex()],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO state_transitions
                (finding_identity_hash, from_state, to_state, trigger, ts,
                 by_review_session_id, recurrence_at_transition)
             VALUES (?1, 'local_only', 'promoted_convention', 'explicit_promote', 5000, NULL, NULL)",
            [h.to_hex()],
        )
        .unwrap();
    }

    let rows = store.load_transitions(&h).unwrap();
    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].ts_ms, 1000, "oldest-first");
    assert_eq!(rows[0].trigger, TransitionTrigger::AutoRecurrence);
    assert_eq!(rows[0].by_review_session_id.as_deref(), Some("sess-1"));
    assert_eq!(rows[0].recurrence_at_transition, Some(3));
    assert_eq!(rows[1].ts_ms, 5000);
    assert_eq!(rows[1].trigger, TransitionTrigger::ExplicitPromote);
    assert!(rows[1].by_review_session_id.is_none());
    assert!(rows[1].recurrence_at_transition.is_none());
}

#[test]
fn load_transitions_for_pre_v2_row_returns_empty() {
    // Spec §4.1: no backfill of state_transitions for pre-v2 rows. A row
    // with no audit-log entries returns an empty vec — same code path as
    // a pre-v2 dismissal would hit.
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let h = dismiss_with_state(&store, "no-audit", &["m"], PromotionState::Candidate);
    let rows = store.load_transitions(&h).unwrap();
    assert!(rows.is_empty());
}

#[test]
fn load_transitions_for_unknown_hash_returns_empty() {
    let td = init_repo();
    let store = LocalSqliteMemoryStore::new(td.path()).unwrap();
    let bogus = FindingIdentityHash([0u8; 32]);
    let rows = store.load_transitions(&bogus).unwrap();
    assert!(rows.is_empty());
}