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
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
// SPDX-License-Identifier: GPL-3.0-only
//! `comparison::project` — tier-3 projection & gauge (SL-213 design §3, rules
//! P1–P15). Pure leaf (ADR-001): depends only on the tier-2 [`ConstraintSet`]
//! plus std `BTree` collections. No clock, disk, rng, or git.
//!
//! Input: a compiled [`ConstraintSet`] (retained, post-quarantine classes,
//! strict class digraph, and per-class anchors) plus a [`ProjectionCfg`] (the
//! two gauge parameters as pure PER-CALL inputs — no config reads in here,
//! SL-219 D8; each domain's call site supplies its own params, the value
//! domain's shipped constants named [`VALUE_PROJECTION_PARAMS`]). Output: a
//! [`Projection`] mapping every evidence-bearing **entity** id to a scalar and
//! its [`ValueProvenance`]; every member of a class takes the class value.
//!
//! ## Method (design §3)
//! Reverse-topological greedy placement (sinks/lowest first, uid-sorted
//! tiebreak). Each unanchored class is a pure function of its already-placed
//! direct successors (the floor) and the min anchor weakly above it (the
//! ceiling), by **budgeted** interpolation `f + (c − f)/(d_up + 1)` (P4).
//! Anchors are exact (P3). Unbounded tails step by `gauge_step` off a synthetic
//! floor/off the floor (P5/P6). A class with neither floor nor ceiling is
//! gauged to `gauge_center` (P7). An anchor-free component is spread by
//! height (P8, component `H`). Ported from `.doctrine/slice/213/projection-prototype.py`,
//! whose scenario battery (S1–S8, Y1–Y7, N1–N4) is the golden suite below —
//! except gauge scope, where the port is per-component (SL-216; the
//! multi-component goldens `s2`/`s8` are re-pinned off the prototype's
//! global-`H` output — see below).
//!
//! ## Gauge scope — per-component, adjudicated
//! Placement runs per weakly-connected component (P1): each component picks
//! its regime by its OWN anchors — no anchor → P8 spread with `H` = component
//! max height; ≥1 anchor → the anchored pipeline over its members. Locality
//! (P12) is universal, both regimes, including regime membership (the
//! corpus's first anchor never moves a disjoint island). The original port
//! followed the prototype's global-`H` / any-anchor-anywhere semantics; that
//! tension was adjudicated for the per-component reading (SL-216, IMP-279,
//! RV-266 F-3 follow-on), the `s2`/`s8` goldens re-pinned to component scale,
//! and SL-213 design §3 amended in place. Accepted consequence: in a mixed
//! corpus an anchor-free island's loser lands below the gauge center
//! (judged-and-lost ranks below unjudged).

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

use super::compile::{ClassId, ConstraintSet, EdgeMap};

/// The provenance of a projected scalar (design D11, `authored > projected >
/// gauge`). Absence from a [`Projection`] is the implicit fourth tier
/// (`default`) — an entity with no row evidence is never placed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ValueProvenance {
    /// P3: the class carries an authored anchor; the value is exact.
    Authored,
    /// P4/P5/P6: interpolated or gauge-stepped between order neighbours.
    Projected,
    /// P7/P8: placed by the gauge convention, not by evidence.
    Gauge,
}

/// The two gauge parameters, passed as pure per-call inputs (SL-219 D8:
/// `project()` never reads config — the calling shell threads each domain's
/// own pair). Value domain: [`VALUE_PROJECTION_PARAMS`] (step overridable via
/// `[priority.gauge] step`). Estimate domain: `EST_GAUGE_STEP` + `gauge_center
/// = ctx.absent`, the corpus's bare-item cost anchor (D7/D8).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ProjectionCfg {
    /// The additive gauge step for unbounded tails/heads (`0.25` = a quarter
    /// of the value domain's `gauge_center`, design P5).
    pub gauge_step: f64,
    /// The gauge CENTER: the value for a class with no order path to any
    /// anchor (P7) and the center/scale of the anchor-free component spread
    /// (P8). The value domain centers on `DEFAULT_VALUE`; the estimate domain
    /// centers its render-only gauge on the corpus's own bare anchor.
    pub gauge_center: f64,
}

/// The VALUE domain's shipped projection parameters (SL-219 D8, STD-001): the
/// prototype's `STEP = 0.25` / `DEFAULT = 1.0`, mirrored by the priority-layer
/// `config::GAUGE_STEP` / `graph::DEFAULT_VALUE` (a test cross-pins them —
/// this leaf cannot depend upward on `priority`). The value call site passes
/// this const (its `gauge_step` config-overridable via `[priority.gauge]
/// step`); the byte-identical goldens below are the invariant's proof.
pub(crate) const VALUE_PROJECTION_PARAMS: ProjectionCfg = ProjectionCfg {
    gauge_step: 0.25,
    gauge_center: 1.0,
};

/// Entity id → its projected scalar and provenance. Deterministic ordering
/// (`BTree`); `f64` is never a key.
pub(crate) type Projection = BTreeMap<String, (f64, ValueProvenance)>;

/// Directed adjacency over class ids (winner → losers, or its transpose).
type Adj = BTreeMap<ClassId, BTreeSet<ClassId>>;

/// Project a [`ConstraintSet`] onto per-entity scalars (design §3). Pure and
/// deterministic over its inputs.
pub(crate) fn project(cs: &ConstraintSet, cfg: &ProjectionCfg) -> Projection {
    let nodes: BTreeSet<ClassId> = cs.classes.values().cloned().collect();
    let (out, inn) = adjacency(&cs.edges);
    let class_values = place(&nodes, &out, &inn, &cs.anchors, cfg);
    // Fan the class value out to every member entity (P1: every member of a
    // class gets the class value).
    cs.classes
        .iter()
        .filter_map(|(entity, class)| {
            class_values
                .get(class)
                .map(|&(value, prov)| (entity.clone(), (value, prov)))
        })
        .collect()
}

// ---- graph helpers ---------------------------------------------------------

