doctrine 0.25.1

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `comparison::resolve` — tier-1 row-validity resolution (SL-213 design §2,
//! rules R1–R6). Pure leaf: depends only on the `wire` model plus std `BTree`
//! collections. No clock, disk, rng, or git.
//!
//! Given the parsed sessions (any merge order) plus an entity status map, every
//! judgement row is tagged with exactly one [`ResolutionStatus`] under the
//! first-matching-rule discipline. Supersession is a single, order-free pass
//! (design R2: `supersedes` is a durable act, not testimony) — cycles among
//! supersession edges deactivate their participants (`Malformed`) and surface a
//! [`MalformedSupersession`] finding rather than looping to a fixpoint.
//!
//! PHASE-06 adds [`RowState`] — the join of this tier's [`ResolutionStatus`]
//! with tier-2's `compile::CompilationStatus` into the single `compare list`/
//! `explain` display token (design §1 D13). That one type's sole purpose pulls
//! in `compile`'s result type; every actual resolution rule above stays pure
//! over `wire` alone.

use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};

use super::compile::{CompilationStatus, QuarantineReason};
use super::{ComparisonSession, DOMAIN_PRIORITY, Judgement, RaterKind, RowForm};

/// The tier-1 validity verdict for one judgement row (design §2). Deliberately
/// distinct from compilation status (web review corr. 2): quarantine is a later
/// tier layered over an otherwise-active row. `Malformed` is the R2 extension —
/// a supersession-cycle participant, deactivated; the cycle detail rides a
/// separate [`MalformedSupersession`] finding, never the status variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ResolutionStatus {
    Active,
    Superseded { by: String },
    Tombstoned,
    InertLens,
    InertDomain,
    InertLifecycle,
    Malformed,
}

/// The design §1/D13 join of a row's [`ResolutionStatus`] with its (Active-only)
/// [`CompilationStatus`] verdict into ONE display token — PHASE-06's shared
/// consumer seam for `compare list`'s status column and `explain`'s citations.
/// Lives here (the phase sheet's A1 decision): `resolve` and `compile` are
/// sibling leaf tiers with no directional dependency between them (`compile`
/// takes plain `&[&Judgement]`, agnostic of how a caller resolved them), so a
/// `resolve → compile` type reference to compose their two outputs crosses no
/// ADR-001 layer boundary — it only names a sibling's result type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RowState {
    pub resolution: ResolutionStatus,
    /// `None` unless `resolution` is `Active` (design §1).
    pub compilation: Option<CompilationStatus>,
}

impl RowState {
    pub(crate) fn new(
        resolution: ResolutionStatus,
        compilation: Option<CompilationStatus>,
    ) -> Self {
        Self {
            resolution,
            compilation,
        }
    }

    /// The single display token (design §4 S2). The design's nine-token
    /// enumeration predates PHASE-02's `Malformed` variant (a supersession-
    /// cycle participant — R2's `MalformedSupersession` finding carries the
    /// cycle detail); this join appends a tenth, `malformed`, following the
    /// same lowercase-token convention rather than leaving it undisplayable.
    pub(crate) fn display_token(&self) -> String {
        match &self.resolution {
            ResolutionStatus::Superseded { by } => format!("superseded→{by}"),
            ResolutionStatus::Tombstoned => "tombstoned".to_string(),
            ResolutionStatus::InertLens => "inert(lens)".to_string(),
            ResolutionStatus::InertDomain => "inert(domain)".to_string(),
            ResolutionStatus::InertLifecycle => "inert(lifecycle)".to_string(),
            ResolutionStatus::Malformed => "malformed".to_string(),
            ResolutionStatus::Active => match &self.compilation {
                Some(CompilationStatus::NoConstraint) => "no-constraint".to_string(),
                Some(CompilationStatus::Quarantined(QuarantineReason::PreferenceCycle {
                    ..
                })) => "quarantined(cycle)".to_string(),
                Some(CompilationStatus::Quarantined(QuarantineReason::AnchorConflict {
                    ..
                })) => "quarantined(anchors)".to_string(),
                Some(CompilationStatus::Constraining) | None => "active".to_string(),
            },
        }
    }
}

/// A supersession cycle (R2): the participating row uids in deterministic
/// order. Emitted as finding data, kept out of [`ResolutionStatus`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct MalformedSupersession {
    pub cycle: Vec<String>,
}

/// A live supersession edge whose target uid is not present in the loaded
/// corpus (R2 "T unknown uid" — the edge is ignored, the dangling reference is
/// reported). Uid-bearing so a surface can direct the fix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct UnknownSupersedesTarget {
    pub row: String,
    pub target: String,
}

/// Minimal entity lifecycle for R6 — the only distinctions tier-1 acts on.
/// Populated in a later phase; an empty [`StatusMap`] makes R6 a no-op.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum EntityLifecycle {
    /// done / rejected — inert for elicitation only; the row stays `Active` for
    /// inference (design R6).
    Terminal,
    /// The entity was replaced; its rows go `InertLifecycle`, and `by` carries
    /// the successor id for the later reprobe hint (no silent transfer).
    Superseded { by: String },
}

