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
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
// SPDX-License-Identifier: GPL-3.0-only
//! `priority::elicit` — SL-217 design §2: the elicitation queue assembler.
//!
//! Pure over its [`ElicitInputs`] (active comparison rows, anchors, the ranked
//! frontier, a per-item costing map, and the projection) plus a
//! [`DecisionContext`]. No clock, disk, rng, or git — the one impure load
//! (session scan + costing build from the priority graph) stays in the command
//! shell / PHASE-03. The assembler compiles the baseline [`ConstraintSet`]
//! internally (single source; compile is evidence-sized) and rides the
//! `comparison::query` predicates for every determinacy question.
//!
//! Three candidate sources feed one ranked queue:
//!
//! 1. **Comparison** — indeterminate pairs among the *constrained* top-K
//!    value-sensitive items, behind the capture-admissibility gate.
//! 2. **Median-probe** (D14) — one calibration probe per *un-constrained*
//!    top-K item against the projected median of its comparable set. Stateless.
//! 3. **Anchor-review** (D12) — one candidate per distinct suspect anchor in an
//!    `AnchorConflict` quarantine pair; admits on suspect EXISTENCE, not on
//!    yield, and is deliberately NOT K-gated.
//! 4. **Sizing-probe** (SL-219 §4, D4) — one calibration probe per un-sized
//!    top-K subject (no authored estimate, zero est-domain rows), driving a
//!    `more-work` sizing session against the median-cost authored-estimate
//!    target. Existence-admitted, never yield-ranked (`score 0`,
//!    `yield_basis` Calibration) — probes sink below every yield-motivated
//!    entry via the one sort. No hypothetical machinery runs for a probe.
//!
//! Ranking (D13): `score = guaranteed_yield × guaranteed_impact ×
//! confirm_boost`; `guaranteed_impact` = the min, over the answers attaining
//! the min yield, of the rank-decay-weighted count of that answer's
//! newly-determined pairs. Determinism: `BTree` everywhere, `total_cmp` on
//! scores, id-lexicographic tiebreak, no float in any key.
//!
//! Design-internal reconciliation flagged for audit (notes.md): the
//! `guaranteed_yield > 0` admission filter applies to the yield-motivated
//! sources (comparison, median-probe) only; anchor-review admits on existence
//! (D15 pins a live stale-anchor suspect as standing evidence-debt — a blanket
//! filter would gut it). A second in-phase reading: comparison enumerates
//! *constrained* pool pairs while median-probe owns the *un-constrained* items,
//! partitioning the two sources so a brand-new item yields one probe rather
//! than K flooding pairs (D14's calibration intent).

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

use crate::comparison::{
    AnchorMap, Bound, ClaimFinding, ClaimResolution, ClaimTier, ClassId, ConstraintSet,
    Hypothetical, Judgement, PairSide, Projection, QuarantinePolicy, QuarantineReason,
    Reachability, Response, RowUid, ValueBounds, ValueProvenance, admissible_estimate_pair,
    admissible_value_pair, compile, compile_human_only, constraining_counts_by_class, determined,
    human_rows, hypothetical_outcome, synthetic_answer_row,
};

// ── inputs ──────────────────────────────────────────────────────────────────

/// The pluggable decision-context seam (design D3). `Sequencing` ships alone;
/// `Scoping { budget }` is Phase E's slot. The relevant-pair predicate varies
/// by context; the yield machinery is context-blind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DecisionContext {
    /// The sequencing context: probe the top-`depth` frontier band.
    Sequencing { depth: usize },
}

/// One frontier item, ranked best-first: its entity id and kind prefix. The
/// kind drives the capture-admissibility gate (design §2 source 1) — the same
/// `admissible_value_pair` rule `compare record` applies, no second rule set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FrontierItem {
    pub id: String,
    pub kind: String,
}

/// Per-item costing, built by the PHASE-03 shell from the priority graph
/// (`m = coeff.value × kind_weight × tag_term`, design D6; `est_cost` per the
/// β-skewed model). `bare_estimate` flags a projected/gauge value with no
/// estimate facet (D17 mask).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct ItemCosting {
    pub multiplier: f64,
    pub est_cost: f64,
    pub bare_estimate: bool,
}

/// The pure inputs to [`assemble`] (design §2). The shell fills these from the
/// composed pipeline; the assembler needs no disk. `rank_decay` /
/// `confirm_boost` are the `[priority.elicit]` numeric shapes (D13), passed as
/// pure config inputs.
#[derive(Debug, Clone)]
pub(crate) struct ElicitInputs<'a> {
    /// The value-domain PAIRWISE evidence (SL-220 §2: the shell feeds
    /// `Pipeline::active_pairwise` — anchor rows terminate at the claims
    /// pass and never reach this recompiler, RV-278 F-6).
    pub active: Vec<&'a Judgement>,
    pub anchors: AnchorMap,
    pub frontier: Vec<FrontierItem>,
    pub costing: BTreeMap<String, ItemCosting>,
    pub projection: Projection,
    pub rank_decay: f64,
    pub confirm_boost: f64,
    /// SL-218 D1: knob-on, every determinacy verdict is read over the
    /// human-rows-only system; the full system keeps bounds, projection,
    /// and the queue pool.
    pub demote_agent_evidence: bool,
    /// SL-219 §4: the est-domain facts the sizing-probe source reads. An empty
    /// bundle (the default) mints no probes and discloses nothing — the
    /// behaviour-preservation gate for every corpus with no est activity.
    pub sizing: SizingInputs,
    /// SL-220 §3: the value-domain claim resolution (the shell clones
    /// `Pipeline.value_claims`). Three queue consumers: rung-1 `anchored`
    /// items retire calibration probes KNOB-INDEPENDENTLY (a human answered);
    /// `priors` retire them only while `demote_agent_evidence` is off (a
    /// number, not an answer); the anchored-tier conflict findings mint the
    /// D14 claim-reprobe entries. An empty resolution (the default) is the
    /// pre-claims queue bit-for-bit.
    pub claims: ClaimResolution,
    /// SL-220 §3 rung 5: items carrying an unmigrated `[value]` facet (the
    /// shell derives it from the graph's facet attrs). Valued for queue
    /// purposes exactly like a prior — knob-off retired, knob-on
    /// probe-eligible.
    pub facet_valued: BTreeSet<String>,
}

/// The est-domain inputs the sizing-probe source (SL-219 §4) rides — derived by
/// the shell from the est pipeline, threaded as PURE facts (no disk here). Two
/// signals: the calibration-target pool (authored est costs only, so the
/// anchored-membership postcondition holds by construction) and the
/// est-evidenced set (an item touched by ANY resolved-active est row — the
/// predicate that retires a probe when an `incomparable` row lands).
#[derive(Debug, Clone, Default)]
pub(crate) struct SizingInputs {
    /// Admissible items WITH an authored estimate → their authored `est_cost`
    /// (D1). The probe-target candidate pool — NEVER a projected/gauge cost.
    /// Whole corpus, not just top-K (fallback tier 1 medians over all of it).
    pub estimated_costs: BTreeMap<String, f64>,
    /// Items touched by ≥1 resolved-active est-domain row of ANY compilation
    /// status (§4 pool predicate). An est-evidenced item is NOT a probe subject
    /// — an `incomparable` row (→ `NoConstraint`) still lands here, so the
    /// engine asks once and retires; gauge-component members carry est rows too,
    /// so they fall out here (never probed, mask-annotation only).
    pub est_evidenced: BTreeSet<String>,
    /// SL-222 E10 (design §6.10): items with an anchored-tier estimate claim
    /// (Pin/Human) — the ONLY valid sizing-probe TARGETS. A facet-only or
    /// agent/migrated-only item is NOT a valid target. The shell populates this
    /// from `pipeline.estimate_claims.anchored` keys. An empty set means zero
    /// anchored-tier claims exist ⇒ no probes minted and the
    /// "no estimated item to calibrate against" state detail fires.
    pub estimate_anchored_targets: BTreeSet<String>,
}

// ── queue model ─────────────────────────────────────────────────────────────

/// The queue state (design D15, precedence pinned): any entries ⇒ `Candidates`;
/// no entries with every value-sensitive top-K pair determined ⇒ `Stable`; no
/// entries with an indeterminate pair (a zero-yield bridge) ⇒ `Stalled`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum QueueState {
    Candidates,
    Stalled { depth: usize },
    Stable { depth: usize },
}

/// The candidate kind (design D16, kind-tagged entries).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CandidateKind {
    Comparison,
    AnchorReview,
    /// SL-219 §4: a deterministic sizing session against a median authored
    /// estimate — existence-admitted, zero yield claim.
    SizingProbe,
    /// SL-220 D14: an ANCHORED-tier (Pin/Human) claim conflict — "the humans
    /// must talk". Existence-admitted, zero yield claim, knob-independent;
    /// agent/migrated conflicts never mint one.
    ClaimReprobe,
}

/// The answer space an entry's guaranteed yield ranges over (design D11) —
/// disclosed so a curator knows the numbers stay spine-comparable but the
/// semantics differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum YieldBasis {
    OrderBearingAnswers,
    CanonicalResolvingActions,
    /// SL-219 §4 / SL-220 D14: the entry makes NO yield claim — its numbers
    /// are pinned at zero and disclosed as such (a sizing probe's calibration
    /// ask, or a claim reprobe's existence admission), never spine-comparable
    /// to a yield-motivated entry.
    Calibration,
}

/// A structured reason (design D16, findings JSON-parity idiom).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Reason {
    pub code: String,
    pub text: String,
}

/// A lean participant (design D16): id + annotations; no body summaries — the
/// render fetches entity context itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Participant {
    pub id: String,
    pub annotations: Vec<String>,
}

/// The deterministic calibration target of a sizing probe (SL-219 §4): the
/// median authored-estimate item the subject is sized against. `estimate` is
/// the target's authored `est_cost` (never projected/gauge — the target pool is
/// authored-only), carried so the render shows the anchor the curator judges
/// against. `tier_label` names the claim tier backing this target ("human claim",
/// "agent claim", etc.) for the probe reason text (SL-222 PHASE-07).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct SizingTarget {
    pub id: String,
    pub estimate: f64,
    /// The tier label of the estimate claim backing this target, e.g.
    /// "human claim", "agent claim". Empty string when no claim tier is known
    /// (defensive fallback for pre-tier code paths).
    pub tier_label: String,
}

/// The suspect anchor an anchor-review entry is about.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct AnchorSubject {
    pub id: String,
    pub anchor: Option<f64>,
    pub conflict_pairs: Vec<(String, String)>,
    pub quarantined_rows: Vec<String>,
}

/// The ask block: the answer tokens, each token's disclosed yield, and (for
/// anchor-review) the conditional-yield note (design §3, RV-269 F-3).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct AskSpec {
    pub answers: Vec<&'static str>,
    pub yield_by_answer: BTreeMap<String, i64>,
    pub yield_note: Option<String>,
}

/// The kind-specific payload (design §2/§3).
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum EntryPayload {
    Comparison {
        a: Participant,
        b: Participant,
        ask: AskSpec,
    },
    AnchorReview {
        subject: AnchorSubject,
        ask: AskSpec,
    },
    /// SL-219 §4: a sizing probe — a lean subject (id + annotations) sized
    /// against the median authored-estimate `target`. Carries no `AskSpec`: the
    /// `more-work` frame, `estimate` domain, and answer tokens are invariant
    /// (rendered from constants), and a probe discloses NO per-answer yield.
    SizingProbe {
        subject: Participant,
        target: SizingTarget,
    },
    /// SL-220 D14: a contested anchored-tier claim — the conflict's tier
    /// (`Pin` renders "contested pin"), the resolved mean, the D3 interval
    /// `{low, high, distinct}`, and the winning-tier row count. Carries no
    /// `AskSpec`: the resolving action is invariant (a superseding
    /// `value set`/`value pin` row) and a reprobe discloses no yield.
    ClaimReprobe {
        subject: String,
        tier: ClaimTier,
        mean: f64,
        low: f64,
        high: f64,
        distinct: u32,
        rows: u32,
    },
}

/// One ranked queue entry (design §2 spine).
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct QueueEntry {
    pub kind: CandidateKind,
    pub guaranteed_yield: i64,
    pub guaranteed_impact: f64,
    pub score: f64,
    pub yield_basis: YieldBasis,
    pub reasons: Vec<Reason>,
    pub payload: EntryPayload,
}

/// The assembled queue: its state, the ranked entries, the D6 disclosure count
/// of top-K pairs dropped as value-insensitive (`m = 0`), and the SL-219 §4
/// sizing-debt disclosure (top-K un-sized items NOT covered by a minted probe,
/// plus whether an eligible subject found no estimated target to calibrate
/// against) — disclosed, never gating.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ElicitQueue {
    pub state: QueueState,
    pub entries: Vec<QueueEntry>,
    pub excluded_value_insensitive: usize,
    /// SL-219 §4: top-K un-sized items (no authored estimate, admissible) with
    /// NO minted probe — sizing debt disclosed on the state line, non-gating
    /// (sizing-declined subjects, gauge-masked items, or would-be subjects with
    /// no calibration target).
    pub sizing_residual: usize,
    /// SL-219 §4: a probe-eligible subject existed (un-sized, no est rows) but
    /// no admissible authored-estimate item was available to calibrate against
    /// (fallback tier 2) — drives the "estimate any item to seed sizing" detail.
    pub sizing_no_calibration_target: bool,
}