/// Build the forward (winner → losers) and transpose (loser → winners)
/// adjacencies from the retained edge keys. Deliberate small duplication of
/// `compile.rs`'s private `adjacency`/`transpose` (design §1 sanctions local
/// graph helpers over widening a sibling module's surface).
fn adjacency(edges: &EdgeMap) -> (Adj, Adj) {
    let mut out: Adj = BTreeMap::new();
    let mut inn: Adj = BTreeMap::new();
    for (winner, loser) in edges.keys() {
        out.entry(winner.clone()).or_default().insert(loser.clone());
        inn.entry(loser.clone()).or_default().insert(winner.clone());
    }
    (out, inn)
}

/// Reverse-topological order (sinks/lowest first), deterministic by class id
/// (Kahn over out-degree; every node in `nodes`, including edge-free isolates,
/// is emitted). Post-C3 the graph is a DAG (PHASE-03 guarantee), so this
/// always drains.
fn topo_order(nodes: &BTreeSet<ClassId>, out: &Adj, inn: &Adj) -> Vec<ClassId> {
    let mut indeg: BTreeMap<ClassId, usize> = nodes
        .iter()
        .map(|n| (n.clone(), out.get(n).map_or(0, BTreeSet::len)))
        .collect();
    let mut ready: BTreeSet<ClassId> = nodes
        .iter()
        .filter(|n| indeg.get(*n).copied().unwrap_or(0) == 0)
        .cloned()
        .collect();
    let mut order = Vec::with_capacity(nodes.len());
    while let Some(n) = ready.pop_first() {
        if let Some(preds) = inn.get(&n) {
            for p in preds {
                if let Some(d) = indeg.get_mut(p) {
                    *d -= 1;
                    if *d == 0 {
                        ready.insert(p.clone());
                    }
                }
            }
        }
        order.push(n);
    }
    order
}

/// Longest-path height above each node's sinks (`h[v] = 0` at a sink, else
/// `max(h[successor]) + 1`). The P8 gauge spread's `h`.
fn heights(order: &[ClassId], out: &Adj) -> BTreeMap<ClassId, usize> {
    let mut h: BTreeMap<ClassId, usize> = BTreeMap::new();
    for v in order {
        let hv = out.get(v).map_or(0, |succ| {
            succ.iter()
                .map(|s| h.get(s).copied().unwrap_or(0) + 1)
                .max()
                .unwrap_or(0)
        });
        h.insert(v.clone(), hv);
    }
    h
}

/// For each class: `hi` = the min anchor value weakly above (the ceiling `c`,
/// P4), and `dup` = the longest directed path up to that ceiling-defining
/// anchor (ties on value resolved by the LONGER path — most room). Processed
/// sources-first so every predecessor is settled first.
fn longest_up(
    order: &[ClassId],
    inn: &Adj,
    anchors: &BTreeMap<ClassId, f64>,
) -> (BTreeMap<ClassId, f64>, BTreeMap<ClassId, usize>) {
    let mut hi: BTreeMap<ClassId, f64> = BTreeMap::new();
    let mut dup: BTreeMap<ClassId, usize> = BTreeMap::new();
    for v in order.iter().rev() {
        let mut best: Option<(f64, usize)> = None;
        if let Some(preds) = inn.get(v) {
            for p in preds {
                let cand = if let Some(&a) = anchors.get(p) {
                    Some((a, 1usize))
                } else if let (Some(&hp), Some(&dp)) = (hi.get(p), dup.get(p)) {
                    Some((hp, dp + 1))
                } else {
                    None
                };
                if let Some((cv, cd)) = cand {
                    let take = match best {
                        None => true,
                        Some((bv, bd)) => {
                            cv.total_cmp(&bv).is_lt() || (cv.total_cmp(&bv).is_eq() && cd > bd)
                        }
                    };
                    if take {
                        best = Some((cv, cd));
                    }
                }
            }
        }
        if let Some((bv, bd)) = best {
            hi.insert(v.clone(), bv);
            dup.insert(v.clone(), bd);
        }
    }
    (hi, dup)
}

/// Longest directed path from the nearest anchor above down to each class
/// (`d_down`, P6 synthetic-floor depth). Processed sources-first.
fn depth_below_ceiling(
    order: &[ClassId],
    inn: &Adj,
    anchors: &BTreeMap<ClassId, f64>,
) -> BTreeMap<ClassId, usize> {
    let mut depth: BTreeMap<ClassId, usize> = BTreeMap::new();
    for v in order.iter().rev() {
        let mut best: Option<usize> = None;
        if let Some(preds) = inn.get(v) {
            for p in preds {
                let cand = if anchors.contains_key(p) {
                    Some(1)
                } else {
                    depth.get(p).map(|d| d + 1)
                };
                if let Some(c) = cand {
                    best = Some(best.map_or(c, |b: usize| b.max(c)));
                }
            }
        }
        if let Some(b) = best {
            depth.insert(v.clone(), b);
        }
    }
    depth
}

/// The max already-placed value over `v`'s DIRECT successors — the floor `f`
/// (P4). `None` when `v` has no placed descendant.
fn successor_max(values: &BTreeMap<ClassId, f64>, out: &Adj, v: &str) -> Option<f64> {
    out.get(v).and_then(|succ| {
        succ.iter()
            .filter_map(|s| values.get(s).copied())
            .reduce(|a, b| if a.total_cmp(&b).is_ge() { a } else { b })
    })
}

/// Python `x or 1` for an optional count: `None`/`0` → `1`.
fn nonzero_or_one(x: Option<usize>) -> usize {
    match x {
        Some(0) | None => 1,
        Some(n) => n,
    }
}

/// Widen a small graph count (height / path length) to `f64` without an `as`
/// cast — the project-wide lint surface denies `as_conversions`
/// (`priority/findings.rs` idiom). These counts never approach `u32::MAX`.
fn count_f64(n: usize) -> f64 {
    f64::from(u32::try_from(n).unwrap_or(u32::MAX))
}