/// Entity id → its lifecycle. Defined here, populated by a later phase.
pub(crate) type StatusMap = BTreeMap<String, EntityLifecycle>;

/// The tier-1 output: every retained row tagged with its status in display
/// order `(date, session_uid, seq)`, plus the two structured finding streams.
/// Rows borrow the source judgements (the downstream `compile` consumes
/// `&[&Judgement]`), so no clone of the un-`Clone` wire model is needed.
#[derive(Debug, PartialEq)]
pub(crate) struct Resolution<'a> {
    pub rows: Vec<(&'a Judgement, ResolutionStatus)>,
    pub unknown_supersedes: Vec<UnknownSupersedesTarget>,
    pub malformed: Vec<MalformedSupersession>,
}

/// One retained row plus the session it is attributed to (the min-uid session
/// on a cherry-picked duplicate).
#[derive(Debug)]
struct RowMeta<'a> {
    judgement: &'a Judgement,
    session_uid: &'a str,
}

/// Resolve parsed sessions to tier-1 statuses (design §2). Deterministic across
/// any merge order of the session slice. `Err` only on a corruption guard: the
/// same uid carrying differing content across two files.
pub(crate) fn resolve<'a>(
    sessions: &'a [ComparisonSession],
    statuses: &StatusMap,
) -> anyhow::Result<Resolution<'a>> {
    // Order-free by construction: sort the sessions by uid before any work, so
    // duplicate collapse and every tiebreak are independent of input order.
    let mut ordered: Vec<&'a ComparisonSession> = sessions.iter().collect();
    ordered.sort_by(|a, b| a.session.uid.cmp(&b.session.uid));

    let rows = collect_rows(&ordered)?;
    let tombstoned = tombstoned_targets(&ordered);
    let (on_cycle, malformed) = supersession_cycles(&rows, &tombstoned);
    let (superseded_by, unknown_supersedes) = supersession_effects(&rows, &tombstoned, &on_cycle);
    let superseded_r3 = implicit_revisions(&rows, &tombstoned);

    let mut out: Vec<(&'a Judgement, &'a str, ResolutionStatus)> = Vec::new();
    for (&uid, meta) in &rows {
        let j = meta.judgement;
        // First matching rule wins (R1 → R6).
        let status = if tombstoned.contains(&uid) {
            ResolutionStatus::Tombstoned
        } else if on_cycle.contains(&uid) {
            ResolutionStatus::Malformed
        } else if let Some(&by) = superseded_by.get(&uid) {
            ResolutionStatus::Superseded { by: by.to_string() }
        } else if let Some(&by) = superseded_r3.get(&uid) {
            ResolutionStatus::Superseded { by: by.to_string() }
        } else if j.domain == DOMAIN_PRIORITY {
            // R4 gates ONLY the priority domain (SL-219 R4): estimate-domain
            // rows resolve Active like value rows.
            ResolutionStatus::InertDomain
        } else if j.lens.is_some() {
            ResolutionStatus::InertLens
        } else if entity_superseded(j, statuses) {
            ResolutionStatus::InertLifecycle
        } else {
            ResolutionStatus::Active
        };
        out.push((j, meta.session_uid, status));
    }

    // SL-220 §1: `ordering_date()` (`date`, else `observed_at`) keeps the
    // tier-1 key total over migrated rows — deterministic mixed ordering.
    out.sort_by(|a, b| {
        a.0.ordering_date()
            .cmp(b.0.ordering_date())
            .then_with(|| a.1.cmp(b.1))
            .then_with(|| a.0.seq.cmp(&b.0.seq))
    });

    let ordered_rows = out.into_iter().map(|(j, _sid, st)| (j, st)).collect();
    Ok(Resolution {
        rows: ordered_rows,
        unknown_supersedes,
        malformed,
    })
}

/// Collect every judgement keyed by uid, collapsing byte-identical duplicates
/// (cherry-picks) and rejecting the same uid with differing content. Iterating
/// the uid-sorted sessions means the first (min-uid) session wins attribution.
fn collect_rows<'a>(
    ordered: &[&'a ComparisonSession],
) -> anyhow::Result<BTreeMap<&'a str, RowMeta<'a>>> {
    let mut by_uid: BTreeMap<&'a str, RowMeta<'a>> = BTreeMap::new();
    for sess in ordered {
        for j in &sess.judgements {
            match by_uid.entry(j.uid.as_str()) {
                Entry::Occupied(existing) => {
                    if existing.get().judgement != j {
                        anyhow::bail!(
                            "comparison row uid `{}` appears with differing content across \
                             session files — resolve the conflict at source",
                            j.uid
                        );
                    }
                }
                Entry::Vacant(slot) => {
                    slot.insert(RowMeta {
                        judgement: j,
                        session_uid: sess.session.uid.as_str(),
                    });
                }
            }
        }
    }
    Ok(by_uid)
}