// ── reason / ask codes (STD-001) ────────────────────────────────────────────

const REASON_FRONTIER_PAIR: &str = "indeterminate-frontier-pair";
const REASON_MEDIAN_PROBE: &str = "median-probe";
const REASON_AGENT_ONLY: &str = "agent-only-calibration";
const REASON_STALE_ANCHOR: &str = "stale-anchor-suspect";
const REASON_SIZING_PROBE: &str = "sizing-probe";
const REASON_CONTESTED_CLAIM: &str = "contested-claim";

const ANSWER_PREFER_A: &str = "prefer-a";
const ANSWER_PREFER_B: &str = "prefer-b";
const ANSWER_EQUAL: &str = "equal";
const ANSWER_INCOMPARABLE: &str = "incomparable";
/// The sizing-probe answer tokens (SL-219 §4): the order-bearing trio plus
/// `incomparable` (which retires the probe). `pub(crate)` so the shell's JSON
/// ask block keys off this ONE definition (STD-001) — a probe stores no
/// `AskSpec`, the tokens are invariant.
pub(crate) const SIZING_PROBE_ANSWERS: &[&str] = &[
    ANSWER_PREFER_A,
    ANSWER_PREFER_B,
    ANSWER_EQUAL,
    ANSWER_INCOMPARABLE,
];
// Anchor-review answer tokens are `pub(crate)` — the elicit JSON surface keys
// each entry's `exits` action list by answer token (design §3), so the shell
// shares this ONE definition rather than restating the strings (STD-001).
pub(crate) const ANSWER_REVISE_ANCHOR: &str = "revise-anchor";
pub(crate) const ANSWER_UPHOLD_ANCHOR: &str = "uphold-anchor";

const MASK_ANNOTATION: &str = "projection masked by bare estimate";
const ANCHOR_YIELD_NOTE: &str = "revise-anchor yield assumes a RESOLVING revision (conflict \
    removed); a still-conflicting value yields nothing and re-surfaces this candidate next \
    refresh. uphold-anchor models retiring the COMPLETE cited closure — real yield may exceed it";

/// The unbounded interval, for a classless frontier item with zero rows
/// (design decision: `PairSide` over its own entity id, Free coupling).
const UNBOUNDED: ValueBounds = ValueBounds {
    lower: Bound::Unbounded,
    upper: Bound::Unbounded,
};

// ── pool items ──────────────────────────────────────────────────────────────

/// A top-K value-sensitive item, resolved against the compiled baseline.
/// Class and interval facts are NOT stored: a [`PairSide`] is resolved per
/// verdict system via [`side_in`] (SL-218 D1).
#[derive(Debug, Clone)]
struct PoolItem {
    id: String,
    kind: String,
    multiplier: f64,
    cost: f64,
    constrained: bool,
    agent_only: bool,
    bare: bool,
}

/// `w == 0` without a `float_cmp` footgun.
fn is_zero(w: f64) -> bool {
    w.abs().total_cmp(&0.0).is_eq()
}

/// The rank-decay weight of a newly-determined pair at better frontier rank `r`
/// (design D13): `w(r) = 1/(1 + decay·r)`, `r` 0-based.
#[expect(
    clippy::as_conversions,
    clippy::cast_precision_loss,
    reason = "frontier ranks are tiny counts, far from f64 precision limits"
)]
fn rank_weight(r: usize, decay: f64) -> f64 {
    1.0 / (1.0 + decay * (r as f64))
}

/// Resolve a class's better (min) 0-based rank among the top-K frontier
/// members that name it; a class with no member in the band ranks at `depth`.
fn class_rank(rank_map: &BTreeMap<ClassId, usize>, class: &ClassId, depth: usize) -> usize {
    rank_map.get(class).copied().unwrap_or(depth)
}

/// The system that issues determinacy verdicts (SL-218 D1): the baseline full
/// system knob-off; the fresh human-rows-only system knob-on. Pool
/// composition, bounds display, projection, and confirm-boost stay on the
/// full system (INV-3) — only `determined()` and its hypothetical diffs move.
struct VerdictSystem<'s, 'a> {
    cs: &'s ConstraintSet,
    reach: &'s Reachability,
    rows: &'s [&'a Judgement],
}

/// Resolve an entity's [`PairSide`] in `cs` — its class, C6 interval, and anchor
/// — carrying the given pre-computed `eff_weight` (design D6: `m_self·c_other`).
/// An entity absent from that system falls back to a singleton class with
/// unbounded interval, so the pair reads indeterminate rather than panicking
/// (SL-218 D1). The SINGLE [`PairSide`] resolver — the elicit queue ([`side_in`])
/// and the PHASE-02 tension grader ([`super::surface`]) both go through it, so
/// grade and queue read one predicate over one system (design F-1/F-7).
pub(crate) fn pair_side(cs: &ConstraintSet, id: &str, eff_weight: f64) -> PairSide {
    let class = cs
        .classes
        .get(id)
        .cloned()
        .unwrap_or_else(|| id.to_string());
    let bounds = cs.bounds.get(&class).copied().unwrap_or(UNBOUNDED);
    let anchor = cs.anchors.get(&class).copied();
    PairSide {
        class,
        eff_weight,
        bounds,
        anchor,
    }
}

/// The pool item's [`PairSide`] against a partner whose cost is `cost_other`
/// (design D6: `eff_weight = m_self · c_other`, built per pair), resolved in
/// `cs` — the verdict system's constraint set.
fn side_in(cs: &ConstraintSet, item: &PoolItem, cost_other: f64) -> PairSide {
    pair_side(cs, &item.id, item.multiplier * cost_other)
}

/// One answer's evaluated determinacy outcome over the relevant pool pairs.
struct AnswerEval {
    yield_delta: i64,
    newly: Vec<(ClassId, ClassId)>,
}

/// The impact of one answer: `Σ w(r)` over its newly-determined pairs (design
/// D13), `r` the better frontier rank in each pair.
fn answer_impact(
    newly: &[(ClassId, ClassId)],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    decay: f64,
) -> f64 {
    newly
        .iter()
        .map(|(ca, cb)| {
            let r = class_rank(rank_map, ca, depth).min(class_rank(rank_map, cb, depth));
            rank_weight(r, decay)
        })
        .sum()
}

/// Reduce an answer set to `(guaranteed_yield, guaranteed_impact)`: the min
/// yield, then the min impact over the answers attaining it (design D13 —
/// worst-case in both count and placement, answer-token invariant).
fn reduce_answers(
    evals: &[AnswerEval],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    decay: f64,
) -> Option<(i64, f64)> {
    let gy = evals.iter().map(|e| e.yield_delta).min()?;
    let gi = evals
        .iter()
        .filter(|e| e.yield_delta == gy)
        .map(|e| answer_impact(&e.newly, rank_map, depth, decay))
        .reduce(|a, b| if a.total_cmp(&b).is_le() { a } else { b })?;
    Some((gy, gi))
}

// ── candidate assembly ──────────────────────────────────────────────────────

/// A ranked candidate before sort: the entry plus its lexicographic tiebreak
/// key (design D13: id-lexicographic tiebreak, `total_cmp` on scores).
struct Candidate {
    sort_key: String,
    entry: QueueEntry,
}

/// Assemble the elicitation queue (design §2). Pure over `inputs`; compiles the
/// baseline internally and rides the `comparison::query` predicates.
pub(crate) fn assemble(inputs: &ElicitInputs<'_>, ctx: DecisionContext) -> ElicitQueue {
    let DecisionContext::Sequencing { depth } = ctx;
    let cs = compile(&inputs.active, &inputs.anchors, QuarantinePolicy::Symmetric);
    let reach = Reachability::build(&cs);
    let counts = constraining_counts_by_class(&cs, &inputs.active);

    // The verdict system (SL-218 D1): knob-on, determinacy is read over a
    // fresh human-rows-only compile (its own C2–C4); knob-off it IS the
    // baseline — no second compile, shipped behaviour bit-for-bit.
    let human = inputs.demote_agent_evidence.then(|| {
        let vcs = compile_human_only(&inputs.active, &inputs.anchors, QuarantinePolicy::Symmetric);
        let vreach = Reachability::build(&vcs);
        (vcs, vreach, human_rows(&inputs.active))
    });
    let verdict = match &human {
        Some((vcs, vreach, vrows)) => VerdictSystem {
            cs: vcs,
            reach: vreach,
            rows: vrows,
        },
        None => VerdictSystem {
            cs: &cs,
            reach: &reach,
            rows: &inputs.active,
        },
    };

    // Top-K frontier band and its class → best-rank map (all members, not just
    // value-sensitive ones — rank is a frontier fact).
    let band: Vec<&FrontierItem> = inputs.frontier.iter().take(depth).collect();
    let rank_map = build_rank_map(&band, &cs);

    // Value-bearing top-K items, split into the value-sensitive pool (m > 0)
    // and the value-insensitive exclusions (m = 0, design D6).
    let mut pool: Vec<PoolItem> = Vec::new();
    let mut value_bearing = 0_usize;
    for item in &band {
        if admissible_value_pair(&item.kind, &item.kind).is_err() {
            continue; // not value-bearing (or a risk): outside the value pool
        }
        let Some(costing) = inputs.costing.get(&item.id) else {
            continue; // no costing: the shell could not price it — skip
        };
        value_bearing += 1;
        if is_zero(costing.multiplier) {
            continue; // value-insensitive: excluded from pool AND stability (D6)
        }
        pool.push(resolve_item(
            item,
            costing,
            &cs,
            &counts,
            &inputs.projection,
        ));
    }
    let n_pool = pool.len();
    let excluded_value_insensitive = pairs(value_bearing).saturating_sub(pairs(n_pool));

    // The relevant pair set for every yield: ALL pool pairs (flips counted both
    // directions by `hypothetical_outcome`). Keyed off the VERDICT system's
    // classes — determinacy diffs must live where the verdicts do (SL-218 D1).
    let relevant = relevant_pairs(verdict.cs, &pool);

    let mut candidates: Vec<Candidate> = Vec::new();
    comparison_candidates(
        inputs,
        &pool,
        &verdict,
        &relevant,
        &rank_map,
        depth,
        &mut candidates,
    );
    median_probe_candidates(
        inputs,
        &pool,
        &verdict,
        &relevant,
        &rank_map,
        depth,
        &mut candidates,
    );
    anchor_review_candidates(
        inputs,
        &cs,
        &verdict,
        &relevant,
        &rank_map,
        depth,
        &mut candidates,
    );
    // Source 4 (SL-219 §4): sizing probes over the un-sized top-K band — pure
    // over the est-domain facts, no hypothetical machinery. Returns the
    // sizing-debt disclosure (residual count + no-target flag).
    let (sizing_residual, sizing_no_calibration_target) =
        sizing_probe_candidates(inputs, &band, &mut candidates);
    // Source 5 (SL-220 D14): one reprobe per ANCHORED-tier claim conflict —
    // knob-independent by construction (no `demote_agent_evidence` read).
    claim_reprobe_candidates(inputs, &mut candidates);

    // Rank: score desc via total_cmp, id-lexicographic tiebreak.
    candidates.sort_by(|a, b| {
        b.entry
            .score
            .total_cmp(&a.entry.score)
            .then_with(|| a.sort_key.cmp(&b.sort_key))
    });
    let entries: Vec<QueueEntry> = candidates.into_iter().map(|c| c.entry).collect();

    let state = if !entries.is_empty() {
        QueueState::Candidates
    } else if pool_has_indeterminate(&pool, &verdict) {
        QueueState::Stalled { depth }
    } else {
        QueueState::Stable { depth }
    };

    ElicitQueue {
        state,
        entries,
        excluded_value_insensitive,
        sizing_residual,
        sizing_no_calibration_target,
    }
}

/// `n·(n−1)/2` — the pair count over `n` items.
#[expect(clippy::integer_division, reason = "exact: n·(n−1) is even")]
fn pairs(n: usize) -> usize {
    n.saturating_mul(n.saturating_sub(1)) / 2
}

/// Class → best (min) 0-based frontier rank among the top-K members naming it.
fn build_rank_map(band: &[&FrontierItem], cs: &ConstraintSet) -> BTreeMap<ClassId, usize> {
    let mut out: BTreeMap<ClassId, usize> = BTreeMap::new();
    for (r, item) in band.iter().enumerate() {
        let class = cs
            .classes
            .get(&item.id)
            .cloned()
            .unwrap_or_else(|| item.id.clone());
        out.entry(class)
            .and_modify(|best| *best = (*best).min(r))
            .or_insert(r);
    }
    out
}

/// Resolve a frontier item against the compiled baseline: its class, interval,
/// anchor, constrained/agent-only flags, and bare-estimate mask.
fn resolve_item(
    item: &FrontierItem,
    costing: &ItemCosting,
    cs: &ConstraintSet,
    counts: &BTreeMap<ClassId, crate::comparison::RaterCounts>,
    projection: &Projection,
) -> PoolItem {
    let class = cs
        .classes
        .get(&item.id)
        .cloned()
        .unwrap_or_else(|| item.id.clone());
    let anchor = cs.anchors.get(&class).copied();
    let class_counts = counts.get(&class).copied().unwrap_or_default();
    let constrained = class_counts.total() > 0 || anchor.is_some();
    let agent_only = class_counts.human == 0 && class_counts.agent >= 1;
    let bare = costing.bare_estimate && is_masked(projection.get(&item.id));
    PoolItem {
        id: item.id.clone(),
        kind: item.kind.clone(),
        multiplier: costing.multiplier,
        cost: costing.est_cost,
        constrained,
        agent_only,
        bare,
    }
}