/// Weakly-connected components of the merged-class graph (undirected
/// reachability over `out ∪ inn`), ordered by minimum member id (determinism;
/// the result map is a `BTreeMap`, so the order is internal-only).
fn components(nodes: &BTreeSet<ClassId>, out: &Adj, inn: &Adj) -> Vec<BTreeSet<ClassId>> {
    let mut unvisited: BTreeSet<ClassId> = nodes.clone();
    let mut comps = Vec::new();
    // pop_first yields the globally smallest unvisited id; every member of
    // its component is still unvisited, so each seed is its component's min.
    while let Some(seed) = unvisited.pop_first() {
        let mut comp = BTreeSet::new();
        let mut frontier = vec![seed];
        while let Some(n) = frontier.pop() {
            for adj in [out, inn] {
                if let Some(neighbours) = adj.get(&n) {
                    for m in neighbours {
                        if unvisited.remove(m) {
                            frontier.push(m.clone());
                        }
                    }
                }
            }
            comp.insert(n);
        }
        comps.push(comp);
    }
    comps
}

/// Place every class (P3–P8), per weakly-connected component (SL-216 D1):
/// each component picks its regime by its OWN anchors — no anchor →
/// component gauge spread; ≥1 anchor → the anchored pipeline restricted to
/// its members. No cross-component edges exist by construction, so the
/// anchored machinery per component is bitwise-identical to running it
/// globally.
fn place(
    nodes: &BTreeSet<ClassId>,
    out: &Adj,
    inn: &Adj,
    anchors: &BTreeMap<ClassId, f64>,
    cfg: &ProjectionCfg,
) -> BTreeMap<ClassId, (f64, ValueProvenance)> {
    let mut result = BTreeMap::new();
    for members in components(nodes, out, inn) {
        let component_anchors: BTreeMap<ClassId, f64> = anchors
            .iter()
            .filter(|(class, _)| members.contains(*class))
            .map(|(class, &v)| (class.clone(), v))
            .collect();
        result.extend(place_component(&members, out, inn, &component_anchors, cfg));
    }
    result
}

/// Place one component's classes (P3–P8). Anchor-free component → gauge
/// spread over the component's height range (P8); otherwise
/// reverse-topological budgeted interpolation with gauge tails. `out`/`inn`
/// are the whole-graph adjacencies — safe, since every neighbour of a member
/// is a member.
fn place_component(
    nodes: &BTreeSet<ClassId>,
    out: &Adj,
    inn: &Adj,
    anchors: &BTreeMap<ClassId, f64>,
    cfg: &ProjectionCfg,
) -> BTreeMap<ClassId, (f64, ValueProvenance)> {
    let order = topo_order(nodes, out, inn);

    // P8: anchor-free component spread, `H` = component max height.
    if anchors.is_empty() {
        let h = heights(&order, out);
        let big_h = h.values().copied().max().unwrap_or(0);
        let denom = count_f64(big_h) + 2.0;
        return nodes
            .iter()
            .map(|n| {
                let hn = h.get(n).copied().unwrap_or(0);
                let value = 2.0 * cfg.gauge_center * (count_f64(hn) + 1.0) / denom;
                (n.clone(), (value, ValueProvenance::Gauge))
            })
            .collect();
    }

    let (hi, dup) = longest_up(&order, inn, anchors);
    let dbc = depth_below_ceiling(&order, inn, anchors);
    let mut values: BTreeMap<ClassId, f64> = BTreeMap::new();
    let mut result: BTreeMap<ClassId, (f64, ValueProvenance)> = BTreeMap::new();

    for v in &order {
        // P3: an anchored class takes its authored value exactly.
        if let Some(&anchor) = anchors.get(v) {
            debug_assert!(
                successor_max(&values, out, v).is_none_or(|f| f < anchor),
                "P3: infeasible anchor placement — C5 should have guaranteed floor < anchor"
            );
            values.insert(v.clone(), anchor);
            result.insert(v.clone(), (anchor, ValueProvenance::Authored));
            continue;
        }

        let floor = successor_max(&values, out, v);
        let ceiling = hi.get(v).copied();
        let value = match (floor, ceiling) {
            // P7: no floor AND no ceiling — gauge to the center.
            (None, None) => {
                values.insert(v.clone(), cfg.gauge_center);
                result.insert(v.clone(), (cfg.gauge_center, ValueProvenance::Gauge));
                continue;
            }
            // P6: unbounded below — synthetic floor strictly under the ceiling
            // (clamped to ≥ 0 only when the ceiling is positive), then P4 up.
            (None, Some(c)) => {
                let down = nonzero_or_one(dbc.get(v).copied());
                let mut synthetic = c - cfg.gauge_step * (count_f64(down) + 1.0);
                if c > 0.0 {
                    synthetic = synthetic.max(0.0);
                }
                let up = nonzero_or_one(dup.get(v).copied());
                synthetic + (c - synthetic) / (count_f64(up) + 1.0)
            }
            // P5: unbounded above — one additive gauge step off the floor.
            (Some(f), None) => f + cfg.gauge_step,
            // P4: budgeted interpolation between floor and ceiling.
            (Some(f), Some(c)) => {
                let up = nonzero_or_one(dup.get(v).copied());
                f + (c - f) / (count_f64(up) + 1.0)
            }
        };
        values.insert(v.clone(), value);
        result.insert(v.clone(), (value, ValueProvenance::Projected));
    }
    result
}

#[cfg(test)]
mod tests {
    use super::super::compile::{AnchorMap, QuarantinePolicy, compile};
    use super::{Projection, ProjectionCfg, VALUE_PROJECTION_PARAMS, ValueProvenance, project};
    use crate::comparison::{
        DOMAIN_VALUE, FRAME_EQUAL_EFFORT, Judgement, RaterKind, Response, RowForm,
    };

    use ValueProvenance::{Authored, Gauge, Projected};

    /// The prototype's `DEFAULT = 1.0`, `STEP = 0.25` — the value call site's
    /// shipped constants (SL-219 D8): every golden below runs under the const
    /// itself, so their byte-identity IS the parameterization invariant.
    const CFG: ProjectionCfg = VALUE_PROJECTION_PARAMS;
    const EPS: f64 = 1e-4;

    // ---- SL-219 VT-1: D8 parameterization ----------------------------------