/// Every uid targeted by a tombstone (R1). A target that names no loaded row is
/// simply inert.
fn tombstoned_targets<'a>(ordered: &[&'a ComparisonSession]) -> BTreeSet<&'a str> {
    let mut out = BTreeSet::new();
    for sess in ordered {
        for t in &sess.tombstones {
            out.insert(t.target.as_str());
        }
    }
    out
}

/// Detect supersession cycles (R2). The supersession relation is a functional
/// graph — each row names at most one target — so a trivial coloured walk over
/// the live edges (non-tombstoned holder, non-tombstoned known target) finds
/// every participant; no graph machinery imported. Returns the participant set
/// (each is `Malformed`) plus one finding per distinct cycle, uids sorted.
fn supersession_cycles<'a>(
    rows: &BTreeMap<&'a str, RowMeta<'a>>,
    tombstoned: &BTreeSet<&'a str>,
) -> (BTreeSet<&'a str>, Vec<MalformedSupersession>) {
    let mut edge: BTreeMap<&'a str, &'a str> = BTreeMap::new();
    for (&uid, meta) in rows {
        if tombstoned.contains(&uid) {
            continue; // holder tombstoned: edge disarmed
        }
        if let Some(target) = meta.judgement.supersedes.as_deref()
            && !tombstoned.contains(&target)
            && rows.contains_key(target)
        {
            edge.insert(uid, target);
        }
    }

    // Coloured walk: 0 unvisited, 1 on the current chain, 2 settled.
    let mut state: BTreeMap<&'a str, u8> = BTreeMap::new();
    let mut on_cycle: BTreeSet<&'a str> = BTreeSet::new();
    for &start in edge.keys() {
        if state.get(&start).copied().unwrap_or(0) != 0 {
            continue;
        }
        let mut chain: Vec<&'a str> = Vec::new();
        let mut cur = start;
        loop {
            match state.get(&cur).copied().unwrap_or(0) {
                0 => {
                    state.insert(cur, 1);
                    chain.push(cur);
                    match edge.get(&cur) {
                        Some(&next) => cur = next,
                        None => break,
                    }
                }
                1 => {
                    // `cur` is on the current chain: walk the loop back to it.
                    let mut c = cur;
                    loop {
                        on_cycle.insert(c);
                        match edge.get(&c) {
                            Some(&n) if n != cur => c = n,
                            _ => break,
                        }
                    }
                    break;
                }
                _ => break, // settled: any cycle already recorded
            }
        }
        for n in chain {
            state.insert(n, 2);
        }
    }

    let mut findings: Vec<MalformedSupersession> = Vec::new();
    let mut seen: BTreeSet<&'a str> = BTreeSet::new();
    for &node in &on_cycle {
        if seen.contains(&node) {
            continue;
        }
        let mut members: BTreeSet<String> = BTreeSet::new();
        let mut c = node;
        loop {
            if !seen.insert(c) {
                break;
            }
            members.insert(c.to_string());
            match edge.get(&c) {
                Some(&next) if on_cycle.contains(&next) => c = next,
                _ => break,
            }
        }
        findings.push(MalformedSupersession {
            cycle: members.into_iter().collect(),
        });
    }

    (on_cycle, findings)
}

/// Apply R2's durable-replacement effect and collect dangling-target warnings.
/// A row T is `Superseded { by: X }` iff some non-tombstoned, non-cycle row X
/// names it — X need not itself be active (a superseded holder's act stands).
/// Iterating the uid-sorted rows makes the min-uid holder win on contention.
fn supersession_effects<'a>(
    rows: &BTreeMap<&'a str, RowMeta<'a>>,
    tombstoned: &BTreeSet<&'a str>,
    on_cycle: &BTreeSet<&'a str>,
) -> (BTreeMap<&'a str, &'a str>, Vec<UnknownSupersedesTarget>) {
    let mut superseded_by: BTreeMap<&'a str, &'a str> = BTreeMap::new();
    let mut unknown: Vec<UnknownSupersedesTarget> = Vec::new();
    for (&uid, meta) in rows {
        if tombstoned.contains(&uid) {
            continue; // holder tombstoned: whole row withdrawn, act included
        }
        let Some(target) = meta.judgement.supersedes.as_deref() else {
            continue;
        };
        if !rows.contains_key(target) {
            unknown.push(UnknownSupersedesTarget {
                row: uid.to_string(),
                target: target.to_string(),
            });
            continue;
        }
        if on_cycle.contains(&uid) {
            continue; // holder is a cycle participant: Malformed, confers nothing
        }
        superseded_by.entry(target).or_insert(uid);
    }
    (superseded_by, unknown)
}