/// The bare-estimate mask applies only over a projected/gauge value (design
/// D17): an authored anchor is exact, not masked.
fn is_masked(projected: Option<&(f64, ValueProvenance)>) -> bool {
    matches!(
        projected,
        Some((_, ValueProvenance::Projected | ValueProvenance::Gauge))
    )
}

/// Every pool pair as a `(PairSide, PairSide)` with per-pair effective
/// weights, resolved in the verdict system's constraint set.
fn relevant_pairs(cs: &ConstraintSet, pool: &[PoolItem]) -> Vec<(PairSide, PairSide)> {
    let mut out = Vec::new();
    for (i, a) in pool.iter().enumerate() {
        for b in pool.iter().skip(i + 1) {
            out.push((side_in(cs, a, b.cost), side_in(cs, b, a.cost)));
        }
    }
    out
}

/// Is any pool pair indeterminate (design D15 stall/stable discriminator)?
fn pool_has_indeterminate(pool: &[PoolItem], verdict: &VerdictSystem<'_, '_>) -> bool {
    for (i, a) in pool.iter().enumerate() {
        for b in pool.iter().skip(i + 1) {
            let (sa, sb) = (
                side_in(verdict.cs, a, b.cost),
                side_in(verdict.cs, b, a.cost),
            );
            if !determined(verdict.reach, &sa, &sb).is_determined() {
                return true;
            }
        }
    }
    false
}

/// Source 1: indeterminate pairs among the *constrained* pool items, behind the
/// capture-admissibility gate. Admission `guaranteed_yield > 0`.
fn comparison_candidates(
    inputs: &ElicitInputs<'_>,
    pool: &[PoolItem],
    verdict: &VerdictSystem<'_, '_>,
    relevant: &[(PairSide, PairSide)],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    out: &mut Vec<Candidate>,
) {
    for (i, a) in pool.iter().enumerate() {
        for b in pool.iter().skip(i + 1) {
            if !a.constrained || !b.constrained {
                continue; // un-constrained items are median-probe's job
            }
            if admissible_value_pair(&a.kind, &b.kind).is_err() {
                continue;
            }
            let (sa, sb) = (
                side_in(verdict.cs, a, b.cost),
                side_in(verdict.cs, b, a.cost),
            );
            if determined(verdict.reach, &sa, &sb).is_determined() {
                continue; // already fixed — nothing to ask
            }
            if let Some(entry) = build_comparison(
                inputs,
                verdict,
                a,
                b,
                relevant,
                rank_map,
                depth,
                REASON_FRONTIER_PAIR,
            ) {
                out.push(entry);
            }
        }
    }
}

/// SL-220 §3 determinacy: does a resolved claim retire this item's
/// calibration probe? Rung 1 (an anchored Pin/Human claim) always — a human
/// ANSWERED, knob-independently (and row-lessly: compile's row-gating drops
/// a row-less anchor from the constraint set, so `constrained` cannot see
/// it — scope R1). Rungs 3–5 (agent/migrated priors, or an unmigrated
/// `[value]` facet) only while `demote_agent_evidence` is off: knob-on they
/// hold a number, not an answer, and the item stays probe-eligible.
fn claim_retired(inputs: &ElicitInputs<'_>, id: &str) -> bool {
    if inputs.claims.anchored.contains_key(id) {
        return true;
    }
    if inputs.demote_agent_evidence {
        return false;
    }
    inputs.claims.priors.contains_key(id) || inputs.facet_valued.contains(id)
}

/// Source 2: one median-probe per un-constrained top-K item, against the
/// projected-median comparable item (design D14). Stateless, heuristic.
/// SL-220 §3: an item whose value is claim-resolved (per [`claim_retired`])
/// needs no calibration probe.
fn median_probe_candidates(
    inputs: &ElicitInputs<'_>,
    pool: &[PoolItem],
    verdict: &VerdictSystem<'_, '_>,
    relevant: &[(PairSide, PairSide)],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    out: &mut Vec<Candidate>,
) {
    for u in pool.iter().filter(|p| !p.constrained) {
        if claim_retired(inputs, &u.id) {
            continue; // valued by claim/facet — no calibration probe (§3)
        }
        let Some(target) = median_target(inputs, pool, u) else {
            continue;
        };
        if let Some(entry) = build_comparison(
            inputs,
            verdict,
            u,
            target,
            relevant,
            rank_map,
            depth,
            REASON_MEDIAN_PROBE,
        ) {
            out.push(entry);
        }
    }
}

/// The comparable item nearest the projected median of `u`'s comparable set —
/// the other pool items with a projection (design D14). Deterministic: ties
/// break to the smaller projected value, then the smaller id.
#[expect(
    clippy::integer_division,
    reason = "median index; integer halving is intended"
)]
fn median_target<'p>(
    inputs: &ElicitInputs<'_>,
    pool: &'p [PoolItem],
    u: &PoolItem,
) -> Option<&'p PoolItem> {
    let mut comparable: Vec<(&PoolItem, f64)> = pool
        .iter()
        .filter(|p| p.id != u.id)
        .filter(|p| admissible_value_pair(&u.kind, &p.kind).is_ok())
        .filter_map(|p| inputs.projection.get(&p.id).map(|&(v, _)| (p, v)))
        .collect();
    if comparable.is_empty() {
        return None;
    }
    comparable.sort_by(|(pa, va), (pb, vb)| va.total_cmp(vb).then_with(|| pa.id.cmp(&pb.id)));
    let mid = comparable.len() / 2;
    let median = comparable.get(mid).map_or(0.0, |&(_, v)| v);
    comparable
        .into_iter()
        .min_by(|(pa, va), (pb, vb)| {
            (va - median)
                .abs()
                .total_cmp(&(vb - median).abs())
                .then_with(|| pa.id.cmp(&pb.id))
        })
        .map(|(p, _)| p)
}

/// Build a comparison-kind candidate (sources 1 and 2 share this): synthetic
/// order-bearing answers, min-over-order-bearing yield, argmin-yield impact,
/// confirm-boost, admission `guaranteed_yield > 0`.
#[expect(
    clippy::too_many_arguments,
    reason = "yield inputs + impact-band context (rank_map, depth) fanned to a private helper"
)]
fn build_comparison(
    inputs: &ElicitInputs<'_>,
    verdict: &VerdictSystem<'_, '_>,
    a: &PoolItem,
    b: &PoolItem,
    relevant: &[(PairSide, PairSide)],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    reason_code: &str,
) -> Option<Candidate> {
    let order_bearing = [
        (ANSWER_PREFER_A, Response::PreferA),
        (ANSWER_PREFER_B, Response::PreferB),
        (ANSWER_EQUAL, Response::Equal),
    ];
    let mut evals: Vec<AnswerEval> = Vec::new();
    let mut yield_by_answer: BTreeMap<String, i64> = BTreeMap::new();
    for (token, response) in order_bearing {
        // The synthetic answer joins the VERDICT system's rows: fresh
        // testimony always constrains — post-filter, its rater is moot.
        let row = synthetic_answer_row(&a.id, &b.id, response);
        let outcome = hypothetical_outcome(
            verdict.reach,
            verdict.rows,
            &inputs.anchors,
            &Hypothetical::Answer(Box::new(row)),
            relevant,
        );
        yield_by_answer.insert(token.to_string(), outcome.yield_delta());
        evals.push(AnswerEval {
            yield_delta: outcome.yield_delta(),
            newly: outcome.newly_determined,
        });
    }
    // `incomparable` is structurally 0 — disclosed, excluded from the min (D11).
    yield_by_answer.insert(ANSWER_INCOMPARABLE.to_string(), 0);

    let (gy, gi) = reduce_answers(&evals, rank_map, depth, inputs.rank_decay)?;
    if gy <= 0 {
        return None; // admission: yield-motivated sources need positive yield
    }
    let boost = if a.agent_only && b.agent_only {
        inputs.confirm_boost
    } else {
        1.0
    };
    let score = i64_as_f64(gy) * gi * boost;

    let mut reasons = vec![Reason {
        code: reason_code.to_string(),
        text: comparison_reason_text(reason_code),
    }];
    if boost.total_cmp(&1.0).is_gt() {
        reasons.push(Reason {
            code: REASON_AGENT_ONLY.to_string(),
            text: "both items currently calibrated only by agent evidence".to_string(),
        });
    }

    let ask = AskSpec {
        answers: vec![
            ANSWER_PREFER_A,
            ANSWER_PREFER_B,
            ANSWER_EQUAL,
            ANSWER_INCOMPARABLE,
        ],
        yield_by_answer,
        yield_note: None,
    };
    let payload = EntryPayload::Comparison {
        a: participant(a),
        b: participant(b),
        ask,
    };
    let (lo, hi) = if a.id <= b.id {
        (&a.id, &b.id)
    } else {
        (&b.id, &a.id)
    };
    Some(Candidate {
        sort_key: format!("cmp:{lo}:{hi}"),
        entry: QueueEntry {
            kind: CandidateKind::Comparison,
            guaranteed_yield: gy,
            guaranteed_impact: gi,
            score,
            yield_basis: YieldBasis::OrderBearingAnswers,
            reasons,
            payload,
        },
    })
}

fn comparison_reason_text(code: &str) -> String {
    if code == REASON_MEDIAN_PROBE {
        "un-constrained item — calibrate against the projected median of its comparable set"
            .to_string()
    } else {
        "an indeterminate value_dim order between two top-K frontier items".to_string()
    }
}

fn participant(item: &PoolItem) -> Participant {
    let mut annotations = Vec::new();
    if item.bare {
        annotations.push(MASK_ANNOTATION.to_string());
    }
    Participant {
        id: item.id.clone(),
        annotations,
    }
}

/// Source 3: one candidate per distinct suspect anchor in an `AnchorConflict`
/// quarantine pair (design D12). Admits on EXISTENCE; yield = min over the two
/// resolving outcomes (revise-as-removal, uphold-as-rows-retired); NOT K-gated.
fn anchor_review_candidates(
    inputs: &ElicitInputs<'_>,
    cs: &ConstraintSet,
    verdict: &VerdictSystem<'_, '_>,
    relevant: &[(PairSide, PairSide)],
    rank_map: &BTreeMap<ClassId, usize>,
    depth: usize,
    out: &mut Vec<Candidate>,
) {
    // Suspects come from the FULL system's quarantine diagnostics (the pool
    // stays full-system, SL-218 D1); only the yield evaluation — a
    // determinacy diff — moves to the verdict system.
    for suspect in suspect_anchors(cs, &inputs.anchors) {
        let rows = rows_citing(cs, &suspect);
        let removed = hypothetical_outcome(
            verdict.reach,
            verdict.rows,
            &inputs.anchors,
            &Hypothetical::AnchorRemoved(&suspect),
            relevant,
        );
        let retired = hypothetical_outcome(
            verdict.reach,
            verdict.rows,
            &inputs.anchors,
            &Hypothetical::RowsRetired(&rows),
            relevant,
        );
        let revise_yield = removed.yield_delta();
        let uphold_yield = retired.yield_delta();
        let evals = [
            AnswerEval {
                yield_delta: revise_yield,
                newly: removed.newly_determined,
            },
            AnswerEval {
                yield_delta: uphold_yield,
                newly: retired.newly_determined,
            },
        ];
        let Some((gy, gi)) = reduce_answers(&evals, rank_map, depth, inputs.rank_decay) else {
            continue;
        };
        // Existence admission (D15): a suspect stays on the queue whatever its
        // yield — zero-yield suspects sink to the bottom, never vanish.
        let score = i64_as_f64(gy).max(0.0) * gi;

        let mut yield_by_answer = BTreeMap::new();
        yield_by_answer.insert(ANSWER_REVISE_ANCHOR.to_string(), revise_yield);
        yield_by_answer.insert(ANSWER_UPHOLD_ANCHOR.to_string(), uphold_yield);

        let subject = AnchorSubject {
            id: suspect.clone(),
            anchor: inputs.anchors.get(&suspect).copied(),
            conflict_pairs: conflict_pairs_for(cs, &suspect),
            quarantined_rows: rows.iter().cloned().collect(),
        };
        let ask = AskSpec {
            answers: vec![ANSWER_REVISE_ANCHOR, ANSWER_UPHOLD_ANCHOR],
            yield_by_answer,
            yield_note: Some(ANCHOR_YIELD_NOTE.to_string()),
        };
        out.push(Candidate {
            sort_key: format!("anc:{suspect}"),
            entry: QueueEntry {
                kind: CandidateKind::AnchorReview,
                guaranteed_yield: gy,
                guaranteed_impact: gi,
                score,
                yield_basis: YieldBasis::CanonicalResolvingActions,
                reasons: vec![Reason {
                    code: REASON_STALE_ANCHOR.to_string(),
                    text: format!("anchor on {suspect} sits on a quarantined conflict path"),
                }],
                payload: EntryPayload::AnchorReview { subject, ask },
            },
        });
    }
}