    /// D8: `VALUE_PROJECTION_PARAMS` carries the SHIPPED constants — pinned
    /// against the priority-layer named consts (`config::GAUGE_STEP`,
    /// `graph::DEFAULT_VALUE`) so the leaf-local literals can never drift, and
    /// `gauge_center` is the value domain's `1.0`. `project()` takes its params
    /// per call (no config reads — the signature is the seam); the goldens in
    /// this module all run under this const, byte-identical to the
    /// pre-parameterization suite.
    #[test]
    fn d8_value_projection_params_are_the_shipped_constants() {
        assert_eq!(
            VALUE_PROJECTION_PARAMS.gauge_step,
            crate::priority::config::GAUGE_STEP
        );
        assert_eq!(
            VALUE_PROJECTION_PARAMS.gauge_center,
            crate::priority::graph::DEFAULT_VALUE
        );
        assert_eq!(CFG, VALUE_PROJECTION_PARAMS);
    }

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

    fn judgement(uid: &str, winner: &str, loser: &str) -> Judgement {
        Judgement {
            uid: uid.to_string(),
            seq: 0,
            a: winner.to_string(),
            b: Some(loser.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-11".to_string()),
            observed_at: None,
            basis: None,
            est_lower: None,
            est_upper: None,
            admission: None,
        }
    }

    /// Compile a scenario (edges winner→loser, anchors) through the real
    /// tier-2 seam and project it. Going through `compile()` keeps the
    /// fixtures honest: classes, edges and anchors are exactly what the
    /// pipeline produces (all scenarios are feasible DAGs — no quarantine).
    fn project_scenario(edges: &[(&str, &str)], anchors: &[(&str, f64)]) -> Projection {
        project(&compiled(edges, anchors), &CFG)
    }

    fn compiled(edges: &[(&str, &str)], anchors: &[(&str, f64)]) -> super::ConstraintSet {
        let rows: Vec<Judgement> = edges
            .iter()
            .enumerate()
            .map(|(i, (w, l))| judgement(&format!("j{i}"), w, l))
            .collect();
        let refs: Vec<&Judgement> = rows.iter().collect();
        let amap: AnchorMap = anchors.iter().map(|&(e, v)| (e.to_string(), v)).collect();
        let cs = compile(&refs, &amap, QuarantinePolicy::Symmetric);
        assert!(cs.quarantined.is_empty(), "fixture must be a feasible DAG");
        cs
    }

    fn value(p: &Projection, e: &str) -> f64 {
        p.get(e).unwrap_or_else(|| panic!("missing entity {e}")).0
    }

    /// Assert an entity's value (approx 1e-4) and provenance against the
    /// prototype's 4-decimal printed golden.
    fn golden(p: &Projection, e: &str, expected: f64, prov: ValueProvenance) {
        let (got, got_prov) = *p.get(e).unwrap_or_else(|| panic!("missing entity {e}"));
        assert!(
            (got - expected).abs() < EPS,
            "{e}: got {got:.4}, want {expected:.4}"
        );
        assert_eq!(got_prov, prov, "{e} provenance");
        assert!(!got.is_nan(), "{e} is NaN");
    }

    fn chain(prefix: &str, n: usize) -> Vec<(String, String)> {
        (0..n.saturating_sub(1))
            .map(|i| (format!("{prefix}{i}"), format!("{prefix}{}", i + 1)))
            .collect()
    }

    fn edge_refs(edges: &[(String, String)]) -> Vec<(&str, &str)> {
        edges
            .iter()
            .map(|(a, b)| (a.as_str(), b.as_str()))
            .collect()
    }

    // ---- VT-1: the prototype battery (S1–S8, Y1–Y7, N1–N4) -----------------

    #[test]
    fn s1_chain8_gauge() {
        let e = chain("n", 8);
        let p = project_scenario(&edge_refs(&e), &[]);
        for (i, want) in [
            1.7778, 1.5556, 1.3333, 1.1111, 0.8889, 0.6667, 0.4444, 0.2222,
        ]
        .into_iter()
        .enumerate()
        {
            golden(&p, &format!("n{i}"), want, Gauge);
        }
    }

    #[test]
    fn s2_partial_order_gauge() {
        // Diamond a>b,a>c,b>d,c>d,d>e PLUS a disjoint pendant f>g. Each
        // component takes its own spread (P8: component H — SL-216): the
        // diamond over H=3, the pendant over H=1, so f/g land at the 2-chain
        // scale 1.3333/0.6667, not on rungs of the diamond's taller ladder.
        let edges = [
            ("a", "b"),
            ("a", "c"),
            ("b", "d"),
            ("c", "d"),
            ("d", "e"),
            ("f", "g"),
        ];
        let p = project_scenario(&edges, &[]);
        golden(&p, "a", 1.6000, Gauge);
        golden(&p, "b", 1.2000, Gauge);
        golden(&p, "c", 1.2000, Gauge);
        golden(&p, "d", 0.8000, Gauge);
        golden(&p, "f", 1.3333, Gauge);
        golden(&p, "e", 0.4000, Gauge);
        golden(&p, "g", 0.6667, Gauge);
    }

    #[test]
    fn s3_mid_anchor_budgeted() {
        let e = chain("n", 8);
        let p = project_scenario(&edge_refs(&e), &[("n4", 5.0)]);
        golden(&p, "n0", 6.0000, Projected);
        golden(&p, "n1", 5.7500, Projected);
        golden(&p, "n2", 5.5000, Projected);
        golden(&p, "n3", 5.2500, Projected);
        golden(&p, "n4", 5.0000, Authored);
        golden(&p, "n5", 4.7500, Projected);
        golden(&p, "n6", 4.5000, Projected);
        golden(&p, "n7", 4.2500, Projected);
    }

    #[test]
    fn s4_low_anchor_deep_tail() {
        let e = chain("m", 6);
        let p = project_scenario(&edge_refs(&e), &[("m0", 0.5)]);
        golden(&p, "m0", 0.5000, Authored);
        golden(&p, "m1", 0.4167, Projected);
        golden(&p, "m2", 0.3333, Projected);
        golden(&p, "m3", 0.2500, Projected);
        golden(&p, "m4", 0.1667, Projected);
        golden(&p, "m5", 0.0833, Projected);
    }

    #[test]
    fn s5_bracket_crowding_budgeted() {
        let e = chain("b", 6);
        let p = project_scenario(&edge_refs(&e), &[("b0", 8.0), ("b5", 2.0)]);
        golden(&p, "b0", 8.0000, Authored);
        golden(&p, "b1", 6.8000, Projected);
        golden(&p, "b2", 5.6000, Projected);
        golden(&p, "b3", 4.4000, Projected);
        golden(&p, "b4", 3.2000, Projected);
        golden(&p, "b5", 2.0000, Authored);
    }

    #[test]
    fn s6_sparse_anchor_before_and_after() {
        let edges = [
            ("p", "q"),
            ("q", "r"),
            ("p", "s"),
            ("s", "t"),
            ("t", "u"),
            ("q", "t"),
        ];
        let before = project_scenario(&edges, &[]);
        golden(&before, "p", 1.6000, Gauge);
        golden(&before, "q", 1.2000, Gauge);
        golden(&before, "s", 1.2000, Gauge);
        golden(&before, "t", 0.8000, Gauge);
        golden(&before, "r", 0.4000, Gauge);
        golden(&before, "u", 0.4000, Gauge);

        let after = project_scenario(&edges, &[("s", 5.0)]);
        golden(&after, "p", 5.2500, Projected);
        golden(&after, "q", 5.0000, Projected);
        golden(&after, "s", 5.0000, Authored);
        golden(&after, "t", 4.7500, Projected);
        golden(&after, "u", 4.5000, Projected);
        golden(&after, "r", 1.0000, Gauge);
        // Order flips r below u after the anchor lands (minimal-motion demo).
        assert!(value(&after, "u") > value(&after, "r"));
    }

    #[test]
    fn s7_cross_window_edge() {
        let edges = [("A8", "u"), ("u", "v"), ("v", "A2"), ("A5", "v")];
        let p = project_scenario(&edges, &[("A8", 8.0), ("A5", 5.0), ("A2", 2.0)]);
        golden(&p, "A8", 8.0000, Authored);
        golden(&p, "u", 5.7500, Projected);
        golden(&p, "A5", 5.0000, Authored);
        golden(&p, "v", 3.5000, Projected);
        golden(&p, "A2", 2.0000, Authored);
    }

    #[test]
    fn s8_incremental_locality() {
        // The anchor-free island {z>w} picks its own regime (D1): the P8
        // component spread over H=1, both Gauge — not P7+P5 off the corpus's
        // anchored component. The anchored side is untouched.
        let base = [("x", "y"), ("z", "w")];
        let islands = project_scenario(&base, &[("x", 4.0)]);
        golden(&islands, "x", 4.0000, Authored);
        golden(&islands, "y", 3.7500, Projected);
        golden(&islands, "z", 1.3333, Gauge);
        golden(&islands, "w", 0.6667, Gauge);

        let joined = project_scenario(&[("x", "y"), ("z", "w"), ("y", "z")], &[("x", 4.0)]);
        golden(&joined, "x", 4.0000, Authored);
        golden(&joined, "y", 3.7500, Projected);
        golden(&joined, "z", 3.5000, Projected);
        golden(&joined, "w", 3.2500, Projected);
    }

    #[test]
    fn mixed_corpus_island() {
        // Anchored diamond (a=2.0) + anchor-free pendant f>g (SL-216 D1).
        // The pendant is its own component: centred P8 spread over its H=1,
        // Gauge provenance — it ignores the neighbour component's anchor
        // entirely (f sits ABOVE the diamond's interior values). The loser g
        // lands BELOW default (0.6667 < 1.0): judged-and-lost ranks below
        // unjudged, the adjudicated behavioural change.
        let edges = [
            ("a", "b"),
            ("a", "c"),
            ("b", "d"),
            ("c", "d"),
            ("d", "e"),
            ("f", "g"),
        ];
        let p = project_scenario(&edges, &[("a", 2.0)]);
        golden(&p, "a", 2.0000, Authored);
        golden(&p, "b", 1.7500, Projected);
        golden(&p, "c", 1.7500, Projected);
        golden(&p, "d", 1.5000, Projected);
        golden(&p, "e", 1.2500, Projected);
        golden(&p, "f", 1.3333, Gauge);
        golden(&p, "g", 0.6667, Gauge);
    }

    #[test]
    fn singleton_island_lands_on_default_value() {
        // An edge-free class (equal-merged pair) in a pure-gauge
        // multi-component corpus is its own component: h=0, H=0 ⇒
        // 2·D·(0+1)/(0+2) = D (default_value) — not a rung of a neighbouring
        // component's ladder (SL-216, design internal F3).
        let mut rows = vec![judgement("j0", "a", "b")];
        let mut eq = judgement("j1", "s1", "s2");
        eq.response = Some(Response::Equal);
        rows.push(eq);
        let refs: Vec<&Judgement> = rows.iter().collect();
        let cs = compile(&refs, &AnchorMap::new(), QuarantinePolicy::Symmetric);
        assert!(cs.quarantined.is_empty(), "fixture must be a feasible DAG");
        let p = project(&cs, &CFG);
        golden(&p, "a", 1.3333, Gauge);
        golden(&p, "b", 0.6667, Gauge);
        golden(&p, "s1", 1.0000, Gauge);
        golden(&p, "s2", 1.0000, Gauge);
    }

    #[test]
    fn y1_join_y_gauge() {
        let edges = [
            ("a0", "a1"),
            ("a1", "a2"),
            ("a2", "j"),
            ("b0", "b1"),
            ("b1", "j"),
        ];
        let p = project_scenario(&edges, &[]);
        golden(&p, "a0", 1.6000, Gauge);
        golden(&p, "a1", 1.2000, Gauge);
        golden(&p, "b0", 1.2000, Gauge);
        golden(&p, "a2", 0.8000, Gauge);
        golden(&p, "b1", 0.8000, Gauge);
        golden(&p, "j", 0.4000, Gauge);
    }

    #[test]
    fn y2_split_y_gauge() {
        let edges = [
            ("h", "c0"),
            ("c0", "c1"),
            ("c1", "c2"),
            ("h", "d0"),
            ("d0", "d1"),
        ];
        let p = project_scenario(&edges, &[]);
        golden(&p, "h", 1.6000, Gauge);
        golden(&p, "c0", 1.2000, Gauge);
        golden(&p, "c1", 0.8000, Gauge);
        golden(&p, "d0", 0.8000, Gauge);
        golden(&p, "c2", 0.4000, Gauge);
        golden(&p, "d1", 0.4000, Gauge);
    }

    #[test]
    fn y3_sensitivity_extend_short_arm() {
        let edges = [
            ("a0", "a1"),
            ("a1", "a2"),
            ("a2", "j"),
            ("b0", "b1"),
            ("b1", "b2"),
            ("b2", "j"),
        ];
        let p = project_scenario(&edges, &[]);
        golden(&p, "a0", 1.6000, Gauge);
        golden(&p, "b0", 1.6000, Gauge);
        golden(&p, "a1", 1.2000, Gauge);
        golden(&p, "b1", 1.2000, Gauge);
        golden(&p, "a2", 0.8000, Gauge);
        golden(&p, "b2", 0.8000, Gauge);
        golden(&p, "j", 0.4000, Gauge);
    }

    #[test]
    fn y4_pin_cross_judgement() {
        let edges = [
            ("a0", "a1"),
            ("a1", "a2"),
            ("a2", "j"),
            ("b0", "b1"),
            ("b1", "j"),
            ("b0", "a1"),
        ];
        let p = project_scenario(&edges, &[]);
        golden(&p, "a0", 1.6000, Gauge);
        golden(&p, "b0", 1.6000, Gauge);
        golden(&p, "a1", 1.2000, Gauge);
        golden(&p, "a2", 0.8000, Gauge);
        golden(&p, "b1", 0.8000, Gauge);
        golden(&p, "j", 0.4000, Gauge);
    }

    #[test]
    fn y5_pin_with_anchor_collision() {
        // b0=3 anchor; a1 and b1 both land at 2.75 — the accepted
        // anchor-value collision (D14/P15), order-safe, disambiguated by
        // provenance.
        let edges = [
            ("a0", "a1"),
            ("a1", "a2"),
            ("a2", "j"),
            ("b0", "b1"),
            ("b1", "j"),
        ];
        let p = project_scenario(&edges, &[("b0", 3.0)]);
        golden(&p, "a0", 3.2500, Projected);
        golden(&p, "a1", 3.0000, Projected);
        golden(&p, "b0", 3.0000, Authored);
        golden(&p, "a2", 2.7500, Projected);
        golden(&p, "b1", 2.7500, Projected);
        golden(&p, "j", 2.5000, Projected);
    }

    #[test]
    fn y6_bracketed_arms() {
        let edges = [
            ("T", "a1"),
            ("a1", "a2"),
            ("a2", "a3"),
            ("a3", "B"),
            ("T", "b1"),
            ("b1", "B"),
        ];
        let p = project_scenario(&edges, &[("T", 8.0), ("B", 2.0)]);
        golden(&p, "T", 8.0000, Authored);
        golden(&p, "a1", 6.5000, Projected);
        golden(&p, "a2", 5.0000, Projected);
        golden(&p, "b1", 5.0000, Projected);
        golden(&p, "a3", 3.5000, Projected);
        golden(&p, "B", 2.0000, Authored);
    }

    #[test]
    fn y7_pin_inside_bracket() {
        let edges = [
            ("T", "a1"),
            ("a1", "a2"),
            ("a2", "a3"),
            ("a3", "B"),
            ("T", "b1"),
            ("b1", "B"),
            ("a2", "b1"),
        ];
        let p = project_scenario(&edges, &[("T", 8.0), ("B", 2.0)]);
        golden(&p, "T", 8.0000, Authored);
        golden(&p, "a1", 6.5000, Projected);
        golden(&p, "a2", 5.0000, Projected);
        golden(&p, "a3", 3.5000, Projected);
        golden(&p, "b1", 3.5000, Projected);
        golden(&p, "B", 2.0000, Authored);
        // Minimal motion: only the touched arm (b1) moved vs y6; a1/a2/a3 held.
        assert!((value(&p, "a2") - 5.0).abs() < EPS);
    }

    #[test]
    fn n1_negative_ceiling_tail() {
        let e = chain("k", 4);
        let p = project_scenario(&edge_refs(&e), &[("k0", -0.5)]);
        golden(&p, "k0", -0.5000, Authored);
        golden(&p, "k1", -0.7500, Projected);
        golden(&p, "k2", -1.0000, Projected);
        golden(&p, "k3", -1.2500, Projected);
    }

    #[test]
    fn n2_sign_crossing_bracket() {
        let e = chain("j", 4);
        let p = project_scenario(&edge_refs(&e), &[("j0", 3.0), ("j3", -2.0)]);
        golden(&p, "j0", 3.0000, Authored);
        golden(&p, "j1", 1.3333, Projected);
        golden(&p, "j2", -0.3333, Projected);
        golden(&p, "j3", -2.0000, Authored);
    }

    #[test]
    fn n3_branch_floor_and_ceiling() {
        let edges = [("A", "X"), ("X", "Y"), ("X", "Z")];
        let p = project_scenario(&edges, &[("A", 10.0), ("Z", 8.0)]);
        golden(&p, "A", 10.0000, Authored);
        golden(&p, "X", 9.7500, Projected);
        golden(&p, "Y", 9.5000, Projected);
        golden(&p, "Z", 8.0000, Authored);
    }

    #[test]
    fn n4_multi_ceiling_tiebreak() {
        let edges = [("A", "X"), ("B", "W"), ("W", "X"), ("X", "Y")];
        let p = project_scenario(&edges, &[("A", 10.0), ("B", 9.0)]);
        golden(&p, "A", 10.0000, Authored);
        golden(&p, "B", 9.0000, Authored);
        golden(&p, "W", 8.7500, Projected);
        golden(&p, "X", 8.5000, Projected);
        golden(&p, "Y", 8.2500, Projected);
    }

    // ---- VT-2: property tests over DETERMINISTICALLY generated inputs -------

    /// Every response assignment over four entities' six pairs (4^6 ledgers)
    /// crossed with three anchor configs — the same deterministic enumeration
    /// PHASE-03 uses (no proptest, no rng).
    fn generated_cases() -> impl Iterator<Item = (Vec<(String, String)>, Vec<(&'static str, f64)>)>
    {
        const PAIRS: [(&str, &str); 6] = [
            ("A", "B"),
            ("A", "C"),
            ("A", "D"),
            ("B", "C"),
            ("B", "D"),
            ("C", "D"),
        ];
        let configs: [Vec<(&'static str, f64)>; 3] = [
            vec![],
            vec![("A", 5.0), ("D", 1.0)],
            vec![("A", 8.0), ("B", 3.0), ("D", 1.0)],
        ];
        configs.into_iter().flat_map(move |cfg| {
            (0..4_u32.pow(6)).filter_map(move |mask| {
                // Only keep ledgers whose anchors are order-consistent with a
                // possible acyclic reading — compile quarantines the rest, so
                // we simply project whatever survives (retained edges only).
                let mut edges = Vec::new();
                for (i, (a, b)) in PAIRS.iter().enumerate() {
                    match (mask / 4_u32.pow(i as u32)) % 4 {
                        1 => edges.push(((*a).to_string(), (*b).to_string())),
                        2 => edges.push(((*b).to_string(), (*a).to_string())),
                        // 0 = absent, 3 = equal (skip; we only need strict
                        // edges for the order-safety property).
                        _ => {}
                    }
                }
                Some((edges, cfg.clone()))
            })
        })
    }

    #[test]
    fn p10_generated_order_consistency_no_nan() {
        for (edges, anchors) in generated_cases() {
            let refs = edge_refs(&edges);
            let rows: Vec<Judgement> = refs
                .iter()
                .enumerate()
                .map(|(i, (w, l))| judgement(&format!("j{i}"), w, l))
                .collect();
            let jrefs: Vec<&Judgement> = rows.iter().collect();
            let amap: AnchorMap = anchors.iter().map(|&(e, v)| (e.to_string(), v)).collect();
            let cs = compile(&jrefs, &amap, QuarantinePolicy::Symmetric);
            let p = project(&cs, &CFG);
            // Every RETAINED strict edge is strictly respected; nothing NaN.
            for (winner, loser) in cs.edges.keys() {
                let wv = cs.classes.get(winner).and_then(|c| class_value(&cs, &p, c));
                let lv = cs.classes.get(loser).and_then(|c| class_value(&cs, &p, c));
                if let (Some(w), Some(l)) = (wv, lv) {
                    assert!(w > l, "edge {winner}>{loser}: {w} !> {l}");
                }
            }
            for (_, (val, _)) in &p {
                assert!(!val.is_nan(), "NaN projected value");
            }
        }
    }

    /// A class's value via any of its member entities.
    fn class_value(cs: &super::ConstraintSet, p: &Projection, class: &str) -> Option<f64> {
        cs.classes
            .iter()
            .find(|(_, c)| c.as_str() == class)
            .and_then(|(entity, _)| p.get(entity).map(|&(v, _)| v))
    }

    #[test]
    fn p11_determinism_under_permuted_input() {
        let edges = [("A", "B"), ("B", "C"), ("C", "D"), ("A", "E"), ("E", "D")];
        let anchors = [("A", 9.0), ("D", 1.0)];
        let rows: Vec<Judgement> = edges
            .iter()
            .enumerate()
            .map(|(i, (w, l))| judgement(&format!("j{i}"), w, l))
            .collect();
        let amap: AnchorMap = anchors.iter().map(|&(e, v)| (e.to_string(), v)).collect();
        let forward: Vec<&Judgement> = rows.iter().collect();
        let backward: Vec<&Judgement> = rows.iter().rev().collect();
        let p1 = project(&compile(&forward, &amap, QuarantinePolicy::Symmetric), &CFG);
        let p2 = project(
            &compile(&backward, &amap, QuarantinePolicy::Symmetric),
            &CFG,
        );
        assert_eq!(
            p1, p2,
            "projection must be bitwise-identical across input order"
        );
    }

    #[test]
    fn p12_locality_disjoint_anchored_components() {
        // Anchored↔anchored witness (retained verbatim, SL-216 / RV-267 F-4).
        // Component X = {A>B, A=10}; component Y = {P>Q, P=5}. Perturbing X
        // (append B>C) must not move Y's values.
        let y_edges = [("P", "Q")];
        let x_before = [("A", "B")];
        let anchors = [("A", 10.0), ("P", 5.0)];

        let combined = |x: &[(&str, &str)]| -> Projection {
            let edges: Vec<(&str, &str)> = x.iter().chain(y_edges.iter()).copied().collect();
            project_scenario(&edges, &anchors)
        };
        let base = combined(&x_before);
        let perturbed = combined(&[("A", "B"), ("B", "C")]);
        for e in ["P", "Q"] {
            assert_eq!(
                base.get(e),
                perturbed.get(e),
                "component Y entity {e} moved under a disjoint-X evidence delta"
            );
        }
    }

    #[test]
    fn p12_locality_anchored_perturbation_freezes_gauge_island() {
        // Universal locality (SL-216 D1): an evidence delta inside anchored
        // X = {A>B, A=10} must not move the anchor-free island Y = {P>Q} —
        // values OR provenance.
        let combined = |x: &[(&str, &str)]| -> Projection {
            let edges: Vec<(&str, &str)> = x.iter().chain([("P", "Q")].iter()).copied().collect();
            project_scenario(&edges, &[("A", 10.0)])
        };
        let base = combined(&[("A", "B")]);
        let perturbed = combined(&[("A", "B"), ("B", "C")]);
        for e in ["P", "Q"] {
            assert_eq!(
                base.get(e),
                perturbed.get(e),
                "gauge island entity {e} moved under a disjoint anchored-X delta"
            );
        }
    }

    #[test]
    fn p12_locality_gauge_island_perturbation_freezes_anchored() {
        // The reverse direction: growing the anchor-free island Y (append
        // Q>R) must not move anchored X's values.
        let combined = |y: &[(&str, &str)]| -> Projection {
            let edges: Vec<(&str, &str)> = [("A", "B")].iter().chain(y.iter()).copied().collect();
            project_scenario(&edges, &[("A", 10.0)])
        };
        let base = combined(&[("P", "Q")]);
        let perturbed = combined(&[("P", "Q"), ("Q", "R")]);
        for e in ["A", "B"] {
            assert_eq!(
                base.get(e),
                perturbed.get(e),
                "anchored entity {e} moved under a disjoint gauge-island delta"
            );
        }
    }

    #[test]
    fn p12_locality_first_anchor_leaves_disjoint_island_frozen() {
        // Leak 2 (SL-216 D1): the corpus's FIRST anchor landing in component
        // X must not flip disjoint island Y's regime — Y keeps its component
        // spread (1.3333/0.6667, Gauge), it does not fall to P7+P5 (1.25/1.0).
        // Regime membership is itself local.
        let edges = [("A", "B"), ("P", "Q")];
        let pure = project_scenario(&edges, &[]);
        golden(&pure, "P", 1.3333, Gauge);
        golden(&pure, "Q", 0.6667, Gauge);

        let first_anchor = project_scenario(&edges, &[("A", 10.0)]);
        for e in ["P", "Q"] {
            assert_eq!(
                pure.get(e),
                first_anchor.get(e),
                "island entity {e} moved when the corpus's first anchor landed in X"
            );
        }
    }

    #[test]
    fn p14_scoped_affine_equivariance() {
        // Within an anchor-bracketed span, shifting/scaling BOTH anchors
        // shifts/scales the interior projections identically. Scope limit:
        // this holds for bracketed (floor-and-ceiling) spans; unbounded tails
        // move by absolute gauge_step, not affinely (design P14).
        let e = chain("b", 6);
        let refs = edge_refs(&e);
        let base = project_scenario(&refs, &[("b0", 8.0), ("b5", 2.0)]);

        // Shift: +10 on both anchors ⇒ +10 on every bracketed class.
        let shifted = project_scenario(&refs, &[("b0", 18.0), ("b5", 12.0)]);
        for i in 1..5 {
            let k = format!("b{i}");
            assert!(
                (value(&shifted, &k) - (value(&base, &k) + 10.0)).abs() < EPS,
                "shift {k}"
            );
        }

        // Scale: ×2 about zero on both anchors ⇒ ×2 on every bracketed class.
        let scaled = project_scenario(&refs, &[("b0", 16.0), ("b5", 4.0)]);
        for i in 1..5 {
            let k = format!("b{i}");
            assert!(
                (value(&scaled, &k) - value(&base, &k) * 2.0).abs() < EPS,
                "scale {k}"
            );
        }
    }

    #[test]
    fn p6_synthetic_floor_strictly_below_ceiling() {
        // Unbounded-below tails: every projected value strictly below its
        // ceiling and strictly decreasing; positive ceiling keeps them ≥ 0,
        // negative ceiling lets them go negative (RV-265 F-1). Swept over
        // depths and both ceiling signs.
        for &(anchor, positive) in &[(0.5_f64, true), (-0.5_f64, false)] {
            for depth in 1..6 {
                let e = chain("t", depth + 1);
                let p = project_scenario(&edge_refs(&e), &[("t0", anchor)]);
                let mut prev = anchor;
                for i in 1..=depth {
                    let cur = value(&p, &format!("t{i}"));
                    assert!(cur < prev, "not strictly decreasing at t{i}");
                    assert!(cur < anchor, "t{i} not strictly below ceiling");
                    if positive {
                        assert!(cur >= 0.0, "positive ceiling manufactured a negative t{i}");
                    }
                    prev = cur;
                }
            }
        }
    }

    #[test]
    fn p8_gauge_spread_positive_and_centred() {
        // Anchor-free spread lands strictly in (0, 2·default) and is centred:
        // min + max = 2·default (the extremes are symmetric about default).
        let e = chain("n", 8);
        let p = project_scenario(&edge_refs(&e), &[]);
        let vals: Vec<f64> = (0..8).map(|i| value(&p, &format!("n{i}"))).collect();
        let lo = vals.iter().copied().fold(f64::INFINITY, f64::min);
        let hi = vals.iter().copied().fold(f64::NEG_INFINITY, f64::max);
        assert!(lo > 0.0, "gauge below 0");
        assert!(hi < 2.0 * CFG.gauge_center, "gauge above 2·default");
        assert!(
            (lo + hi - 2.0 * CFG.gauge_center).abs() < EPS,
            "not centred"
        );
    }

    // ---- EX-3: GAUGE_STEP sensitivity sweep --------------------------------

    #[test]
    fn ex3_gauge_step_sweep_order_and_provenance_invariant() {
        // Order-safety and provenance labels must hold at every gauge_step on
        // the grid 0.05..=1.0 (step 0.05), over scenarios exercising both
        // unbounded tails (P6) and unbounded heads (P5/P7).
        let tail = chain("m", 6); // low anchor, deep tail below (P6)
        let head = [("x", "y"), ("z", "w"), ("y", "z")]; // chain under anchor + P5 head
        let mut step_milli = 5_u32;
        while step_milli <= 1000 {
            let cfg = ProjectionCfg {
                gauge_step: f64::from(step_milli) / 1000.0,
                gauge_center: 1.0,
            };

            let tp = project(&compiled(&edge_refs(&tail), &[("m0", 0.5)]), &cfg);
            assert_eq!(tp.get("m0").map(|&(_, pr)| pr), Some(Authored));
            for i in 1..6 {
                assert_eq!(
                    tp.get(&format!("m{i}")).map(|&(_, pr)| pr),
                    Some(Projected),
                    "tail provenance drifted at step {step_milli}"
                );
            }
            for i in 0..5 {
                assert!(
                    value(&tp, &format!("m{i}")) > value(&tp, &format!("m{}", i + 1)),
                    "tail order broke at step {step_milli}"
                );
            }

            let hp = project(&compiled(&head, &[("x", 4.0)]), &cfg);
            for (winner, loser) in &head {
                assert!(
                    value(&hp, winner) > value(&hp, loser),
                    "head order {winner}>{loser} broke at step {step_milli}"
                );
            }
            assert_eq!(hp.get("x").map(|&(_, pr)| pr), Some(Authored));

            step_milli += 50;
        }
    }
}