/// R3 implicit revision — within a single session file only, the highest-`seq`
/// row of a shared identity key wins; the losers are `Superseded { by: winner }`.
/// Cross-session same-key rows land in distinct groups (keyed by session uid)
/// and so stay concurrent. Tombstoned rows are withdrawn from the contest.
fn implicit_revisions<'a>(
    rows: &BTreeMap<&'a str, RowMeta<'a>>,
    tombstoned: &BTreeSet<&'a str>,
) -> BTreeMap<&'a str, &'a str> {
    let mut groups: BTreeMap<IdentityKey, Vec<(&'a str, u32)>> = BTreeMap::new();
    for (&uid, meta) in rows {
        if tombstoned.contains(&uid) {
            continue;
        }
        let key = identity_key(meta.session_uid, meta.judgement);
        groups
            .entry(key)
            .or_default()
            .push((uid, meta.judgement.seq));
    }

    let mut superseded: BTreeMap<&'a str, &'a str> = BTreeMap::new();
    for members in groups.values() {
        if members.len() < 2 {
            continue;
        }
        let Some(&(winner, _)) = members
            .iter()
            .max_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(b.0)))
        else {
            continue;
        };
        for &(uid, _) in members {
            if uid != winner {
                superseded.insert(uid, winner);
            }
        }
    }
    superseded
}

/// The R3 identity key. The pair is unordered — asking `a` vs `b` and later `b`
/// vs `a` is the same question — so the two entity refs are stored sorted.
/// Anchor rows (SL-220 §1) key degenerately as `(pair_lo = a, pair_hi = None)`
/// — `Option<String>: Ord` keeps the `BTreeMap` key valid, and `None` can never
/// collide with a legal id (a sentinel string could).
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct IdentityKey {
    session: String,
    pair_lo: String,
    pair_hi: Option<String>,
    domain: String,
    frame: String,
    form: &'static str,
    lens: Option<String>,
    rater: &'static str,
}

fn identity_key(session_uid: &str, j: &Judgement) -> IdentityKey {
    let (pair_lo, pair_hi) = match j.b.as_deref() {
        Some(b) if j.a.as_str() <= b => (j.a.clone(), Some(b.to_string())),
        Some(b) => (b.to_string(), Some(j.a.clone())),
        None => (j.a.clone(), None),
    };
    IdentityKey {
        session: session_uid.to_string(),
        pair_lo,
        pair_hi,
        domain: j.domain.clone(),
        frame: j.frame.clone(),
        form: form_key(&j.form),
        lens: j.lens.clone(),
        rater: rater_key(&j.rater),
    }
}

/// Stable ordering tokens for the closed wire enums (they carry no `Ord`).
/// `form` in the key means anchor rows never collide with order/ratio rows on
/// the same subject (SL-220 §1).
fn form_key(form: &RowForm) -> &'static str {
    match form {
        RowForm::Order => "order",
        RowForm::Ratio => "ratio",
        RowForm::Anchor => "anchor",
    }
}

pub(crate) fn rater_key(rater: &RaterKind) -> &'static str {
    match rater {
        RaterKind::Human => "human",
        RaterKind::Agent => "agent",
        RaterKind::Migrated => "migrated",
    }
}

/// R6: a row is `InertLifecycle` when ANY PRESENT subject is superseded —
/// for anchor rows the single subject `a`; `b` is consulted only when present
/// (SL-220 §1). Terminal entities keep their rows active (inert for
/// elicitation only).
fn entity_superseded(j: &Judgement, statuses: &StatusMap) -> bool {
    let superseded =
        |id: &str| matches!(statuses.get(id), Some(EntityLifecycle::Superseded { .. }));
    superseded(&j.a) || j.b.as_deref().is_some_and(superseded)
}

#[cfg(test)]
mod tests {
    use super::{
        EntityLifecycle, MalformedSupersession, Resolution, ResolutionStatus, StatusMap, resolve,
    };
    use crate::comparison::{
        COMPARISON_SCHEMA, COMPARISON_VERSION, ComparisonSession, DOMAIN_ESTIMATE, DOMAIN_PRIORITY,
        DOMAIN_VALUE, FRAME_EQUAL_EFFORT, FRAME_MORE_WORK, FRAME_PREFER_FIRST, FRAME_VALUE_ANCHOR,
        Judgement, RaterKind, Response, RowForm, SessionHeader, Tombstone,
    };

    // ---- fixtures -----------------------------------------------------------

    fn judgement(uid: &str, seq: u32, a: &str, b: &str) -> Judgement {
        Judgement {
            uid: uid.to_string(),
            seq,
            a: a.to_string(),
            b: Some(b.to_string()),
            response: Some(Response::PreferA),
            domain: DOMAIN_VALUE.to_string(),
            frame: FRAME_EQUAL_EFFORT.to_string(),
            form: RowForm::Order,
            magnitude: None,
            supersedes: None,
            lens: None,
            rater: RaterKind::Human,
            by: None,
            note: None,
            date: Some("2026-07-10".to_string()),
            observed_at: None,
            basis: None,
            est_lower: None,
            est_upper: None,
            admission: None,
        }
    }

    /// A live human anchor row (SL-220 §1): single subject, `value-anchor`
    /// frame, magnitude payload.
    fn anchor(uid: &str, seq: u32, a: &str) -> Judgement {
        let mut j = judgement(uid, seq, a, "unused");
        j.b = None;
        j.response = None;
        j.frame = FRAME_VALUE_ANCHOR.to_string();
        j.form = RowForm::Anchor;
        j.magnitude = Some(5.0);
        j
    }