/// The distinct anchored entities named (directly, or via a class-id token) in
/// any `AnchorConflict` quarantine pair (design D12; notes: resolve class-id
/// tokens to their anchored member via the `AnchorMap`).
fn suspect_anchors(cs: &ConstraintSet, anchors: &AnchorMap) -> Vec<String> {
    let mut out: BTreeSet<String> = BTreeSet::new();
    for reason in cs.quarantined.values() {
        if let QuarantineReason::AnchorConflict { pairs } = reason {
            for (x, y) in pairs {
                for token in [x, y] {
                    if let Some(entity) = resolve_anchored(token, anchors, cs) {
                        out.insert(entity);
                    }
                }
            }
        }
    }
    out.into_iter().collect()
}

/// Resolve a conflict-pair token to the anchored entity it names: a direct
/// `AnchorMap` key (C2 member tokens), else the anchored member of the class it
/// names (C4 class-id tokens).
fn resolve_anchored(token: &str, anchors: &AnchorMap, cs: &ConstraintSet) -> Option<String> {
    if anchors.contains_key(token) {
        return Some(token.to_string());
    }
    cs.classes
        .iter()
        .find(|(entity, class)| class.as_str() == token && anchors.contains_key(*entity))
        .map(|(entity, _)| entity.clone())
}

/// Every row uid whose `AnchorConflict` quarantine entry cites `suspect`
/// (design D12: the complete cited closure, deliberately pessimistic).
fn rows_citing(cs: &ConstraintSet, suspect: &str) -> BTreeSet<RowUid> {
    let mut out = BTreeSet::new();
    for (uid, reason) in &cs.quarantined {
        if let QuarantineReason::AnchorConflict { pairs } = reason
            && pairs
                .iter()
                .any(|(x, y)| cites(x, suspect, cs) || cites(y, suspect, cs))
        {
            out.insert(uid.clone());
        }
    }
    out
}

/// Does conflict token `token` name `suspect` — directly, or as the class of
/// the suspect entity?
fn cites(token: &str, suspect: &str, cs: &ConstraintSet) -> bool {
    token == suspect || cs.classes.get(suspect).is_some_and(|c| c.as_str() == token)
}

/// The conflict pairs any quarantine entry citing `suspect` records (display).
fn conflict_pairs_for(cs: &ConstraintSet, suspect: &str) -> Vec<(String, String)> {
    let mut out: BTreeSet<(String, String)> = BTreeSet::new();
    for reason in cs.quarantined.values() {
        if let QuarantineReason::AnchorConflict { pairs } = reason {
            for (x, y) in pairs {
                if cites(x, suspect, cs) || cites(y, suspect, cs) {
                    out.insert((x.clone(), y.clone()));
                }
            }
        }
    }
    out.into_iter().collect()
}

/// Source 4 (SL-219 §4): one sizing probe per un-sized top-K subject, driving a
/// deterministic `more-work` session against the median authored-estimate
/// target. Existence-admitted, never yield-ranked (`score 0`, `yield_basis`
/// Calibration) — no hypothetical machinery runs. Returns `(residual,
/// no_calibration_target)`: the count of top-K un-sized items NOT covered by a
/// minted probe (disclosed sizing debt, non-gating), and whether a probe-
/// eligible subject found no estimated target (fallback tier 2).
///
/// Subject predicate (exact, §4): admissible kind AND no authored estimate
/// (`bare_estimate`) AND zero est-domain rows (`est_evidenced` absent — an
/// `incomparable` row lands there and retires the probe; gauge members carry
/// est rows and fall out here too). One probe per subject. The target
/// (`sizing_target`) is shared across every probe — a corpus-level median.
fn sizing_probe_candidates(
    inputs: &ElicitInputs<'_>,
    band: &[&FrontierItem],
    out: &mut Vec<Candidate>,
) -> (usize, bool) {
    let target = sizing_target(inputs, band);
    let mut unsized_count = 0_usize;
    let mut minted = 0_usize;
    let mut eligible_uncalibrated = false;
    for item in band {
        if admissible_estimate_pair(&item.kind, &item.kind).is_err() {
            continue; // kind carries no comparable settle-cost
        }
        // No authored estimate ⇒ un-sized. An item the shell could not price is
        // not a probe subject (nothing to reason about).
        let Some(costing) = inputs.costing.get(&item.id) else {
            continue;
        };
        if !costing.bare_estimate {
            continue; // already sized (authored estimate)
        }
        unsized_count += 1;
        if inputs.sizing.est_evidenced.contains(&item.id) {
            continue; // est rows present (declined / gauge) — residual, disclosed
        }
        let Some(target) = &target else {
            eligible_uncalibrated = true; // no estimated item to calibrate against
            continue;
        };
        out.push(sizing_probe(inputs, item, target));
        minted += 1;
    }
    (unsized_count.saturating_sub(minted), eligible_uncalibrated)
}

/// The deterministic calibration target (SL-219 §4): the median-cost item among
/// top-K items WITH anchored-tier estimate claims (even count → lower-cost
/// middle; ties id-lexicographic). Fallback tier 1: none in top-K → the median
/// over ALL anchored-tier estimate-claimed items. Tier 2: none anywhere →
/// `None` (the caller discloses "estimate any item to seed sizing").
///
/// E10 postcondition: ONLY items with an anchored-tier estimate claim (Pin/
/// Human) are valid targets — a facet-only or agent/migrated-only item is NOT.
/// The shell's `estimated_costs` includes the full authored-cost pool; this
/// function further filters to only those items also present in
/// `estimate_anchored_targets`. NEVER a projected- or gauge-costed item.
fn sizing_target(inputs: &ElicitInputs<'_>, band: &[&FrontierItem]) -> Option<SizingTarget> {
    let anchored = &inputs.sizing.estimate_anchored_targets;
    let costs = &inputs.sizing.estimated_costs;
    let in_band: Vec<(&String, f64)> = band
        .iter()
        .filter(|f| anchored.contains(&f.id))
        .filter_map(|f| costs.get_key_value(&f.id).map(|(id, &c)| (id, c)))
        .collect();
    let tier_fn = |id: &str| -> String {
        inputs
            .claims
            .anchored
            .get(id)
            .map(|c| match c.tier {
                ClaimTier::Pin => "pin".to_string(),
                ClaimTier::Human => "human claim".to_string(),
                ClaimTier::Agent => "agent claim".to_string(),
                ClaimTier::Migrated => "migrated claim".to_string(),
            })
            .unwrap_or_default()
    };
    if in_band.is_empty() {
        let corpus: Vec<(&String, f64)> = costs
            .iter()
            .filter(|(id, _)| anchored.contains(*id))
            .map(|(id, &c)| (id, c))
            .collect();
        median_by_cost(corpus, tier_fn)
    } else {
        median_by_cost(in_band, tier_fn)
    }
}

/// The lower-middle median of `(id, cost)` by ascending `(cost, id)` (SL-219 §4:
/// even count → lower-cost middle; ties id-lexicographic). `tier_label` is a
/// function that resolves an entity id to its claim tier label for the probe
/// reason text (SL-222 PHASE-07).
#[expect(
    clippy::integer_division,
    reason = "median index; integer halving is intended (lower-middle)"
)]
fn median_by_cost(
    mut items: Vec<(&String, f64)>,
    tier_fn: impl Fn(&str) -> String,
) -> Option<SizingTarget> {
    if items.is_empty() {
        return None;
    }
    items.sort_by(|(ia, ca), (ib, cb)| ca.total_cmp(cb).then_with(|| ia.cmp(ib)));
    let mid = (items.len() - 1) / 2; // lower-middle for even n, exact middle for odd
    items.get(mid).map(|&(id, cost)| SizingTarget {
        id: id.clone(),
        estimate: cost,
        tier_label: tier_fn(id.as_str()),
    })
}

/// Build one sizing-probe candidate (SL-219 §4): a lean subject sized against
/// the shared `target`, pinned at zero yield/impact/score with the Calibration
/// basis. Sort key `siz:{id}` sinks probes below every yield-motivated entry
/// (positive score) and orders probes among themselves by subject id.
fn sizing_probe(
    inputs: &ElicitInputs<'_>,
    item: &FrontierItem,
    target: &SizingTarget,
) -> Candidate {
    let mut annotations = Vec::new();
    if is_masked(inputs.projection.get(&item.id)) {
        annotations.push(MASK_ANNOTATION.to_string());
    }
    let subject = Participant {
        id: item.id.clone(),
        annotations,
    };
    Candidate {
        sort_key: format!("siz:{}", item.id),
        entry: QueueEntry {
            kind: CandidateKind::SizingProbe,
            guaranteed_yield: 0,
            guaranteed_impact: 0.0,
            score: 0.0,
            yield_basis: YieldBasis::Calibration,
            reasons: vec![Reason {
                code: REASON_SIZING_PROBE.to_string(),
                text: format!(
                    "un-sized top-K item — calibrate its cost against {} ({} backing)",
                    target.id, target.tier_label
                ),
            }],
            payload: EntryPayload::SizingProbe {
                subject,
                target: target.clone(),
            },
        },
    }
}

/// Source 5 (SL-220 D14): one reprobe candidate per ANCHORED-tier claim
/// conflict — "the humans must talk" (the stale-anchor existence precedent:
/// admitted on existence, NOT K-gated, never yield-ranked). Tier-gated
/// through the ONE predicate [`ClaimFinding::nominates_reprobe`], so
/// agent/migrated conflicts — ordinary calibrate-via-comparison findings —
/// can NEVER enter the human queue; and KNOB-INDEPENDENT by construction
/// (no `demote_agent_evidence` read anywhere on this path). Score 0: the
/// entry sinks below every yield-motivated entry (the sizing-probe
/// precedent) but never vanishes.
fn claim_reprobe_candidates(inputs: &ElicitInputs<'_>, out: &mut Vec<Candidate>) {
    for finding in &inputs.claims.findings {
        if !finding.nominates_reprobe() {
            continue; // D14: agent/migrated conflicts never reach the queue
        }
        let ClaimFinding::Conflict {
            item,
            tier,
            low,
            high,
            distinct,
            rows,
            ..
        } = finding;
        let contested = match tier {
            ClaimTier::Pin => "contested pin",
            _ => "contested human claims",
        };
        out.push(Candidate {
            sort_key: format!("clm:{item}"),
            entry: QueueEntry {
                kind: CandidateKind::ClaimReprobe,
                guaranteed_yield: 0,
                guaranteed_impact: 0.0,
                score: 0.0,
                yield_basis: YieldBasis::Calibration,
                reasons: vec![Reason {
                    code: REASON_CONTESTED_CLAIM.to_string(),
                    text: format!(
                        "{contested} on {item}{distinct} distinct magnitudes \
                         ({low}{high}) over {rows} rows; resolve by superseding row"
                    ),
                }],
                payload: EntryPayload::ClaimReprobe {
                    subject: item.clone(),
                    tier: *tier,
                    mean: inputs
                        .claims
                        .anchored
                        .get(item)
                        .map_or(0.0, |claim| claim.operative),
                    low: *low,
                    high: *high,
                    distinct: *distinct,
                    rows: *rows,
                },
            },
        });
    }
}