    /// A migrated anchor row (SL-220 §1): `observed_at` in place of `date`.
    fn migrated_anchor(uid: &str, seq: u32, a: &str, observed_at: &str) -> Judgement {
        let mut j = anchor(uid, seq, a);
        j.rater = RaterKind::Migrated;
        j.date = None;
        j.observed_at = Some(observed_at.to_string());
        j
    }

    fn session(
        uid: &str,
        judgements: Vec<Judgement>,
        tombstones: Vec<Tombstone>,
    ) -> ComparisonSession {
        ComparisonSession {
            schema: COMPARISON_SCHEMA.to_string(),
            version: COMPARISON_VERSION,
            session: SessionHeader {
                uid: uid.to_string(),
                date: "2026-07-10".to_string(),
                audience: None,
            },
            judgements,
            tombstones,
        }
    }

    fn tombstone(uid: &str, target: &str) -> Tombstone {
        Tombstone {
            uid: uid.to_string(),
            seq: 0,
            target: target.to_string(),
            date: "2026-07-10".to_string(),
            note: None,
        }
    }

    fn run(sessions: &[ComparisonSession]) -> Resolution<'_> {
        resolve(sessions, &StatusMap::new()).expect("resolve ok")
    }

    fn status_of<'a>(res: &'a Resolution<'_>, uid: &str) -> &'a ResolutionStatus {
        let row = res
            .rows
            .iter()
            .find(|(j, _)| j.uid.as_str() == uid)
            .expect("row present");
        &row.1
    }

    fn superseded_by(uid: &str) -> ResolutionStatus {
        ResolutionStatus::Superseded {
            by: uid.to_string(),
        }
    }

    // ---- R1 -----------------------------------------------------------------

    #[test]
    fn r1_tombstone_evicts_its_target() {
        let s = session(
            "s1",
            vec![judgement("j1", 0, "A", "B")],
            vec![tombstone("t1", "j1")],
        );
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::Tombstoned);
    }

    // ---- R2 state table -----------------------------------------------------

    #[test]
    fn r2_chain_leaves_only_the_head_active() {
        let mut b = judgement("b", 1, "R", "S");
        b.supersedes = Some("a".to_string());
        let mut c = judgement("c", 2, "T", "U");
        c.supersedes = Some("b".to_string());
        let s = session("s1", vec![judgement("a", 0, "P", "Q"), b, c], vec![]);
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "c"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "b"), &superseded_by("c"));
        assert_eq!(status_of(&res, "a"), &superseded_by("b"));
    }

    #[test]
    fn r2_tombstoning_chain_head_revives_middle_but_not_root() {
        // A ← B ← C, then tombstone C: C's edge disarms so B revives, but B's
        // durable edge still suppresses A.
        let mut b = judgement("b", 1, "R", "S");
        b.supersedes = Some("a".to_string());
        let mut c = judgement("c", 2, "T", "U");
        c.supersedes = Some("b".to_string());
        let s = session(
            "s1",
            vec![judgement("a", 0, "P", "Q"), b, c],
            vec![tombstone("t1", "c")],
        );
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "c"), &ResolutionStatus::Tombstoned);
        assert_eq!(status_of(&res, "b"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "a"), &superseded_by("b"));
    }

    #[test]
    fn r2_mutual_supersession_cycle_deactivates_all_participants() {
        let mut a = judgement("a", 0, "P", "Q");
        a.supersedes = Some("b".to_string());
        let mut b = judgement("b", 1, "R", "S");
        b.supersedes = Some("a".to_string());
        let s = session("s1", vec![a, b], vec![]);
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "a"), &ResolutionStatus::Malformed);
        assert_eq!(status_of(&res, "b"), &ResolutionStatus::Malformed);
        assert_eq!(
            res.malformed,
            vec![MalformedSupersession {
                cycle: vec!["a".to_string(), "b".to_string()],
            }]
        );
    }

    #[test]
    fn r2_self_supersession_is_a_degenerate_malformed_cycle() {
        let mut x = judgement("x", 0, "P", "Q");
        x.supersedes = Some("x".to_string());
        let sessions = [session("s1", vec![x], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "x"), &ResolutionStatus::Malformed);
        assert_eq!(res.malformed[0].cycle, vec!["x".to_string()]);
    }

    #[test]
    fn r2_tombstoned_superseder_revives_its_target() {
        let mut x = judgement("x", 1, "R", "S");
        x.supersedes = Some("t".to_string());
        let s = session(
            "s1",
            vec![judgement("t", 0, "P", "Q"), x],
            vec![tombstone("tomb", "x")],
        );
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "x"), &ResolutionStatus::Tombstoned);
        assert_eq!(status_of(&res, "t"), &ResolutionStatus::Active);
    }

    #[test]
    fn r2_superseder_of_a_tombstoned_target_stays_active() {
        let mut x = judgement("x", 1, "R", "S");
        x.supersedes = Some("t".to_string());
        let s = session(
            "s1",
            vec![judgement("t", 0, "P", "Q"), x],
            vec![tombstone("tomb", "t")],
        );
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "t"), &ResolutionStatus::Tombstoned);
        assert_eq!(status_of(&res, "x"), &ResolutionStatus::Active);
    }

    #[test]
    fn r2_unknown_supersedes_target_warns_and_holder_stays_active() {
        let mut x = judgement("x", 0, "P", "Q");
        x.supersedes = Some("ghost".to_string());
        let sessions = [session("s1", vec![x], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "x"), &ResolutionStatus::Active);
        assert_eq!(res.unknown_supersedes.len(), 1);
        assert_eq!(res.unknown_supersedes[0].row, "x");
        assert_eq!(res.unknown_supersedes[0].target, "ghost");
    }

    // ---- R3 identity revision & cross-session concurrency -------------------

    #[test]
    fn r3_within_file_identity_higher_seq_wins_unordered_pair() {
        // Same question re-asked with the pair flipped: one identity key.
        let sessions = [session(
            "s1",
            vec![judgement("p", 0, "X", "Y"), judgement("q", 1, "Y", "X")],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "q"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "p"), &superseded_by("q"));
    }

    #[test]
    fn r3_cross_session_same_key_is_concurrent_both_active() {
        let s1 = session("s1", vec![judgement("p", 0, "X", "Y")], vec![]);
        let s2 = session("s2", vec![judgement("q", 0, "X", "Y")], vec![]);
        let sessions = [s1, s2];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "p"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "q"), &ResolutionStatus::Active);
    }

    // ---- R4 / R5 / R6 -------------------------------------------------------

    #[test]
    fn r4_priority_domain_row_is_inert() {
        let mut j = judgement("j1", 0, "A", "B");
        j.domain = DOMAIN_PRIORITY.to_string();
        j.frame = FRAME_PREFER_FIRST.to_string();
        let sessions = [session("s1", vec![j], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::InertDomain);
    }

    #[test]
    fn r5_lens_tagged_row_is_inert() {
        let mut j = judgement("j1", 0, "A", "B");
        j.lens = Some("user-value".to_string());
        let sessions = [session("s1", vec![j], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::InertLens);
    }

    #[test]
    fn r6_superseded_entity_makes_its_rows_inert() {
        let life = EntityLifecycle::Superseded {
            by: "SL-999".to_string(),
        };
        // The successor id is retained for a later reprobe hint.
        if let EntityLifecycle::Superseded { by } = &life {
            assert_eq!(by, "SL-999");
        }
        let mut statuses = StatusMap::new();
        statuses.insert("SL-100".to_string(), life);
        let s = session("s1", vec![judgement("j1", 0, "SL-100", "SL-200")], vec![]);
        let sessions = [s];
        let res = resolve(&sessions, &statuses).expect("resolve ok");
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::InertLifecycle);
    }

    #[test]
    fn r6_terminal_entity_rows_stay_active() {
        let mut statuses = StatusMap::new();
        statuses.insert("SL-100".to_string(), EntityLifecycle::Terminal);
        let s = session("s1", vec![judgement("j1", 0, "SL-100", "SL-200")], vec![]);
        let sessions = [s];
        let res = resolve(&sessions, &statuses).expect("resolve ok");
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::Active);
    }

    #[test]
    fn r6_empty_status_map_is_a_no_op() {
        let sessions = [session("s1", vec![judgement("j1", 0, "A", "B")], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::Active);
    }

    // ---- SL-219: estimate domain (VT-3) --------------------------------------

    /// `judgement` retargeted to the estimate domain (frame kept consistent
    /// with the closed table, though resolve keys on domain alone).
    fn estimate_judgement(uid: &str, seq: u32, a: &str, b: &str) -> Judgement {
        let mut j = judgement(uid, seq, a, b);
        j.domain = DOMAIN_ESTIMATE.to_string();
        j.frame = FRAME_MORE_WORK.to_string();
        j
    }

    /// SL-219 R4: estimate-domain rows resolve Active — inert-domain gating
    /// stays scoped to `priority` alone.
    #[test]
    fn estimate_domain_row_resolves_active() {
        let sessions = [session(
            "s1",
            vec![estimate_judgement("j1", 0, "A", "B")],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::Active);
    }

    /// SL-219 EX-2: the identity key carries `domain`, so the same unordered
    /// pair holding a value row AND an estimate row — even within one session —
    /// neither collides nor supersedes across domains: both stay Active.
    #[test]
    fn same_pair_value_and_estimate_rows_stay_concurrent() {
        let sessions = [session(
            "s1",
            vec![
                judgement("v", 0, "X", "Y"),
                estimate_judgement("e", 1, "Y", "X"),
            ],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "v"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "e"), &ResolutionStatus::Active);
    }

    /// SL-219 EX-2: R3 within-session revision is scoped per domain — two
    /// estimate rows on one pair revise (higher seq wins) without touching
    /// the value row on the same pair.
    #[test]
    fn r3_revision_scopes_within_the_estimate_domain() {
        let sessions = [session(
            "s1",
            vec![
                judgement("v", 0, "X", "Y"),
                estimate_judgement("e1", 1, "X", "Y"),
                estimate_judgement("e2", 2, "Y", "X"),
            ],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "v"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "e1"), &superseded_by("e2"));
        assert_eq!(status_of(&res, "e2"), &ResolutionStatus::Active);
    }

    // ---- cross-file mechanics ----------------------------------------------

    #[test]
    fn duplicate_uid_identical_content_collapses_to_one_row() {
        let s1 = session("s1", vec![judgement("dup", 0, "A", "B")], vec![]);
        let s2 = session("s2", vec![judgement("dup", 0, "A", "B")], vec![]);
        let sessions = [s1, s2];
        let res = run(&sessions);
        let count = res
            .rows
            .iter()
            .filter(|(j, _)| j.uid.as_str() == "dup")
            .count();
        assert_eq!(count, 1);
    }

    #[test]
    fn same_uid_differing_content_is_a_load_error() {
        let s1 = session("s1", vec![judgement("x", 0, "A", "B")], vec![]);
        let mut conflicting = judgement("x", 0, "A", "B");
        conflicting.response = Some(Response::PreferB);
        let s2 = session("s2", vec![conflicting], vec![]);
        let err = resolve(&[s1, s2], &StatusMap::new()).unwrap_err();
        assert!(err.to_string().contains("differing content"));
        assert!(err.to_string().contains("`x`"));
    }

    // ---- determinism --------------------------------------------------------

    fn det_fixture(name: &str) -> ComparisonSession {
        match name {
            "s1" => {
                let mut b = judgement("b", 0, "R", "S");
                b.supersedes = Some("a".to_string());
                session("s1", vec![b], vec![])
            }
            "s2" => session("s2", vec![judgement("a", 0, "P", "Q")], vec![]),
            _ => {
                let mut c = judgement("c", 0, "T", "U");
                c.supersedes = Some("d".to_string());
                let mut d = judgement("d", 1, "V", "W");
                d.supersedes = Some("c".to_string());
                session("s3", vec![c, d], vec![])
            }
        }
    }

    #[test]
    fn resolution_is_deterministic_across_session_merge_order() {
        let build = |order: [&str; 3]| -> Vec<ComparisonSession> {
            order.iter().map(|&n| det_fixture(n)).collect()
        };
        let p1 = build(["s1", "s2", "s3"]);
        let p2 = build(["s3", "s2", "s1"]);
        let p3 = build(["s2", "s3", "s1"]);
        let r1 = resolve(&p1, &StatusMap::new()).expect("resolve ok");
        let r2 = resolve(&p2, &StatusMap::new()).expect("resolve ok");
        let r3 = resolve(&p3, &StatusMap::new()).expect("resolve ok");
        assert_eq!(r1, r2);
        assert_eq!(r1, r3);
        // Sanity: the fixture exercises a cross-session edge and a cycle.
        assert_eq!(status_of(&r1, "a"), &superseded_by("b"));
        assert_eq!(status_of(&r1, "c"), &ResolutionStatus::Malformed);
    }

    // ---- SL-220 §1: anchor-row resolution semantics (VT-2) --------------------

    /// `ordering_date()` totality: mixed migrated/live rows order
    /// deterministically — `observed_at` slots migrated rows into the same
    /// tier-1 key as live `date` rows, independent of merge order.
    #[test]
    fn ordering_date_orders_mixed_migrated_and_live_rows() {
        // Migrated row observed BEFORE the live rows' dates; a second
        // migrated row shares a date with a live row (session uid tiebreak).
        let s1 = session(
            "s1",
            vec![judgement("live-10", 0, "A", "B")], // date 2026-07-10
            vec![],
        );
        let s2 = session(
            "s2",
            vec![
                migrated_anchor("mig-09", 0, "C", "2026-07-09"),
                migrated_anchor("mig-10", 1, "D", "2026-07-10"),
            ],
            vec![],
        );
        let order_of = |sessions: &[ComparisonSession]| -> Vec<String> {
            resolve(sessions, &StatusMap::new())
                .expect("resolve ok")
                .rows
                .iter()
                .map(|(j, _)| j.uid.clone())
                .collect()
        };
        let forward = order_of(&[s1, s2]);
        // (date, session_uid, seq): 07-09 first; on 07-10 s1 < s2.
        assert_eq!(forward, ["mig-09", "live-10", "mig-10"]);

        let s1 = session("s1", vec![judgement("live-10", 0, "A", "B")], vec![]);
        let s2 = session(
            "s2",
            vec![
                migrated_anchor("mig-09", 0, "C", "2026-07-09"),
                migrated_anchor("mig-10", 1, "D", "2026-07-10"),
            ],
            vec![],
        );
        assert_eq!(order_of(&[s2, s1]), forward, "merge-order independent");
    }

    /// R3 over the degenerate key: same-session same-subject anchor rows by
    /// one rater at one lens group implicitly revise — higher seq wins.
    #[test]
    fn r3_same_subject_anchor_rows_implicitly_revise() {
        let sessions = [session(
            "s1",
            vec![anchor("p", 0, "SL-100"), anchor("q", 1, "SL-100")],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "q"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "p"), &superseded_by("q"));
    }

    /// `form` in the key: an anchor row and an order row on the same subject
    /// never collide — both stay Active (SL-220 §1).
    #[test]
    fn anchor_and_order_rows_on_the_same_subject_stay_concurrent() {
        let sessions = [session(
            "s1",
            vec![
                anchor("anch", 0, "SL-100"),
                judgement("ord", 1, "SL-100", "SL-200"),
            ],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "anch"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "ord"), &ResolutionStatus::Active);
    }

    /// `rater` in the key (`migrated` token): a human anchor and a migrated
    /// anchor on one subject in one session are distinct identities — both
    /// Active, no implicit revision across raters.
    #[test]
    fn human_and_migrated_anchors_on_one_subject_stay_concurrent() {
        let sessions = [session(
            "s1",
            vec![
                anchor("hum", 0, "SL-100"),
                migrated_anchor("mig", 1, "SL-100", "2026-07-16"),
            ],
            vec![],
        )];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "hum"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "mig"), &ResolutionStatus::Active);
    }

    /// Cross-session same-key anchor rows stay concurrent (R3 scopes within
    /// one file; concurrent contradiction is a finding, never latest-wins).
    #[test]
    fn cross_session_same_subject_anchors_are_concurrent() {
        let s1 = session("s1", vec![anchor("p", 0, "SL-100")], vec![]);
        let s2 = session("s2", vec![anchor("q", 0, "SL-100")], vec![]);
        let sessions = [s1, s2];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "p"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "q"), &ResolutionStatus::Active);
    }

    /// Single-subject lifecycle inertness (SL-220 §1): an anchor row is inert
    /// iff its ONE subject is superseded; terminal keeps it active; the
    /// absent `b` is never consulted.
    #[test]
    fn r6_anchor_row_lifecycle_follows_its_single_subject() {
        let mut statuses = StatusMap::new();
        statuses.insert(
            "SL-100".to_string(),
            EntityLifecycle::Superseded {
                by: "SL-999".to_string(),
            },
        );
        statuses.insert("SL-200".to_string(), EntityLifecycle::Terminal);
        let s = session(
            "s1",
            vec![
                anchor("gone", 0, "SL-100"),
                anchor("done", 1, "SL-200"),
                anchor("live", 2, "SL-300"),
            ],
            vec![],
        );
        let sessions = [s];
        let res = resolve(&sessions, &statuses).expect("resolve ok");
        assert_eq!(status_of(&res, "gone"), &ResolutionStatus::InertLifecycle);
        assert_eq!(status_of(&res, "done"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "live"), &ResolutionStatus::Active);
    }

    /// R1/R2 machinery applies to anchor rows unchanged: a tombstone evicts,
    /// an explicit supersession chain leaves only the head active.
    #[test]
    fn anchor_rows_ride_tombstones_and_supersession_chains() {
        let a = anchor("a", 0, "SL-100");
        let mut b = anchor("b", 1, "SL-100");
        b.rater = RaterKind::Agent; // distinct identity: R2 does the work, not R3
        b.supersedes = Some("a".to_string());
        let mut c = migrated_anchor("c", 2, "SL-100", "2026-07-16");
        c.supersedes = Some("b".to_string());
        let d = anchor("d", 3, "SL-200");
        let s = session("s1", vec![a, b, c, d], vec![tombstone("t1", "d")]);
        let sessions = [s];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "c"), &ResolutionStatus::Active);
        assert_eq!(status_of(&res, "b"), &superseded_by("c"));
        assert_eq!(status_of(&res, "a"), &superseded_by("b"));
        assert_eq!(status_of(&res, "d"), &ResolutionStatus::Tombstoned);
    }

    /// R2 cycle detection over anchor rows: mutual supersession deactivates
    /// both participants and surfaces the finding.
    #[test]
    fn anchor_supersession_cycle_is_malformed() {
        let mut p = anchor("p", 0, "SL-100");
        p.supersedes = Some("q".to_string());
        let mut q = anchor("q", 0, "SL-200");
        q.supersedes = Some("p".to_string());
        let sessions = [session("s1", vec![p, q], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "p"), &ResolutionStatus::Malformed);
        assert_eq!(status_of(&res, "q"), &ResolutionStatus::Malformed);
        assert_eq!(
            res.malformed,
            vec![MalformedSupersession {
                cycle: vec!["p".to_string(), "q".to_string()],
            }]
        );
    }

    /// R5 applies to anchor rows: a lens-tagged anchor is InertLens (the
    /// lensed claim partitions arrive at the claims pass, design §2).
    #[test]
    fn lensed_anchor_row_is_inert() {
        let mut j = anchor("j1", 0, "SL-100");
        j.lens = Some("user-value".to_string());
        let sessions = [session("s1", vec![j], vec![])];
        let res = run(&sessions);
        assert_eq!(status_of(&res, "j1"), &ResolutionStatus::InertLens);
    }
}