/// `i64 → f64` for the score product (yields are tiny counts).
#[expect(
    clippy::as_conversions,
    clippy::cast_precision_loss,
    reason = "guaranteed yields are small determinacy counts, exact in f64"
)]
fn i64_as_f64(v: i64) -> f64 {
    v as f64
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::comparison::{DOMAIN_VALUE, FRAME_EQUAL_EFFORT, RaterKind, RowForm};

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

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

    fn win(uid: &str, w: &str, l: &str) -> Judgement {
        jrow(uid, w, l, Response::PreferA, RaterKind::Human)
    }
    fn win_agent(uid: &str, w: &str, l: &str) -> Judgement {
        jrow(uid, w, l, Response::PreferA, RaterKind::Agent)
    }

    /// Build inputs; every frontier item is kind `IMP` (value-bearing),
    /// `bare_estimate = false`, `rank_decay = 1.0`, `confirm_boost = 1.5`.
    fn mk<'a>(
        active: Vec<&'a Judgement>,
        anchors: &[(&str, f64)],
        frontier: &[&str],
        costing: &[(&str, f64, f64)],
        projection: &[(&str, f64, ValueProvenance)],
    ) -> ElicitInputs<'a> {
        ElicitInputs {
            active,
            anchors: anchors.iter().map(|&(e, v)| (e.to_string(), v)).collect(),
            frontier: frontier
                .iter()
                .map(|&id| FrontierItem {
                    id: id.to_string(),
                    kind: "IMP".to_string(),
                })
                .collect(),
            costing: costing
                .iter()
                .map(|&(id, m, c)| {
                    (
                        id.to_string(),
                        ItemCosting {
                            multiplier: m,
                            est_cost: c,
                            bare_estimate: false,
                        },
                    )
                })
                .collect(),
            projection: projection
                .iter()
                .map(|&(id, v, p)| (id.to_string(), (v, p)))
                .collect(),
            rank_decay: 1.0,
            confirm_boost: 1.5,
            demote_agent_evidence: false,
            sizing: SizingInputs::default(),
            claims: ClaimResolution::default(),
            facet_valued: BTreeSet::new(),
        }
    }

    /// Build a [`SizingInputs`] from `(id, authored_est_cost)` target candidates
    /// and est-evidenced ids — the two pure signals the shell derives.
    fn sizing(estimated: &[(&str, f64)], evidenced: &[&str]) -> SizingInputs {
        let anchored: std::collections::BTreeSet<String> =
            estimated.iter().map(|&(id, _)| id.to_string()).collect();
        SizingInputs {
            estimated_costs: estimated
                .iter()
                .map(|&(id, c)| (id.to_string(), c))
                .collect(),
            est_evidenced: evidenced.iter().map(|&s| s.to_string()).collect(),
            estimate_anchored_targets: anchored,
        }
    }

    fn seq(depth: usize) -> DecisionContext {
        DecisionContext::Sequencing { depth }
    }

    // ---- VT-4: state machine (QueueState / Stalled / Stable) --------------------

    #[test]
    fn indeterminate_constrained_pair_is_a_comparison_candidate() {
        // A>C, B>D: A, B both constrained, order-incomparable, unbounded ⇒ the
        // (A, B) value_dim order is open ⇒ one comparison candidate; state
        // Candidates.
        let rows = vec![win("j0", "A", "C"), win("j1", "B", "D")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(2));
        assert_eq!(q.state, QueueState::Candidates);
        assert_eq!(q.entries.len(), 1);
        assert_eq!(q.entries[0].kind, CandidateKind::Comparison);
        assert!(q.entries[0].guaranteed_yield >= 1);
    }

    /// RV-278 F-6 through `assemble` (SL-220 design §2): an anchor-bearing
    /// ledger and its anchor-free twin — fed through the store pipeline's
    /// PAIRWISE view — recompile to an IDENTICAL baseline `ConstraintSet`
    /// and an identical queue. Anchor rows reach no compile consumer, and
    /// the proof is non-vacuous: the queue carries a real candidate.
    #[test]
    fn assemble_baseline_ignores_anchor_rows_via_the_pairwise_view() {
        use crate::comparison::{
            AnchorMap, COMPARISON_SCHEMA, COMPARISON_VERSION, ComparisonSession,
            FRAME_VALUE_ANCHOR, SessionHeader, StatusMap, VALUE_PROJECTION_PARAMS,
            pipeline_from_sessions,
        };
        let session_of = |judgements: Vec<Judgement>| ComparisonSession {
            schema: COMPARISON_SCHEMA.to_string(),
            version: COMPARISON_VERSION,
            session: SessionHeader {
                uid: "s1".to_string(),
                date: "2026-07-12".to_string(),
                audience: None,
            },
            judgements,
            tombstones: Vec::new(),
        };
        let anchor = || {
            let mut j = jrow("anch", "A", "unused", Response::PreferA, RaterKind::Human);
            j.b = None;
            j.response = None;
            j.form = RowForm::Anchor;
            j.frame = FRAME_VALUE_ANCHOR.to_string();
            j.magnitude = Some(6.0);
            j
        };
        let pipeline_of = |judgements: Vec<Judgement>| {
            pipeline_from_sessions(
                &[session_of(judgements)],
                &StatusMap::new(),
                &AnchorMap::new(),
                &VALUE_PROJECTION_PARAMS,
                &VALUE_PROJECTION_PARAMS,
                &std::collections::BTreeMap::new(),
                1.0,
                0.65,
            )
            .expect("pipeline ok")
        };
        let with_anchor = pipeline_of(vec![win("j0", "A", "C"), win("j1", "B", "D"), anchor()]);
        let without_anchor = pipeline_of(vec![win("j0", "A", "C"), win("j1", "B", "D")]);
        assert!(
            !with_anchor.value_claims.anchored.is_empty(),
            "non-vacuous: the claim was captured"
        );

        fn inputs_of(p: &crate::comparison::Pipeline) -> ElicitInputs<'_> {
            mk(
                p.active_pairwise().iter().collect(),
                &[],
                &["A", "B"],
                &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
                &[],
            )
        }
        let inputs_with = inputs_of(&with_anchor);
        let inputs_without = inputs_of(&without_anchor);
        // The baseline `assemble` recompiles (its first act) is identical…
        assert_eq!(
            compile(
                &inputs_with.active,
                &inputs_with.anchors,
                QuarantinePolicy::Symmetric
            ),
            compile(
                &inputs_without.active,
                &inputs_without.anchors,
                QuarantinePolicy::Symmetric
            ),
            "anchor rows never reach the assemble baseline compile"
        );
        // …and so is the whole assembled queue, non-vacuously.
        let q_with = assemble(&inputs_with, seq(2));
        assert_eq!(q_with, assemble(&inputs_without, seq(2)));
        assert_eq!(q_with.entries.len(), 1, "a real candidate rode the proof");
    }

    #[test]
    fn all_determined_pool_no_suspects_is_stable() {
        // A(5) and B(3) both anchored (consistent chain over C=0): the pair is
        // point-determined; no suspects, no un-constrained items ⇒ Stable.
        let rows = vec![win("j0", "A", "C"), win("j1", "B", "C")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("A", 5.0), ("B", 3.0), ("C", 0.0)],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(2));
        assert_eq!(q.state, QueueState::Stable { depth: 2 });
        assert!(q.entries.is_empty());
    }

    #[test]
    fn zero_yield_bridge_drops_admission_and_stalls() {
        // T(5) > A,B > L(-5): A, B both span (-5, 5). With differing costs the
        // pair objective 2·v_A − v_B stays sign-mixed under EVERY order-bearing
        // answer (negative domain), so guaranteed yield is 0 ⇒ admission drops
        // the candidate ⇒ no entries, but the pair is still indeterminate ⇒
        // Stalled, never Stable (D15 zero-yield bridge; RV-269 admission).
        let rows = vec![
            win("j0", "T", "A"),
            win("j1", "A", "L"),
            win("j2", "T", "B"),
            win("j3", "B", "L"),
        ];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("T", 5.0), ("L", -5.0)],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 2.0)],
            &[],
        );
        let q = assemble(&inputs, seq(2));
        assert!(q.entries.is_empty(), "zero-yield candidate not admitted");
        assert_eq!(q.state, QueueState::Stalled { depth: 2 });
    }

    // ---- VT-3: ranking (confirm_boost / guaranteed_impact / argmin) -------------

    #[test]
    fn confirm_boost_agent_only_outranks_human_touched() {
        // The SAME structural pair: agent-only evidence earns the boost, human
        // evidence does not; score_agent = confirm_boost × score_human, and the
        // agent case discloses the agent-only-calibration reason.
        let agent_rows = vec![win_agent("j0", "A", "C"), win_agent("j1", "B", "D")];
        let human_rows = vec![win("j0", "A", "C"), win("j1", "B", "D")];
        let a_refs: Vec<&Judgement> = agent_rows.iter().collect();
        let h_refs: Vec<&Judgement> = human_rows.iter().collect();
        let cost = [("A", 1.0, 1.0), ("B", 1.0, 1.0)];
        let qa = assemble(&mk(a_refs.clone(), &[], &["A", "B"], &cost, &[]), seq(2));
        let qh = assemble(&mk(h_refs.clone(), &[], &["A", "B"], &cost, &[]), seq(2));
        let sa = qa.entries[0].score;
        let sh = qh.entries[0].score;
        assert!(sa > sh, "agent-only outranks human-touched");
        assert!(
            (sa - sh * 1.5).abs() < 1e-9,
            "score scales by confirm_boost"
        );
        assert!(
            qa.entries[0]
                .reasons
                .iter()
                .any(|r| r.code == "agent-only-calibration"),
            "agent case discloses the boost reason"
        );
        assert!(
            qh.entries[0]
                .reasons
                .iter()
                .all(|r| r.code != "agent-only-calibration"),
            "human case claims no boost"
        );
    }

    #[test]
    fn guaranteed_impact_is_min_over_argmin_yield_answers() {
        // RV-269 F-2: two answers tie on the min yield (1) but close pairs at
        // different frontier ranks — prefer-a a rank-0 pair (impact 1.0),
        // prefer-b a rank-1 pair (impact 0.5); guaranteed_impact is the WORSE
        // (min) of the argmin-yield answers = 0.5. A higher-yield answer is
        // excluded from the argmin set.
        let rank_map: BTreeMap<ClassId, usize> = [("A", 0usize), ("B", 1), ("C", 2)]
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect();
        let evals = vec![
            AnswerEval {
                yield_delta: 1,
                newly: vec![("A".to_string(), "B".to_string())],
            },
            AnswerEval {
                yield_delta: 1,
                newly: vec![("B".to_string(), "C".to_string())],
            },
            AnswerEval {
                yield_delta: 2,
                newly: vec![
                    ("A".to_string(), "B".to_string()),
                    ("B".to_string(), "C".to_string()),
                ],
            },
        ];
        let (gy, gi) = reduce_answers(&evals, &rank_map, 3, 1.0).unwrap();
        assert_eq!(gy, 1);
        assert!((gi - 0.5).abs() < 1e-9, "min over argmin-yield answers");
    }

    #[test]
    fn rank_weight_decays_monotonically() {
        assert!((rank_weight(0, 1.0) - 1.0).abs() < 1e-9);
        assert!(rank_weight(0, 1.0) > rank_weight(1, 1.0));
        assert!(rank_weight(1, 1.0) > rank_weight(2, 1.0));
    }

    #[test]
    fn value_insensitive_zero_multiplier_excluded_and_counted() {
        // A, B, Z all value-bearing, constrained, pairwise indeterminate; Z has
        // m = 0 ⇒ excluded from the pool AND the stability obligation, and the
        // dropped pairs (A,Z),(B,Z) are disclosed. Only (A,B) survives.
        let rows = vec![
            win("j0", "A", "P"),
            win("j1", "B", "Q"),
            win("j2", "Z", "R"),
        ];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[],
            &["A", "B", "Z"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0), ("Z", 0.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(3));
        assert_eq!(q.excluded_value_insensitive, 2, "pairs (A,Z),(B,Z) dropped");
        assert_eq!(q.entries.len(), 1);
        for e in &q.entries {
            if let EntryPayload::Comparison { a, b, .. } = &e.payload {
                assert!(a.id != "Z" && b.id != "Z", "Z never surfaces");
            }
        }
    }

    #[test]
    fn entries_sorted_by_score_then_id() {
        // Two independent stale-anchor suspects (A, C) both score 0 ⇒ the id
        // tiebreak orders `anc:A` before `anc:C`.
        let rows = vec![win("j0", "A", "B"), win("j1", "B", "C")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("A", 1.0), ("C", 3.0)],
            &["A", "B", "C"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0), ("C", 1.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(3));
        // Scores are non-increasing.
        for w in q.entries.windows(2) {
            assert!(w[0].score >= w[1].score - 1e-12);
        }
        let subjects: Vec<&str> = q
            .entries
            .iter()
            .filter_map(|e| match &e.payload {
                EntryPayload::AnchorReview { subject, .. } => Some(subject.id.as_str()),
                EntryPayload::Comparison { .. }
                | EntryPayload::SizingProbe { .. }
                | EntryPayload::ClaimReprobe { .. } => None,
            })
            .collect();
        assert_eq!(subjects, vec!["A", "C"], "id-lexicographic tiebreak");
    }

    // ---- VT-1: reprobe / anchor-review (AnchorReview / assemble / resolving) -----

    #[test]
    fn anchor_review_min_over_resolving_uphold_below_removal() {
        // A(1) > B > C(3): the stale A=1 anchor sterilises the A>B>C closure.
        // For suspect A: revise (AnchorRemoved) reactivates two pairs (+2);
        // uphold (RowsRetired of the complete cited closure) retires the ONLY
        // rows A and C have, so their anchors drop and the anchored (A,C) pair
        // reopens — a real −1 (negative deltas are honest, D10). The guaranteed
        // yield is the MIN over resolving answers = −1 (uphold < removal),
        // disclosed per answer with the conditional-yield note.
        let rows = vec![win("j0", "A", "B"), win("j1", "B", "C")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("A", 1.0), ("C", 3.0)],
            &["A", "B", "C"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0), ("C", 1.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(3));
        let subject_a = q
            .entries
            .iter()
            .find(|e| matches!(&e.payload, EntryPayload::AnchorReview { subject, .. } if subject.id == "A"))
            .expect("an anchor-review candidate for suspect A");
        assert_eq!(subject_a.kind, CandidateKind::AnchorReview);
        assert_eq!(subject_a.yield_basis, YieldBasis::CanonicalResolvingActions);
        assert_eq!(
            subject_a.guaranteed_yield, -1,
            "min over resolving = uphold"
        );
        if let EntryPayload::AnchorReview { ask, .. } = &subject_a.payload {
            assert_eq!(ask.yield_by_answer.get("revise-anchor"), Some(&2));
            assert_eq!(ask.yield_by_answer.get("uphold-anchor"), Some(&-1));
            assert!(ask.yield_note.is_some(), "conditional-yield disclosure");
        } else {
            panic!("expected anchor-review payload");
        }
    }

    #[test]
    fn anchor_review_not_k_gated_and_keeps_determined_pool_as_candidates() {
        // Top-K frontier [P, Q] is fully determined (both anchored, consistent).
        // A separate stale-anchor conflict on R(1) > S(3) — entities OUTSIDE the
        // top-K — still raises anchor-review candidates (not K-gated), and the
        // queue stays Candidates despite the determined pool (D15 precedence).
        let rows = vec![
            win("j0", "P", "Pl"),
            win("j1", "Q", "Ql"),
            win("j2", "R", "S"),
        ];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("P", 5.0), ("Q", 3.0), ("R", 1.0), ("S", 3.0)],
            &["P", "Q"],
            &[("P", 1.0, 1.0), ("Q", 1.0, 1.0)],
            &[],
        );
        let q = assemble(&inputs, seq(2));
        assert_eq!(q.state, QueueState::Candidates, "suspect keeps Candidates");
        assert!(
            q.entries.iter().any(
                |e| matches!(&e.payload, EntryPayload::AnchorReview { subject, .. }
                    if subject.id == "R" || subject.id == "S")
            ),
            "suspect outside top-K still admits (not K-gated)"
        );
    }

    // ---- VT-2: median-probe (median_probe) --------------------------------------

    #[test]
    fn median_probe_surfaces_for_unconstrained_item() {
        // U has zero constraining rows and no anchor; W is constrained and
        // carries a projection. U yields ONE median-probe candidate against the
        // projected-median comparable (W), reason `median-probe` — not the full
        // fan of pairs.
        let rows = vec![win("j0", "W", "Z")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let inputs = mk(
            refs.clone(),
            &[("Z", 0.0)],
            &["U", "W"],
            &[("U", 1.0, 1.0), ("W", 1.0, 1.0)],
            &[
                ("U", 2.0, ValueProvenance::Projected),
                ("W", 3.0, ValueProvenance::Projected),
            ],
        );
        let q = assemble(&inputs, seq(2));
        let probe = q
            .entries
            .iter()
            .find(|e| e.reasons.iter().any(|r| r.code == "median-probe"))
            .expect("a median-probe candidate");
        assert_eq!(probe.kind, CandidateKind::Comparison);
        assert!(probe.guaranteed_yield > 0);
        if let EntryPayload::Comparison { a, b, .. } = &probe.payload {
            let ids = [a.id.as_str(), b.id.as_str()];
            assert!(ids.contains(&"U") && ids.contains(&"W"));
        } else {
            panic!("expected comparison payload");
        }
    }

    // ---- SL-218 PHASE-01 D7: demotion knob (design INV-2 / VT-B unit level) -----

    #[test]
    fn demote_reopens_agent_only_determined_pair() {
        // One agent row A>B determines the pair in the full system. Knob-on,
        // determinacy verdicts come from the human-rows-only system: the pair
        // reads indeterminate, re-enters the queue as a comparison candidate
        // (VT-F seed), and the queue state follows.
        let rows = vec![win_agent("g0", "A", "B")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs.clone(),
            &[],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
            &[],
        );

        let off = assemble(&inputs, seq(2));
        assert_eq!(
            off.state,
            QueueState::Stable { depth: 2 },
            "knob-off: the agent row retires the pair"
        );
        assert!(off.entries.is_empty());

        inputs.demote_agent_evidence = true;
        let on = assemble(&inputs, seq(2));
        assert_eq!(
            on.state,
            QueueState::Candidates,
            "knob-on: agent evidence proposes, never retires (INV-2)"
        );
        assert_eq!(on.entries.len(), 1);
        assert_eq!(on.entries[0].kind, CandidateKind::Comparison);
        assert!(
            on.entries[0].guaranteed_yield >= 1,
            "a fresh answer closes the pair in the human system"
        );
    }

    #[test]
    fn anchored_pair_stays_determined_both_knob_states() {
        // Authored anchors are human authority (design D6: point constraints,
        // no special case). A human row names both entities so classes exist
        // in both systems; the anchored order reads determined either way.
        let rows = vec![jrow(
            "h0",
            "A",
            "B",
            Response::Incomparable,
            RaterKind::Human,
        )];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs.clone(),
            &[("A", 2.0), ("B", 1.0)],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
            &[],
        );

        let off = assemble(&inputs, seq(2));
        assert_eq!(off.state, QueueState::Stable { depth: 2 });
        assert!(off.entries.is_empty());

        inputs.demote_agent_evidence = true;
        let on = assemble(&inputs, seq(2));
        assert_eq!(
            on.state,
            QueueState::Stable { depth: 2 },
            "knob-on: anchors still determine — human authority"
        );
        assert!(on.entries.is_empty());
    }

    #[test]
    fn human_determined_pair_survives_knob_on() {
        // Mixed evidence on the same pair: the human row alone determines it,
        // so demotion changes nothing.
        let rows = vec![win("h0", "A", "B"), win_agent("g0", "A", "B")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs.clone(),
            &[],
            &["A", "B"],
            &[("A", 1.0, 1.0), ("B", 1.0, 1.0)],
            &[],
        );
        inputs.demote_agent_evidence = true;
        let on = assemble(&inputs, seq(2));
        assert_eq!(on.state, QueueState::Stable { depth: 2 });
        assert!(on.entries.is_empty());
    }

    // ---- SL-219 PHASE-04 VT-2: cost_feed preservation & the D18 reprobe -----
    //
    // These are DISK-fixture tests (unlike the module's in-memory rows above):
    // the reprobe contract is a whole-shell property — an authored-range or β
    // edit re-derives est anchors → est projection → cost_feed → the ladder
    // `est_cost` the elicit eff-weights consume. No caching seam exists to
    // pin, so the tests drive the same load path the shells use.

    use crate::catalog::scan::ScanMode;
    use crate::comparison::CostFeed;
    use crate::priority::graph::{self, PriorityGraph};
    use crate::relation_graph::{self, EntityKey};

    fn write_file(root: &std::path::Path, rel: &str, body: &str) {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, body).unwrap();
    }

    /// Seed a backlog issue carrying `[value] value = 5.0` and the given
    /// `[estimate]` body (empty ⇒ bare item).
    fn seed_costed_issue(root: &std::path::Path, id: u32, estimate: &str) {
        write_file(
            root,
            &format!(".doctrine/backlog/issue/{id:03}/backlog-{id:03}.toml"),
            &format!(
                "id = {id}\nslug = \"i\"\ntitle = \"I\"\nkind = \"issue\"\nstatus = \"open\"\n\
                 resolution = \"\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
                 [estimate]\n{estimate}\n[value]\nvalue = 5.0\n"
            ),
        );
        write_file(
            root,
            &format!(".doctrine/backlog/issue/{id:03}/backlog-{id:03}.md"),
            "b\n",
        );
    }

    /// One est-domain `more-work` session: ISS-002 evidenced costlier than
    /// ISS-001 (the P5 head over ISS-001's authored anchor).
    /// PHASE-06: also writes an anchor-form claim row for ISS-001 so the
    /// est system has a claim-derived anchor (the old facet anchor is dead).
    /// ISS-001's authored estimate (2, 6) — the anchor row carries the SAME
    /// bounds so β-skew applies identically: operative = 2 + 0.65*4 = 4.6.
    fn write_est_session(root: &std::path::Path) {
        write_file(
            root,
            ".doctrine/comparisons/2026-07-11-e1.toml",
            "schema = \"doctrine.comparison-session\"\nversion = 2\n\n\
             [session]\nuid = \"e1\"\ndate = \"2026-07-11\"\n\n\
             [[judgement]]\nuid = \"e1-row\"\nseq = 0\na = \"ISS-002\"\nb = \"ISS-001\"\n\
             response = \"prefer-a\"\ndomain = \"estimate\"\nframe = \"more-work\"\n\
             form = \"order\"\nrater = \"agent\"\ndate = \"2026-07-11\"\n\n\
             # PHASE-06: anchor-form claim row for ISS-001 (bounds 2..6)\n\
             [[judgement]]\nuid = \"iss001-anchor\"\nseq = 100\na = \"ISS-001\"\n\
             domain = \"estimate\"\nframe = \"cost-anchor\"\n\
             form = \"anchor\"\nrater = \"human\"\ndate = \"2026-07-17\"\n\
             est_lower = 2.0\nest_upper = 6.0\n",
        );
    }

    /// `(multiplier, est_cost)` of `ISS-<id>` through the ONE post-build
    /// costing seam the elicit shell consumes (`item_costing`).
    fn costing_of(pg: &PriorityGraph, id: u32) -> (f64, f64) {
        let cfg = crate::priority::config::PriorityConfig::default();
        let (m, c, _) = pg
            .item_costing(&EntityKey { prefix: "ISS", id }, &cfg)
            .unwrap();
        (m, c)
    }

    /// Behaviour preservation (design §3 normative pin): zero est-domain rows
    /// ⇒ empty cost_feed ⇒ the build is identical to one fed an explicitly
    /// empty feed — score, base dims, and per-item costing all match.
    #[test]
    fn empty_cost_feed_is_identical_graph_build() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 6.0");
        seed_costed_issue(root, 2, "");
        let scanned =
            relation_graph::scan_entities(root, &mut vec![], ScanMode::default()).unwrap();
        let cfg = crate::priority::config::load(root);
        let via_load = graph::build_from(&scanned, root).unwrap();
        // Compute bare anchor from scanned entity uppers (non-terminal
        // max upper + margin). Same formula the pipeline uses.
        let bare_anchor = scanned
            .iter()
            .filter(|entity| {
                crate::priority::partition::status_class(entity.kind, entity.status.as_deref())
                    != crate::priority::partition::StatusClass::Terminal
            })
            // PHASE-09: estimate facet deleted; treat as absent.
            .map(|_| 1.0)
            .next()
            .unwrap_or(1.0);
        let explicit_empty = graph::build_from_with_cfg(
            &scanned,
            root,
            &cfg,
            &Projection::new(),
            &CostFeed::new(),
            &ClaimResolution::default(),
            bare_anchor,
            &crate::comparison::ClaimResolutionGeneric::<
                crate::comparison::EstimatePayload,
            >::default(),
        )
        .unwrap();
        assert_eq!(via_load.score, explicit_empty.score, "score map identical");
        for id in [1, 2] {
            assert_eq!(
                costing_of(&via_load, id),
                costing_of(&explicit_empty, id),
                "ISS-{id:03} costing identical under the empty feed"
            );
        }
        // And the bare item kept the pre-ladder divisor: the bare anchor.
        assert_eq!(costing_of(&via_load, 2).1, via_load.cost_ctx.absent);
    }

    /// D18 reprobe, authored-range edit: editing ISS-001's `[estimate]` moves
    /// its anchor ⇒ the est projection re-derives ⇒ ISS-002's fed cost moves ⇒
    /// the eff-weight (`m_self · c_other`) entering every value-determinacy
    /// verdict moves with it — one reprobe dynamic spanning both domains.
    #[test]
    fn authored_range_edit_rederives_cost_feed_into_eff_weights() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 6.0");
        seed_costed_issue(root, 2, "");
        write_est_session(root);

        // Before: anchor 2 + 0.65·4 = 4.6; ISS-002 fed at the P5 head 4.85.
        let before = graph::build(root).unwrap();
        let (m1, c1) = costing_of(&before, 2);
        assert!((c1 - 4.85).abs() < 1e-9, "fed, not bare-anchored: {c1}");

        // The range edit: ISS-001 → (2, 10). Re-write the anchor-form claim
        // row so the claim cost updates (PHASE-06: anchors are claim-derived,
        // not facet-derived; the test must update the claim to match).
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 10.0");
        // Re-write the anchor row with the new bounds (2, 10) — the β-skew
        // still applies: operative = 2 + 0.65·8 = 7.2.
        std::fs::write(
            root.join(".doctrine/comparisons/2026-07-11-e1.toml"),
            "schema = \"doctrine.comparison-session\"\nversion = 2\n\n\
             [session]\nuid = \"e1\"\ndate = \"2026-07-11\"\n\n\
             [[judgement]]\nuid = \"e1-row\"\nseq = 0\na = \"ISS-002\"\nb = \"ISS-001\"\n\
             response = \"prefer-a\"\ndomain = \"estimate\"\nframe = \"more-work\"\n\
             form = \"order\"\nrater = \"agent\"\ndate = \"2026-07-11\"\n\n\
             [[judgement]]\nuid = \"iss001-anchor\"\nseq = 100\na = \"ISS-001\"\n\
             domain = \"estimate\"\nframe = \"cost-anchor\"\n\
             form = \"anchor\"\nrater = \"human\"\ndate = \"2026-07-17\"\n\
             est_lower = 2.0\nest_upper = 10.0\n",
        )
        .unwrap();
        let after = graph::build(root).unwrap();
        let (m2, c2) = costing_of(&after, 2);
        assert!((c2 - 7.45).abs() < 1e-9, "fed cost re-derived: {c2}");
        assert!(
            (c2 - after.cost_ctx.absent).abs() > 1e-9,
            "still projected, not the (also-moved) bare anchor"
        );
        // The value-domain determinacy input moved: eff = m_self · c_other.
        assert_eq!(m1, m2, "multiplier is cost-free");
        assert!((m1 * c1 - m2 * c2).abs() > 1e-9, "eff-weight re-ran");
    }

    /// D18 reprobe, β edit: an operator `skew` edit moves every authored
    /// anchor ⇒ est projection + fed costs re-derive (design §3 REV content 5).
    #[test]
    fn beta_edit_rederives_cost_feed() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 6.0");
        seed_costed_issue(root, 2, "");
        write_est_session(root);
        let before = graph::build(root).unwrap();
        assert!((costing_of(&before, 2).1 - 4.85).abs() < 1e-9);

        // β → 0.0: the anchor collapses to `lower` (2.0); the head follows.
        write_file(
            root,
            crate::dtoml::DOCTRINE_TOML,
            "[priority.estimate]\nskew = 0.0\n",
        );
        let after = graph::build(root).unwrap();
        assert!(
            (costing_of(&after, 2).1 - 2.25).abs() < 1e-9,
            "β edit re-derived the fed cost"
        );
    }

    // ---- SL-219 PHASE-05: sizing probes (SizingProbe / Calibration) ------------

    /// In-memory inputs for the sizing source: an empty value system (no rows /
    /// anchors / projection), a frontier band, the `bare` ids flipped un-sized
    /// (the `mk` costing hardcodes the flag off), and the two pure sizing
    /// signals. Every frontier item is `IMP` (estimate-admissible), `m = 1`.
    fn unsized_inputs<'a>(
        frontier: &[&str],
        bare: &[&str],
        target_pool: &[(&str, f64)],
        evidenced: &[&str],
    ) -> ElicitInputs<'a> {
        let costing: Vec<(&str, f64, f64)> = frontier.iter().map(|&id| (id, 1.0, 5.0)).collect();
        let mut inputs = mk(vec![], &[], frontier, &costing, &[]);
        for id in bare {
            if let Some(c) = inputs.costing.get_mut(*id) {
                c.bare_estimate = true;
            }
        }
        inputs.sizing = sizing(target_pool, evidenced);
        inputs
    }

    fn probe_of<'q>(q: &'q ElicitQueue) -> Option<&'q QueueEntry> {
        q.entries
            .iter()
            .find(|e| e.kind == CandidateKind::SizingProbe)
    }

    #[test]
    fn sizing_probe_surfaces_for_unsized_subject_and_gates_candidates() {
        // S1 un-sized (no authored estimate, no est rows), T1 an authored
        // estimate ⇒ one existence-admitted SizingProbe (score/yield 0, basis
        // Calibration) against T1, and the probe GATES Candidates.
        let inputs = unsized_inputs(&["S1", "T1"], &["S1"], &[("T1", 2.0)], &[]);
        let q = assemble(&inputs, seq(2));
        assert_eq!(q.state, QueueState::Candidates, "a probe gates Candidates");
        let probe = probe_of(&q).expect("a sizing probe");
        assert_eq!(probe.guaranteed_yield, 0);
        assert!(
            probe.score.total_cmp(&0.0).is_eq(),
            "existence admission, score 0"
        );
        assert_eq!(probe.yield_basis, YieldBasis::Calibration);
        match &probe.payload {
            EntryPayload::SizingProbe { subject, target } => {
                assert_eq!(subject.id, "S1");
                assert_eq!(target.id, "T1");
                assert!((target.estimate - 2.0).abs() < 1e-9);
            }
            _ => panic!("expected a sizing-probe payload"),
        }
        assert_eq!(q.sizing_residual, 0);
        assert!(!q.sizing_no_calibration_target);
    }

    #[test]
    fn sizing_probe_incomparable_row_retires_the_probe() {
        // An est-domain row of ANY status touching S1 (an `incomparable` compiles
        // to NoConstraint but still lands in est_evidenced) retires the probe —
        // the engine asked once. S1 is disclosed as residual sizing debt, NOT a
        // re-probe loop.
        let inputs = unsized_inputs(&["S1", "T1"], &["S1"], &[("T1", 2.0)], &["S1"]);
        let q = assemble(&inputs, seq(2));
        assert!(
            probe_of(&q).is_none(),
            "est-evidenced subject is not re-probed"
        );
        assert_eq!(
            q.sizing_residual, 1,
            "declined subject disclosed as residual"
        );
    }

    #[test]
    fn sizing_target_is_the_lower_middle_median_authored_estimate() {
        // Odd count [1,2,3] ⇒ the middle (TB, cost 2). The subject sizes against it.
        let odd = unsized_inputs(
            &["S1", "TA", "TB", "TC"],
            &["S1"],
            &[("TA", 1.0), ("TB", 2.0), ("TC", 3.0)],
            &[],
        );
        let q = assemble(&odd, seq(4));
        let EntryPayload::SizingProbe { target, .. } = &probe_of(&q).unwrap().payload else {
            panic!("probe payload");
        };
        assert_eq!(target.id, "TB", "odd median = the middle");

        // Even count [1,2,3,4] ⇒ the LOWER-cost middle (TB, cost 2).
        let even = unsized_inputs(
            &["S1", "TA", "TB", "TC", "TD"],
            &["S1"],
            &[("TA", 1.0), ("TB", 2.0), ("TC", 3.0), ("TD", 4.0)],
            &[],
        );
        let q = assemble(&even, seq(5));
        let EntryPayload::SizingProbe { target, .. } = &probe_of(&q).unwrap().payload else {
            panic!("probe payload");
        };
        assert_eq!(target.id, "TB", "even count ⇒ lower-cost middle");

        // Equal costs ⇒ id-lexicographic tiebreak (TA before TB at the middle).
        let tie = unsized_inputs(
            &["S1", "TB", "TA"],
            &["S1"],
            &[("TA", 2.0), ("TB", 2.0)],
            &[],
        );
        let q = assemble(&tie, seq(3));
        let EntryPayload::SizingProbe { target, .. } = &probe_of(&q).unwrap().payload else {
            panic!("probe payload");
        };
        assert_eq!(target.id, "TA", "ties break id-lexicographic");
    }

    #[test]
    fn sizing_target_falls_back_to_all_estimated_then_none() {
        // Fallback tier 1: no authored estimate in the top-K band ⇒ median over
        // ALL admissible authored-estimate items (TB, cost 2).
        let tier1 = unsized_inputs(
            &["S1"],
            &["S1"],
            &[("TA", 1.0), ("TB", 2.0), ("TC", 3.0)],
            &[],
        );
        let q = assemble(&tier1, seq(1));
        let EntryPayload::SizingProbe { target, .. } = &probe_of(&q).unwrap().payload else {
            panic!("probe payload");
        };
        assert_eq!(
            target.id, "TB",
            "tier-1 fallback medians over all estimated"
        );

        // Tier 2: none estimated anywhere ⇒ no probe minted; the subjects are
        // disclosed residual + the no-calibration-target flag set.
        let tier2 = unsized_inputs(&["S1", "S2"], &["S1", "S2"], &[], &[]);
        let q = assemble(&tier2, seq(2));
        assert!(probe_of(&q).is_none(), "no target ⇒ no probe");
        assert!(q.sizing_no_calibration_target, "tier-2 disclosure flag set");
        assert_eq!(q.sizing_residual, 2, "both un-sized subjects disclosed");
    }

    #[test]
    fn sizing_probes_sink_below_yield_motivated_and_order_by_id() {
        // A>C, B>D yields a positive-score comparison on (A,B); un-sized S1/S2
        // add score-0 probes that sink below it, ordered by subject id.
        let rows = vec![win("j0", "A", "C"), win("j1", "B", "D")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs,
            &[],
            &["A", "B", "S2", "S1", "T1"],
            &[
                ("A", 1.0, 1.0),
                ("B", 1.0, 1.0),
                ("S2", 1.0, 5.0),
                ("S1", 1.0, 5.0),
                ("T1", 1.0, 2.0),
            ],
            &[],
        );
        for id in ["S1", "S2"] {
            inputs.costing.get_mut(id).unwrap().bare_estimate = true;
        }
        inputs.sizing = sizing(&[("T1", 2.0)], &[]);
        let q = assemble(&inputs, seq(5));

        assert_eq!(
            q.entries.first().map(|e| e.kind),
            Some(CandidateKind::Comparison),
            "the yield-motivated comparison ranks first"
        );
        let probe_subjects: Vec<&str> = q
            .entries
            .iter()
            .filter_map(|e| match &e.payload {
                EntryPayload::SizingProbe { subject, .. } => Some(subject.id.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            probe_subjects,
            vec!["S1", "S2"],
            "probes ordered by subject id"
        );
        // Every probe sinks below the yield-motivated entry.
        let first_probe = q
            .entries
            .iter()
            .position(|e| e.kind == CandidateKind::SizingProbe)
            .unwrap();
        assert!(
            first_probe > 0,
            "probes sink below the positive-score entry"
        );
    }

    #[test]
    fn sizing_residual_discloses_on_stable_without_gating() {
        // A single un-sized, est-evidenced (declined) item that is ALSO
        // value-insensitive (m = 0, out of the value pool) ⇒ no gating entry, the
        // value pool is determined ⇒ Stable, and the sizing debt is disclosed as
        // residual — never gating (§4 D15 precedence unchanged).
        let mut inputs = unsized_inputs(&["S1"], &["S1"], &[("T1", 2.0)], &["S1"]);
        inputs.costing.get_mut("S1").unwrap().multiplier = 0.0;
        let q = assemble(&inputs, seq(1));
        assert_eq!(
            q.state,
            QueueState::Stable { depth: 1 },
            "residual never gates"
        );
        assert!(probe_of(&q).is_none());
        assert_eq!(
            q.sizing_residual, 1,
            "unresolved sizing disclosed on Stable"
        );
    }

    // ---- E10: anchored-target-required, facet-only corpus, interregnum ------
    //
    // E10 (design §6.10): probe TARGETS require anchored-tier claims. A
    // facet-only corpus has zero anchored-tier estimate claims ⇒ no targets
    // ⇒ "no estimated item to calibrate against" fires with the claim-era
    // remedy. Interregnum: an unmigrated [estimate] facet counts as SIZED
    // for probe-eligibility (knob-independent; mirrors pre-flip; dies with
    // the facet rung).

    /// A facet-only target (no anchored-tier claim) is NOT a valid probe
    /// target — even though it appears in `estimated_costs` via the shell's
    /// authored-cost harvest, the `estimate_anchored_targets` set excludes
    /// it, so `sizing_target` returns None and the "no estimated item to
    /// calibrate against" flag fires.
    #[test]
    fn facet_only_target_is_not_valid_probe_target() {
        let mut inputs = unsized_inputs(&["S1"], &["S1"], &[("T1", 2.0)], &[]);
        // T1 appears in estimated_costs (from bare_estimate=false) but NOT
        // in estimate_anchored_targets — simulate a facet-only corpus with
        // no anchored-tier claims.
        inputs.sizing.estimate_anchored_targets.clear();
        let q = assemble(&inputs, seq(2));
        assert!(probe_of(&q).is_none(), "facet-only target: no probe minted");
        assert!(
            q.sizing_no_calibration_target,
            "facet-only corpus triggers the no-target state detail"
        );
        assert_eq!(q.sizing_residual, 1, "S1 disclosed as residual");
    }

    /// An anchored-tier claim target IS a valid probe target — the
    /// `estimate_anchored_targets` includes it, so the median selects
    /// the claimed item.
    #[test]
    fn anchored_claim_target_is_valid_probe_target() {
        let inputs = unsized_inputs(&["S1"], &["S1"], &[("T1", 2.0)], &[]);
        // T1 is in both estimated_costs AND estimate_anchored_targets
        // (the `sizing()` helper puts all estimated items into
        // estimate_anchored_targets by default).
        let q = assemble(&inputs, seq(2));
        let probe = probe_of(&q).expect("a sizing probe is minted");
        let EntryPayload::SizingProbe { target, .. } = &probe.payload else {
            panic!("sizing-probe payload");
        };
        assert_eq!(target.id, "T1", "anchored-claim target selected");
        assert!(!q.sizing_no_calibration_target);
    }

    /// A corpus with zero anchored-tier estimate claims AND zero
    /// `estimated_costs` entries (the typical pre-flip facet-only corpus)
    /// fires the remedy state detail with claim-era remedy text.
    #[test]
    fn zero_anchored_claims_fires_remedy_detail() {
        // S2 and S3 are un-sized; the estimated_costs pool is empty AND
        // estimate_anchored_targets is empty — zero targets anywhere.
        let inputs = unsized_inputs(&["S1", "S2"], &["S1", "S2"], &[], &[]);
        let q = assemble(&inputs, seq(2));
        assert!(probe_of(&q).is_none(), "no target ⇒ no probe");
        assert!(
            q.sizing_no_calibration_target,
            "remedy detail fires: no estimated item to calibrate against"
        );
    }

    /// Interregnum: an unmigrated [estimate] facet counts as SIZED for
    /// probe-eligibility (knob-independent). The subject is NOT probed
    /// even when target items exist.
    #[test]
    fn unmigrated_facet_counts_as_sized_knob_independently() {
        let rows = vec![win("j0", "A", "C"), win("j1", "B", "D")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs.clone(),
            &[],
            &["A", "B", "S1", "T1"],
            &[
                ("A", 1.0, 1.0),
                ("B", 1.0, 1.0),
                ("S1", 1.0, 5.0),
                ("T1", 1.0, 2.0),
            ],
            &[],
        );
        // S1 is bare (no estimate facet) ⇒ un-sized; T1 has authored
        // estimate (not bare) ⇒ sized target.
        inputs.costing.get_mut("S1").unwrap().bare_estimate = true;
        inputs.sizing = sizing(&[("T1", 2.0)], &[]);

        for knob in [false, true] {
            inputs.demote_agent_evidence = knob;
            let q = assemble(&inputs, seq(4));
            // S1 is bare-flagged → un-sized → probed.
            let probes_s1: Vec<&str> = q
                .entries
                .iter()
                .filter_map(|e| match &e.payload {
                    EntryPayload::SizingProbe { subject, .. } if subject.id == "S1" => {
                        Some(subject.id.as_str())
                    }
                    _ => None,
                })
                .collect();
            assert_eq!(probes_s1.len(), 1, "S1 is probed (bare, knob={knob})");
            // T1 is NOT bare → counts as sized → no probe for T1.
            let probes_t1: Vec<&str> = q
                .entries
                .iter()
                .filter_map(|e| match &e.payload {
                    EntryPayload::SizingProbe { subject, .. } if subject.id == "T1" => {
                        Some(subject.id.as_str())
                    }
                    _ => None,
                })
                .collect();
            assert_eq!(
                probes_t1.len(),
                0,
                "T1 is NOT probed (sized via facet, knob={knob})"
            );
        }
    }

    // ---- SL-219 PHASE-05 postcondition: sizing-probe answers land anchored -----
    //
    // The contract the probe's target selection GUARANTEES: because the target
    // always carries an AUTHORED estimate (an anchored est class), an
    // order-bearing answer lands the un-sized subject in that anchored component
    // with non-Gauge provenance — Projected on `prefer`, Authored (via the class
    // anchor) on `equal` — NEVER the bare anchor, NEVER a gauge component. These
    // are disk-fixture goldens over the est pipeline (never touched here).

    fn write_est_row(root: &std::path::Path, a: &str, b: &str, response: &str) {
        // PHASE-06: also write an anchor-form claim row for `b` (the target
        // with an authored estimate) so the est system has a claim-derived
        // anchor. `b` is ISS-001 with estimate (2, 6) — the anchor row
        // carries the SAME bounds so β-skew applies identically.
        write_file(
            root,
            ".doctrine/comparisons/2026-07-11-e1.toml",
            &format!(
                "schema = \"doctrine.comparison-session\"\nversion = 2\n\n\
                 [session]\nuid = \"e1\"\ndate = \"2026-07-11\"\n\n\
                 [[judgement]]\nuid = \"e1-row\"\nseq = 0\na = \"{a}\"\nb = \"{b}\"\n\
                 response = \"{response}\"\ndomain = \"estimate\"\nframe = \"more-work\"\n\
                 form = \"order\"\nrater = \"agent\"\ndate = \"2026-07-11\"\n\n\
                 # PHASE-06: anchor-form claim row for {b} (bounds 2..6)\n\
                 [[judgement]]\nuid = \"target-anchor\"\nseq = 100\na = \"{b}\"\n\
                 domain = \"estimate\"\nframe = \"cost-anchor\"\n\
                 form = \"anchor\"\nrater = \"human\"\ndate = \"2026-07-17\"\n\
                 est_lower = 2.0\nest_upper = 6.0\n",
            ),
        );
    }

    #[test]
    fn sizing_probe_prefer_answer_projects_subject_non_gauge() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 6.0"); // target: authored anchor 4.6
        seed_costed_issue(root, 2, ""); // subject: un-sized
        // ISS-002 is MORE work than ISS-001 (prefer-a, winner = costlier, D5).
        write_est_row(root, "ISS-002", "ISS-001", "prefer-a");

        let pipeline = graph::load_comparison_pipeline_for_root(root).unwrap();
        let (cost, prov) = pipeline
            .estimate
            .projection
            .get("ISS-002")
            .copied()
            .expect("subject placed in the est projection");
        assert_eq!(
            prov,
            ValueProvenance::Projected,
            "prefer ⇒ Projected placement"
        );
        assert!(cost > 0.0);

        // The scoring feed consumes the projected cost — NEVER the bare anchor.
        let pg = graph::build(root).unwrap();
        let fed = costing_of(&pg, 2).1;
        assert!(
            (fed - pg.cost_ctx.absent).abs() > 1e-9,
            "fed a projected cost, not the bare-anchor fallthrough"
        );
    }

    #[test]
    fn sizing_probe_equal_answer_merges_subject_authored_via_class() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        seed_costed_issue(root, 1, "lower = 2.0\nupper = 6.0"); // anchor 2 + 0.65·4 = 4.6
        seed_costed_issue(root, 2, "");
        write_est_row(root, "ISS-002", "ISS-001", "equal");

        let pipeline = graph::load_comparison_pipeline_for_root(root).unwrap();
        let (cost, prov) = pipeline
            .estimate
            .projection
            .get("ISS-002")
            .copied()
            .expect("subject merged into the est projection");
        assert_eq!(
            prov,
            ValueProvenance::Authored,
            "equal ⇒ anchored-class membership, provenance Authored"
        );
        assert!(
            (cost - 4.6).abs() < 1e-9,
            "the merged member sits at the class anchor cost, not gauge/bare"
        );
    }

    // ---- SL-220 §3 / D14: claim retirement + the claim-reprobe source ------------

    /// A value-domain anchor row for the claims harness (single subject,
    /// magnitude payload — the §2 wire shape).
    fn anchor_claim(uid: &str, item: &str, magnitude: f64, rater: RaterKind) -> Judgement {
        use crate::comparison::{DOMAIN_VALUE, FRAME_VALUE_ANCHOR};
        let migrated = matches!(rater, RaterKind::Migrated);
        let mut j = jrow(uid, item, "unused", Response::PreferA, rater);
        j.b = None;
        j.response = None;
        j.form = RowForm::Anchor;
        j.domain = DOMAIN_VALUE.to_string();
        j.frame = FRAME_VALUE_ANCHOR.to_string();
        j.magnitude = Some(magnitude);
        if migrated {
            j.observed_at = j.date.take();
        }
        j
    }

    /// Resolve a claim ledger over Active rows (the pure harness — mirrors
    /// the store pipeline's own selection).
    fn claims_from(rows: &[Judgement]) -> ClaimResolution {
        let tagged: Vec<(&Judgement, crate::comparison::ResolutionStatus)> = rows
            .iter()
            .map(|j| (j, crate::comparison::ResolutionStatus::Active))
            .collect();
        crate::comparison::resolve_claims(&tagged)
    }

    /// Does the queue carry a median-probe involving `id`?
    fn has_median_probe(q: &ElicitQueue, id: &str) -> bool {
        q.entries.iter().any(|e| {
            e.reasons.iter().any(|r| r.code == "median-probe")
                && matches!(
                    &e.payload,
                    EntryPayload::Comparison { a, b, .. } if a.id == id || b.id == id
                )
        })
    }

    /// §3 demotion widening, rungs 3–4: an agent-tier prior counts as VALUED
    /// while the knob is off (its calibration probe retires) and stays
    /// PROBE-ELIGIBLE when the knob is on (a number, not an answer) — both
    /// settings asserted over the same fixture.
    #[test]
    fn prior_valued_item_probe_retired_knob_off_eligible_knob_on() {
        let rows = vec![win("j0", "W", "Z")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let claim_rows = [anchor_claim("a1", "U", 3.0, RaterKind::Agent)];
        let mut inputs = mk(
            refs.clone(),
            &[("Z", 0.0)],
            &["U", "W"],
            &[("U", 1.0, 1.0), ("W", 1.0, 1.0)],
            &[
                ("U", 2.0, ValueProvenance::Projected),
                ("W", 3.0, ValueProvenance::Projected),
            ],
        );
        inputs.claims = claims_from(&claim_rows);
        assert!(inputs.claims.priors.contains_key("U"), "prior resolved");

        let off = assemble(&inputs, seq(2));
        assert!(
            !has_median_probe(&off, "U"),
            "knob-off: the prior retires the probe (valued for queue purposes)"
        );
        inputs.demote_agent_evidence = true;
        let on = assemble(&inputs, seq(2));
        assert!(
            has_median_probe(&on, "U"),
            "knob-on: rungs 3–5 do not retire elicitation"
        );
    }

    /// §3 demotion widening, rung 5: an unmigrated `[value]` facet behaves
    /// exactly like a prior for queue purposes — knob-off retired, knob-on
    /// probe-eligible.
    #[test]
    fn facet_valued_item_probe_retired_knob_off_eligible_knob_on() {
        let rows = vec![win("j0", "W", "Z")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let mut inputs = mk(
            refs.clone(),
            &[("Z", 0.0)],
            &["U", "W"],
            &[("U", 1.0, 1.0), ("W", 1.0, 1.0)],
            &[
                ("U", 2.0, ValueProvenance::Projected),
                ("W", 3.0, ValueProvenance::Projected),
            ],
        );
        inputs.facet_valued.insert("U".to_string());

        let off = assemble(&inputs, seq(2));
        assert!(!has_median_probe(&off, "U"), "knob-off: facet retires");
        inputs.demote_agent_evidence = true;
        let on = assemble(&inputs, seq(2));
        assert!(has_median_probe(&on, "U"), "knob-on: facet stays eligible");
    }

    /// Rung 1 is an ANSWER, not a number: an anchored (human) claim retires
    /// the calibration probe under BOTH knob settings — even row-lessly
    /// (scope R1: compile's row-gating cannot see the anchor, `claim_retired`
    /// reads `anchored` directly).
    #[test]
    fn anchored_claim_retires_probe_knob_independently() {
        let rows = vec![win("j0", "W", "Z")];
        let refs: Vec<&Judgement> = rows.iter().collect();
        let claim_rows = [anchor_claim("h1", "U", 6.0, RaterKind::Human)];
        let mut inputs = mk(
            refs.clone(),
            &[("Z", 0.0)],
            &["U", "W"],
            &[("U", 1.0, 1.0), ("W", 1.0, 1.0)],
            &[
                ("U", 2.0, ValueProvenance::Projected),
                ("W", 3.0, ValueProvenance::Projected),
            ],
        );
        inputs.claims = claims_from(&claim_rows);
        assert!(inputs.claims.anchored.contains_key("U"));

        for knob in [false, true] {
            inputs.demote_agent_evidence = knob;
            let q = assemble(&inputs, seq(2));
            assert!(
                !has_median_probe(&q, "U"),
                "an anchored claim retires the probe (knob = {knob})"
            );
        }
    }

    /// D14 BOTH directions, BOTH knob settings: an anchored-tier (human)
    /// claim conflict enters the reprobe queue KNOB-INDEPENDENTLY; an
    /// agent-tier conflict — an ordinary calibrate-via-comparison finding —
    /// NEVER does. Existence-admitted at score 0 (sinks, never vanishes).
    #[test]
    fn anchored_conflict_enters_reprobe_queue_knob_independently_agent_never() {
        let claim_rows = [
            anchor_claim("h1", "U", 4.0, RaterKind::Human),
            anchor_claim("h2", "U", 6.0, RaterKind::Human),
            anchor_claim("a1", "V", 1.0, RaterKind::Agent),
            anchor_claim("a2", "V", 3.0, RaterKind::Agent),
        ];
        let claims = claims_from(&claim_rows);
        assert_eq!(claims.findings.len(), 2, "conflicts fire at EVERY tier");

        let mut inputs = mk(vec![], &[], &[], &[], &[]);
        inputs.claims = claims;
        for knob in [false, true] {
            inputs.demote_agent_evidence = knob;
            let q = assemble(&inputs, seq(2));
            let reprobes: Vec<&QueueEntry> = q
                .entries
                .iter()
                .filter(|e| e.kind == CandidateKind::ClaimReprobe)
                .collect();
            assert_eq!(
                reprobes.len(),
                1,
                "exactly the anchored conflict (knob = {knob})"
            );
            let EntryPayload::ClaimReprobe {
                subject,
                tier,
                mean,
                low,
                high,
                distinct,
                rows,
            } = &reprobes[0].payload
            else {
                panic!("claim-reprobe payload");
            };
            assert_eq!(subject, "U", "the agent conflict (V) never enters");
            assert_eq!(*tier, ClaimTier::Human);
            assert_eq!((*mean, *low, *high), (5.0, 4.0, 6.0));
            assert_eq!((*distinct, *rows), (2, 2));
            assert_eq!(reprobes[0].score, 0.0, "existence-admitted, zero yield");
            assert_eq!(reprobes[0].yield_basis, YieldBasis::Calibration);
        }
    }

    /// A contested PIN reprobes too (D3 "contested pin"), named as such in
    /// its reason text — still the one anchored-tier gate, no special case.
    #[test]
    fn contested_pin_mints_a_reprobe_named_contested_pin() {
        let mut p1 = anchor_claim("p1", "U", 3.0, RaterKind::Human);
        p1.admission = Some(crate::comparison::AdmissionKind::Pin);
        let mut p2 = anchor_claim("p2", "U", 9.0, RaterKind::Human);
        p2.admission = Some(crate::comparison::AdmissionKind::Pin);
        let mut inputs = mk(vec![], &[], &[], &[], &[]);
        inputs.claims = claims_from(&[p1, p2]);
        let q = assemble(&inputs, seq(2));
        let entry = q
            .entries
            .iter()
            .find(|e| e.kind == CandidateKind::ClaimReprobe)
            .expect("the contested pin reprobes");
        assert!(
            entry
                .reasons
                .iter()
                .any(|r| r.text.contains("contested pin")),
            "{:?}",
            entry.reasons
        );
        assert!(matches!(
            &entry.payload,
            EntryPayload::ClaimReprobe {
                tier: ClaimTier::Pin,
                ..
            }
        ));
    }
}