yah-cloud 0.8.43

Declarative cloud substrate for yah-managed camps: .yah/cloud/ config schema, MachineProvider drivers (Hetzner + local containerd), cloud-init rendering, and the pond/mesofact reconcilers.
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
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
//! Public-ingress provider seam — `mirror.ingress` → live front-door state.
//!
//! Part of R594-F11 (W267 §"Ingress is a provider, not a fixed part of the
//! stack"). The canonical ticket annotation lives in
//! `.yah/docs/working/W267-sovereign-public-ingress.md`.
//!
//! A mirror declares a **list of edges**
//! ([`IngressEdge`](crate::config::IngressEdge)) and the rules each one needs
//! published are derived, not typed in:
//!
//! ```text
//! slots with `zone` + (`port` | `fronted`)  ─by edge selector─►  IngressPlan { provider, rules, front_doors }
//!                                           ├── cloudflare-tunnel → CF API ingress config
//!                                           └── passway           → PASSWAY_UPSTREAMS
//! ```
//!
//! [`plan_ingress`] is pure and provider-agnostic on purpose: the same
//! `(hostname, port)` pairs feed either arm, so flipping
//! `ingress = "cloudflare-tunnel"` to `ingress = "passway"` needs no other edit
//! to the mirror. That is the whole point of calling ingress a *provider* —
//! walking W267's tier ladder is a config flip, not a rewrite. W305 F2 makes
//! that ladder *per edge*: a mirror can now front its public web tier through
//! cloudflare and an internal tier through passway, which a single
//! [`IngressProvider`](crate::config::IngressProvider) field could not express.
//!
//! **The node's front doors are collated, not declared.** An edge invokes a
//! per-node appliance, but that is downstream of the service's declaration:
//! [`collate_front_doors`] takes every service's plans and derives what each
//! node must run. That direction is the whole point — declaring cohorts
//! node-side (W267 Gap 3) produces two sources of truth for one fact, and the
//! node's copy is the one that goes stale.
//!
//! **The provider owns addressing, never rendering.** A rule carries a
//! hostname and a local port — enough to *dial*, and deliberately nothing about
//! what any path means. The W173 render cube stays in mesofact's manifest
//! (W267 §"Two front doors, one render contract"); growing a path-based router
//! here would mint a third copy of those rules.
//!
//! @yah:relay(R845, "Tunnel ingress cannot resolve Cloudflare creds for a static-machine compute slot")
//! @yah:status(review)
//! @yah:at(2026-09-02T07:05:16Z)
//! @yah:assignee(agent:bundle-anthropic-ashguard)
//! @yah:gotcha("Reported by the noisetable camp (its R131-T6, the first tenant to declare ingress = cloudflare-tunnel). IngressPlan::provider_id() is the `use` of the first FRONTED slot that names one, and apply's CloudflareTunnel arm resolves the Cloudflare account id + API token through it (app/yah/cli/src/cloud.rs, then publish_tunnel_ingress -> CfProvider::resolve).")
//! @yah:gotcha("A slot is FRONTED when it declares `port`. So the field that says what runs the compute is also the field that says whose Cloudflare account holds the tunnel. For a compute slot on a borrowed bare box the compute provider is the inline kind = static (placement-only, no credentials), and there is then no way to name a Cloudflare provider at all: apply bails with 'no fronted slot declares use = <provider-id>'.")
//! @yah:gotcha("The workaround is to write use = cloudflare on the compute slot, which satisfies the lookup by lying about what runs the compute. noisetable deliberately did NOT do that; its mirror (.yah/services/noisetable-api/mirrors/cloud.toml in that camp) documents the gap instead and its front door cannot be applied until this is fixed.")
//! @yah:next("Proposed shape, mirroring what the edge already does for tunnel_id: give IngressEdge its own provider id field, so the front door names the account that holds its tunnel and the fronted slot keeps naming what runs the compute. W267 Gap 3 already argued this exact split for tunnel_id (which cohort a service fronts through is a property of the SERVICE, not of the box); credentials are the same kind of fact.")
//! @yah:next("Keep provider_id() as the fallback so every mirror on disk today (yah-marketing's bundle slot, use = cloudflare) is unchanged.")
//! @yah:next("Whatever lands, the bail message should name the fix. Today it says the fronted slot must declare use = <provider-id>, which for a static-machine slot is advice that cannot be followed.")
//! @yah:handoff("SHIPPED the edge-side split. [[ingress]] entries now take their own use = <provider-id> (IngressEdge.provider_id, serde-renamed to `use` so it is spelled exactly as a slot's). plan_ingress carries it onto IngressPlan.edge_provider_id; IngressPlan::provider_id() resolves edge-first and falls back to the first fronted slot's `use`, which is the pre-R845 rule, so every mirror on disk plans identically.")
//! @yah:handoff("DISCOVERED AND FIXED, beyond the ticket: the pre-R845 fallback picks the first rule with any `use`, sorted by hostname, so a mirror whose compute slot is use = hetzner could hand a Hetzner provider id to CfProvider::resolve. app/yah/cli/src/cloud.rs now prefers a fronted slot referencing a Cloudflare-KIND provider (cfg.provider(id).kind == Provider::Cloudflare) before falling back to plan.provider_id(); the pure planner cannot make that call, having no view of .yah/infra/providers/.")
//! @yah:handoff("An edge's `use` is now cross-ref validated like a slot's: CloudConfig::cross_ref_validate bails with ingress[N].use = <id> - no such provider, via a new MirrorConfig::ingress_edge_slice() that reads the [[ingress]] tables raw (ingress_edges() hard-fails on unrelated shape errors, wrong for a whole-workspace walk). A typo used to survive to the Cloudflare arm of apply.")
//! @yah:handoff("Bail message rewritten to name a followable fix: add use to the [[ingress]] edge, why the slot's `use` is only a fallback, and - for the scalar ingress = cloudflare-tunnel spelling, which has no edge table - convert to the list form. W267 Gap 3 gained a paragraph recording the split (docs are canon; the constraint now lives beside the tunnel_id argument it mirrors).")
//! @yah:verify("cargo test -p yah-cloud --lib (oss/yubaba): 949 passed, 0 failed - includes 4 new ingress tests (edge use overrides the slot's; a kind = static compute slot plans with no slot `use` at all; no-edge-use still answers off the slot; `use` round-trips through mirror TOML) and 1 new cross-ref test.")
//! @yah:verify("cargo check -p yah -p xtask --all-targets: clean. cargo test -p xtask --test main mirror_ingress: 6 passed - that one plans this camp's real .yah/services mirrors, so yah-marketing's bundle slot (use = cloudflare, no edge use) is proven unchanged.")
//! @yah:verify("cargo run -p xtask -- emit-schemas regenerated .yah/schema/mirror.toml.schema.json (new `use` on the edge). It also regenerated machine.toml.schema.json - a pre-existing doc-comment drift on the non-voter role variant, not mine; left in so the gate can go green. NOTE check-schema-drift.sh compares against git HEAD, so it reads red until these are committed.")
//! @yah:gotcha("The noisetable camp's mirror still needs the one-line edit on their side: add use = \"cloudflare\" to its [[ingress]] entry (or convert its scalar ingress = \"cloudflare-tunnel\" to the list form and put it there). Nothing in this camp's tree declares an edge `use` yet, so the new field is exercised only by unit tests until they apply.")
//! @yah:handoff("Installed: cargo xtask install -> ~/.local/bin/yah, sha256 1cac1e97b0651c731d6ce6180c51d80116071126a1f00f6e43a487bf836e8277, build id yah 0.8.29+6c8b994f-dirty, PATH resolves there. Confirmed by content, not mtime: strings -a on the installed binary finds the new bail text (`convert to the list form`, `nothing names the Cloudflare account`). MCP tool surface unchanged, so the app-bundle install is not needed.")
//! @yah:verify("strings -a ~/.local/bin/yah | grep -c 'convert to the list form' -> 1 (the installed CLI is the fixed one).")
//!
//! @yah:relay(R910, "Declare a cloudflare-tunnel edge that fronts the node's own passway (tunnel → sni-demux → passway, W348 §1.3 stacked shape)")
//! @yah:at(2026-09-14T23:04:08Z)
//! @yah:assignee(agent:bundle-anthropic-ashguard)
//! @arch:see(.yah/docs/working/W348-ingress-topology-modes-and-per-route-mixing.md)
//!
//! @yah:ticket(R910-F1, "Tunnel edge `via` the node's passway door: collation pair rule, originRequest render, no apex A record, ACME dns-01 door env")
//! @yah:status(review)
//! @yah:at(2026-09-15T01:43:54Z)
//! @yah:assignee(agent:bundle-anthropic-ashguard)
//! @yah:parent(R910)
//! @yah:next("Tier: Wizard — changes the collation partition rule and IngressEdge vocabulary that every mirror goes through.")
//! @yah:next("WHY: noisetable R704-T4 (operator decision B, 2026-09-14) runs staging.noisetable.com + api-staging.noisetable.com as cloudflared -> passway-demux 127.0.0.1:443 -> passway :8445 (ACME dns-01) on us-west-011, hand-enrolled. No mirror can declare it: collate_front_doors (ingress.rs:1133) rejects one hostname under two providers, and merge_tunnel_ingress (ingress.rs:1365) renders only {hostname, service}, with no originRequest. A mirror carrying the tunnel edge would make apply REPLACE the live rule with service http://<compute> and drop matchSNItoHost, bypassing passway. So both noisetable staging mirrors now carry no [[ingress]] edge.")
//! @yah:next("SHAPE: a tunnel edge naming the node's passway door as its upstream (e.g. `via = \"passway\"`) renders `service: https://127.0.0.1:<demux port>` + `originRequest.matchSNItoHost = true`, verification on. Collation accepts the tunnel+passway pair for one hostname only on the same machine. plan_passway_apex publishes NO A record for a tunnel-fronted passway door (its private-address guard, domain.rs ~591, would otherwise error on 192.168.10.11). The passway door renders PASSWAY_TLS_MODE=acme + dns-01 env, which cloud.rs ingress deploy cannot do today (manual cluster cert only). Then restore both staging mirrors' edges in the noisetable camp.")
//! @yah:next("ORDERING: a cloudflared started before its tunnel's first config PUT never loaded it (noisetable R704-T4 gotcha) — publish config first or restart the connector after the first write. Depends on R907-B1 for that first write.")
//! @yah:handoff("LANDED: a cloudflare-tunnel [[ingress]] edge may carry `via = \"passway\"` (config.rs: new IngressVia enum + IngressEdge.via + IngressEdge::validate_via, called from MirrorConfig::ingress_edges, so via on a passway edge is refused, not ignored). ingress.rs partition(): a via edge is set aside rather than counted as a second claimant, and admitted only beside exactly one passway edge with the SAME hostnames on the SAME machines. It refuses by name: via with no door, a pair split across nodes, a door behind a tunnel that also fronts a public hostname, two stacked edges for one hostname, and via naming a provider other than the terminal edge's. The passway plan is derived IngressPlan.behind_tunnel; the tunnel plan carries IngressPlan.via.")
//! @yah:handoff("RENDER: IngressPlan::tunnel_rule / tunnel_service render {hostname, service: https://127.0.0.1:443 (PASSWAY_DEMUX_ORIGIN), originRequest: {matchSNItoHost: true}}, with verification left on. merge_tunnel_ingress now takes the plan, so apply renders the exact config R704-T4 PUT by hand instead of replacing it with http://<compute>.")
//! @yah:handoff("COLLATION: collate_front_doors skips stacked tunnels in the two-provider and upstream conflict passes, then checks cross-service that a passway door fronts each stacked hostname on each tunnel machine. It marks NodeFrontDoor.stacked on both doors, per hostname. domain.rs plan_passway_apex filters out doors whose stacked list names the domain, so no A record is published and the private-address guard is never reached; the ensure_passway_apex bail text now names the tunnel case.")
//! @yah:handoff("APPLY (app/yah/cli/src/cloud.rs): reconcile_ingress_edge skips workload discovery for a via plan (it never dials the workload). The tunnel arm prints the demux service. The passway arm, for a behind_tunnel plan, prints IngressPlan::behind_tunnel_env (loopback PASSWAY_LISTEN, TLS_MODE=acme, CHALLENGE=dns-01, DIRECTORY=production, DOMAIN=<hostnames>, placeholders for contact, zone id and token file) and returns BEFORE pushing the public manual-TLS appliance. `yah cloud ingress collate` labels each side of a stacked hostname.")
//! @yah:handoff("NOT DONE, filed as R910-F2: declared ACME inputs plus the PasswayIngressSpec lowering for a pushed door behind a tunnel, demux route rendering, and restoring the noisetable staging mirrors. Also not done: `cargo xtask install`. Nothing consumes `via` until F2, and F2 names the install as its precondition.")
//! @yah:handoff("DOCS + GENERATED: W348 section 1.3 stamped as expressible (R910-F1), and the section 6 superseded paragraph points at it. `cargo run -p xtask -- emit-schemas` regenerated .yah/schema/mirror.toml.schema.json (+23 lines: the `via` property and the IngressVia definition, nothing else).")
//! @yah:verify("cargo test -p yah-cloud --lib (oss/yubaba), filtered to reconciler::ingress, reconciler::domain, service_discovery, ingress_verify and validate: 243 passed / 0 failed. Targeted run of the 13 new R910 tests: all ok. ingress.rs has 12: a_tunnel_via_passway_and_its_door_plan_as_one_stacked_pair, without_via_the_same_two_edges_are_still_a_conflict, a_via_tunnel_with_no_passway_door_is_refused, a_via_tunnel_on_another_machine_than_its_door_is_refused, via_on_a_passway_edge_is_refused_rather_than_ignored, via_is_spelled_in_mirror_toml_as_a_kebab_case_provider, a_stacked_pair_collates_and_both_of_its_doors_know_it, a_stacked_tunnel_on_a_node_its_door_is_not_on_is_a_conflict, a_stacked_tunnel_does_not_license_a_direct_one_for_the_same_hostname, only_the_stacked_hostnames_on_a_shared_node_are_marked, a_via_passway_rule_renders_the_live_stacked_config_exactly (asserts byte-equality with the live R704-T4 tunnel config and no-PUT idempotence), and a_door_behind_a_tunnel_renders_dns01_acme_for_exactly_its_hostnames (not matched by the targeted filter, but inside the 243). domain.rs has a_door_behind_a_cloudflare_tunnel_is_not_an_apex_origin: a public-ip-tainted machine on 192.168.10.11 with a stacked pair plans to None instead of erroring.")
//! @yah:verify("Full yah-cloud lib suite: 1195 passed / 36 failed / 4 ignored. ALL 36 failures are one pre-existing cause outside this diff: workload fixtures in migrate.rs, topology.rs and config.rs tests declare `schema_version`, which the workload-schema unknown-key lint now refuses. Counted: 36 panics, 36 naming schema_version. Noisetable's R704-T4 notes attribute the key's removal to R896-T4; this ticket touches no workload parsing.")
//! @yah:verify("cargo check -p yah --lib --tests (root): Finished, zero errors. cargo check -p yubaba --tests (oss/yubaba): Finished. cargo check -p yah-cloud --all-targets: no warnings in ingress.rs, domain.rs or config.rs. cargo test -p xtask --test main mirror_ingress: 14 passed / 0 failed, so this camp's real mirrors plan unchanged.")
//! @yah:gotcha("The camp daemon's TaskRun store is failing: every `yah build run` this session reported `open TaskRun store ... turso: I/O error: short read on page 24050: expected 4096 bytes, got 0` and fell back to running locally. Unrelated to this ticket, but builds are running outside the camp queue until it is fixed.")
//! @yah:assumes("Cloudflare's GET of tunnel configuration echoes originRequest as {matchSNItoHost: true} without adding defaulted keys. If it adds keys, merged != live and every apply re-PUTs an identical config. That costs one extra PUT, not a wrong route. Not measured: the byte-equality test uses R704-T4's recorded PUT body, not a live GET.")
//! @yah:assumes("passway-demux listens on 127.0.0.1:443 on every node a stacked pair lands on (PASSWAY_DEMUX_ORIGIN is a constant). True for us-west-011 per R704-T4. Nothing in yubaba declares the demux, so a node with the demux elsewhere would need this to become an edge field.")
//!
//! @yah:ticket(R910-F2, "Push the door behind a tunnel: declared ACME dns-01 inputs + loopback listen + demux route, then restore noisetable's staging edges")
//! @yah:status(review)
//! @yah:at(2026-09-15T20:16:15Z)
//! @yah:assignee(agent:bundle-anthropic-ashguard)
//! @yah:parent(R910)
//! @yah:gotcha("OPERATOR CONSTRAINT 2026-09-14: the door's DNS token must PERSIST, either in a checked-in camp vault or encrypted on R2. As built today a Cluster secret meets NEITHER condition (read, not inferred). (1) Fleet copy: raft only. ClusterResolver reads the ciphertext from the LOCAL RAFT REPLICA (oss/yubaba/crates/yubaba/src/secrets.rs header), and the dev sovereign group is a separate raft (W348 section 1.4 precondition 3). The litestream sidecar is started for headscale (leader.rs header); no litestream wiring for raft was found. (2) The camp's durable copy is the `keys` vault W294 calls the camp vault. It is PER-HOST, not checked in: credentials.enc plus machine.key under ProjectDirs::data_dir (oss/yah-base/crates/keys/src/lib.rs header). `.yah/infra/secrets/<x>.toml` checks in only name / vault_slot / access. (3) The encrypted-on-R2 precedent already exists: cert_store keeps SecretRecord ciphertext sealed under the cluster KEK at certs/<issuer>/<domain>/{cert,key}.sealed (cert_store.rs header, R779), and tenant_passway materializes those records to files on the node. W294 has no R2 persistence plan (grep for R2 / object store / backup / restore found nothing).")
//! @yah:depends_on(R910-F1)
//! @yah:depends_on(R911)
//! @yah:verify("yubaba `cargo test -p yubaba --lib` 992/0, up from 983: +5 cert_store, +2 tenant_passway, +1 domain_issuer, +1 demux_routes scope test. `cargo check -p yubaba --all-targets` clean. workload-spec lib 207/0 and --test main 108/0; ts_drift green after export-ts; new jit_spec_renders_discovery_as_derived_keys. kamaji-proto 48/0. yah-cloud --lib 1215/36/4 against R911's recorded 1210/36/4 baseline: the 36 are the pre-existing R892 fixture refusals (migrate:: and topology:: plus one config:: test), none in ingress. +5 net: 6 new tunnel_door tests, one env-print test replaced, and the domain.rs stacked fixture given a tunnel_door.")
//! @yah:verify("PROD ROUTE-TABLE BASELINE before the roll, identical on us-south-001, us-east-001 and us-west-001: /var/lib/passway/routes/demux.routes sha256 7715dd94a419c98b8aae8d819bfa6fbef2a605ac6c40306bfa1ed3a3ce5bea90, http-router.routes 9c0f59f2277f1f7c0ea3dcbfc501f8315ac60ab39a08c947b0081d939fbf433a. After the roll both must be byte-identical (every live record is unscoped). Schema regen: mirror.toml.schema.json +45 (tunnel_door / TunnelDoor), workload.toml.schema.json +33 (TenantPasswayWorkload.discover); TS bindings +16/-1.")
//! @yah:gotcha("MACHINE NAME IS /etc/hostname, AND TWO PROD DOORS DO NOT CARRY THEIR MACHINE NAME (read over ssh 2026-09-15). Enrollment::serves_on matches leader::derive_machine_name(), which reads /etc/hostname. us-south-001, us-west-011, us-west-013 and us-west-014 match their machine names. us-east-001 is `vps-8dba9ff8` and us-west-001 is `vps-4c1efa56`. So a record scoped to us-east-001 or us-west-001 by machine name would route and arm nowhere. That fails closed (no leak), and this door, scoped to us-west-011, is unaffected. Fix before scoping a prod record: set those hostnames, or give derive_machine_name an explicit source (the machine TOML name via YUBABA_MACHINE or similar).")
//! @yah:verify("cloud-client `cargo test -p cloud-client --lib enrollment_body` 1/0. `cargo check -p yah` clean (EXIT=0).")
//! @yah:verify("Live after the full roll: every node's route tables equal the pre-roll baseline; after cutover, both staging hostnames serve through the tunnel with certs issued by the us-west-011 yubaba (records visible as certs/acme-v02.api.letsencrypt.org/<host>/*.sealed).")
//! @yah:gotcha("An older yubaba ignores Enrollment.machines and would publish a scoped route fleet-wide (prod and dev share the bucket). Do NOT run step 5 until step 2 has rolled every prod node.")
//! @yah:gotcha("apply's discovery wait (R844-B24) runs for the passway door plan too. If noisetable-staging's bundle is not deployed on 011, marketing's apply may stall or refuse at `no ready service record`, independent of R910.")
//! @yah:gotcha("The prior session's dev roll (qed run de242499) sat 9h with ZERO steps and was cancelled, and its /tmp log is gone. Re-run 2026-09-15 by session:6e319a10 directly via scripts/hotship.sh (log /tmp/r910f2-hotship-dev2.log). `yubaba --version` prints `0.8.39` on every node regardless of hotship stamp (kamaji prints its -hN stamp), so it cannot confirm a roll. Verify by behaviour or binary sha256 instead.")
//! @yah:gotcha("NO FLEET KAMAJI HAS EVER BEEN BUILT WITH --features tenant-passway (read 2026-09-15). Neither hotship.sh app_spec nor publish-yubaba-release.sh listed it. Setting KAMAJI_TENANT_PASSWAY_DIR on such a binary makes kamaji exit at startup (`--tenant-passway-dir requires the kamaji binary be built with --features tenant-passway`). Step 3 crash-looped us-west-011's kamaji for about a minute. Reverted: both drop-ins moved to /etc/yah-cloud/r910f2-{kamaji-40,yubaba-60}-tenant-passway.conf.disabled, kamaji and yubaba restarted, and noisetable-account-staging is Running again. FIXED in scripts/hotship.sh (kamaji app_spec) and scripts/publish-yubaba-release.sh (build line + header). Re-ship kamaji to 011 before re-enabling.")
//! @yah:verify("session:6e319a10: `cargo test -p yubaba --lib` (run from oss/yubaba; root-workspace -p yubaba fails EXIT=101) = 994 passed / 0 failed, up from 992 with 2 new cert_store tests (unscoped serves only under Fleet; scope env parse), and the demux and tenant_passway scope tests extended with the Named-on-011 case. `cargo check -p yubaba --all-targets` EXIT=0. `cargo check -p kamaji-bin --features containerd-integration,native-exec,bundle-serving,microvm,tenant-passway` (oss/kamaji) EXIT=0. hotship logs: /tmp/r910f2-hotship-{dev2,prod,011-kamaji,011-yubaba}.log all EXIT=0.")
//! @yah:gotcha("yubaba 0.8.39 `--version` on the node binary ignores the hotship stamp. Read the version from `curl <node>:7443/health`, which reports `0.8.40-hN` and kamaji_version. Prod yubaba binds its mesh IP only (100.64.0.{1,2,3}:7443), not localhost.")
//! @yah:gotcha("noisetable-marketing's staging bundle (`noisetable-staging`) has never been deployed on 011, so its door answers 503 `no ready upstreams` until step B's marketing apply succeeds. staging.noisetable.com is already 503 today, so there is no regression.")
//! @yah:verify("Prod scope-leak check: demux.routes 7715dd94a419c98b... and http-router.routes 9c0f59f2277f1f7c... on us-east-001, us-south-001 and us-west-001 were re-read after the api apply, after each marketing apply, and at 19:24Z. Identical every time; no leak.")
//! @yah:verify("External at 19:24Z: https://api-staging.noisetable.com 404 (vary headers, server cloudflare; still via the hand door), https://staging.noisetable.com 503 (unchanged pre-existing `no ready upstreams`).")
//! @yah:gotcha("kamaji ProtectSystem=strict + tenant passway: without write access to /var/lib/yah/passway, the held loopback socket accepts TCP and never answers TLS, and older kamaji logs nothing (WorkloadStatus flattens to Failed). Check `ss -ltn sport = :<port>` Recv-Q and the generation cgroup.procs before suspecting certs or passway.")
//! @yah:gotcha("The h20 ship to us-west-011 at 19:01Z on 2026-09-15 came from @Miravel:spade (session:03e340a3, a yah-camp chat session). It ran `scripts/hotship.sh --nodes us-west-011,us-west-013,us-west-014 --binaries yubaba,kamaji` (seen in camp.roster by leader session:0836b5e4). Miravel confirmed that the R910-F2 drop-ins survived and that kamaji attached the tenant-passway tier, and agreed to hold further 011 rolls until R910-F2 reaches review. Re-read /health before assuming which build runs there.")
//! @yah:handoff("CURRENT STATE (condensed 2026-09-15 by session:5283b15f; history is in events.jsonl and the W348 section 1.3 rewrite). A behind_tunnel passway door is declared as `[ingress.tunnel_door]` on the passway edge, and `yah cloud apply` writes one Enrollment per hostname scoped by `machines`, through a node on those machines. The scoped node's yubaba publishes the demux route (demux_routes), issues the cert by DNS-01 with the R911 cluster-secret token (domain_issuer::spawn_declared, sealed into cert_store), and has kamaji arm a cold loopback passway (tenant_passway). Operator decisions on record: native door, not the container appliance; all cluster secrets sealed in R2 (R911); scope the enrollment rail; fail-closed YUBABA_ENROLLMENT_SCOPE (Named default, Fleet on prod); hold the cutover until both hostnames were enrolled; cdn-staging.noisetable.com as the staging bundle origin.")
//! @yah:handoff("CODE (landed earlier, verified in verify): cert_store Enrollment{machines, acme, discover} + EnrollmentScope/ServingNode + declare_enrollment (Created/Unchanged/Replaced, BackendTaken, InvalidEnrollment); demux_routes / tenant_passway / domain_issuer filter by serving_on; yubaba GET/PUT/DELETE /domains/{domain}/enrollment; cloud config IngressEdge.tunnel_door + validate_tunnel_door; IngressPlan.door_backends; CLI apply passway arm; cloud-client EnrollmentBody/declare_enrollment; workload-spec TenantPasswayWorkload.discover; scripts/hotship.sh + publish-yubaba-release.sh build kamaji with tenant-passway; kamaji.service template grants /var/lib/yah/passway; kamaji jit.rs warns on on-demand fork/watch failure; yubaba.service RuntimeDirectory gains yah/passway yah/yubaba.")
//! @yah:handoff("FLEET: us-west-011 runs yubaba + kamaji 0.8.40-h20 with drop-ins kamaji 20-bundle, 40-tenant-passway, 41-tenant-passway-rw and yubaba 60-tenant-passway, 62-tenant-runtime-dirs, 63-demux-publisher (all recorded in .yah/infra/machines/us-west-011.toml, cap:bundle-serving added). Prod us-east-001 / us-south-001 / us-west-001 run scope-aware yubaba with 61-enrollment-scope.conf (YUBABA_ENROLLMENT_SCOPE=fleet); their demux.routes / http-router.routes are byte-identical to the pre-R910 baseline.")
//! @yah:handoff("LIVE DOORS (both enrolled scoped to us-west-011): api-staging.noisetable.com -> 127.0.0.1:8447 (written by `yah cloud apply --env staging --service noisetable-api`) and staging.noisetable.com -> 127.0.0.1:8448. staging was written by the operator-class PUT /domains/staging.noisetable.com/enrollment through 011 (leader decision: separate the door from the bundle, since noisetable-marketing's apply is gated on R719's engine edits). The body is exactly what apply's passway arm builds: discover.urls [http://100.64.0.10:7443] (passway_discovery_env for a literal-machines slot, matching api-staging's stored record), ident noisetable-staging (resolve_workload_ident from the bundle slot's name). Both certs are LE, issued by 011's yubaba. CUTOVER C DONE 20:13Z: 63-demux-publisher.conf (YUBABA_DEMUX_ROUTES_FILE=/var/lib/passway/routes/demux.routes + ReadWritePaths=/var/lib/passway/routes), and yubaba published both routes. Hand door passway-noisetable-staging is disabled; its env file and plaintext cf-token dir are deleted; rollback copy of the hand routes is at /root/r910f2-demux.routes.hand.")
//! @yah:handoff("NOISETABLE: marketing mirror port changed 8446 -> 8448 to match the record (see gotcha); `yah cloud validate` ok. R704-T4 updated with current state. The marketing bundle deploy (cdn-staging binding + noisetable-staging bundle on 011) is filed as noisetable R704-T7, open, waiting on R719's engine edits; its apply should report the enrollment `already current`.")
//! @yah:verify("2026-09-15 session:5283b15f, live. On 011: GET /domains/staging.noisetable.com/enrollment was 404 before the write. PUT on 127.0.0.1:8446 returned 409 BackendTaken (holder scrabcake.com). PUT on 127.0.0.1:8448 returned 200 declared=created (20:05:45Z; logs /tmp/r910f2-staging-enroll-put{,2}.log). Journal: `domain issuer: issued and stored` 20:08:36Z, `tenant passway: materialized cert pair domain=staging.noisetable.com` 20:12:16Z. `curl --resolve staging.noisetable.com:8448:127.0.0.1` returned 503 no ready upstreams with ssl_verify=0; openssl showed CN=staging.noisetable.com, LE YE1, notAfter 2026-12-14.")
//! @yah:verify("Cutover C (log /tmp/r910f2-cutover-c.log): after 63-demux-publisher.conf and a yubaba restart, journal shows `route table published domains=2` at 20:13:17Z. /var/lib/passway/routes/demux.routes = api-staging.noisetable.com=127.0.0.1:8447, staging.noisetable.com=127.0.0.1:8448. /health still yubaba+kamaji 0.8.40-h20, scope Named. Hand door retired (log /tmp/r910f2-retire-hand-door.log): unit inactive and disabled, env file and cf-token dir gone, nothing on :8445.")
//! @yah:verify("External, after retirement, 20:14:43Z: https://api-staging.noisetable.com/ 404 with vary: origin, access-control-request-method, access-control-request-headers; https://staging.noisetable.com/ 503 {\"error\":\"no ready upstreams\"} from the staging passway (its stderr log records the request).")
//! @yah:verify("Prod leak check: demux.routes 7715dd94a419... and http-router.routes 9c0f59f2277f... are identical on us-east-001, us-south-001 and us-west-001 before the write, right after it, after a full 300s publisher sweep, and after the cutover (4 reads each). `yah cloud validate --path ~/ss/noisetable` EXIT=0 after the mirror port change and the R704-T7 annotation.")
//! @yah:gotcha("A TUNNEL DOOR'S DECLARED PORT MUST BE FREE IN THE WHOLE ENROLLMENT SET, NOT JUST ON ITS NODE. declare_enrollment refuses a tls_backend that any overlapping record holds, and an unscoped prod tenant record overlaps every machine. Prod tenants hold 127.0.0.1:8443-8446 today (read from us-south-001's demux.routes), so staging's declared 8446 was refused (409, holder scrabcake.com) and moved to 8448. `yah cloud validate` cannot see this, because the enrollment set lives in the cert-store bucket and not in the tree. Before declaring a new tunnel_door port, read a prod door's demux.routes or GET the candidate.")
//! @yah:cleanup("On the next kamaji hotship to us-west-011: the shipped kamaji.service template grants /var/lib/yah/passway and jit.rs warns on on-demand fork/watch failure, so a unit rendered from the template makes 011's 41-tenant-passway-rw.conf redundant. Remove it then.")
//! @yah:cleanup("/root/r910f2-demux.routes.hand on us-west-011 is a rollback copy of the retired hand routes. Delete it once the publisher-owned table has run a while.")
//! @yah:cleanup("The ticket's gotchas still include the prod /etc/hostname trap (us-east-001=vps-8dba9ff8, us-west-001=vps-4c1efa56) and the rule to confirm 61-enrollment-scope.conf before any prod yubaba roll. Both remain true and unfixed.")

use std::collections::HashMap;

use anyhow::{bail, Context, Result};
use local_driver::passway_ingress::PasswayAuth;
use serde_json::{json, Value};
use tracing::{debug, info};

use crate::config::{
    resolve_machines_among, IngressEdge, IngressProvider, IngressVia, RequiredSpec, TunnelDoor,
};
use crate::{CloudflareClient, MachineConfig, MirrorConfig};

/// Slot field naming the public hostname a slot is fronted at.
const ZONE_FIELD: &str = "zone";
/// Slot field pinning the node-local port the front door dials. Already
/// `BundleSlot.port`'s meaning — the port kamaji binds the workload to and the
/// port the front door dials are the same port, so this reuses that field
/// rather than minting a parallel one.
///
/// **A value, no longer the opt-in** (R844-F5). It used to be both, which meant
/// deleting the key did not remove a pin — it removed the *slot* from the plan,
/// silently un-publishing a live hostname. [`FRONTED_FIELD`] now carries the
/// participation half, and this one is optional: a rule that declares no port
/// gets it from the fronting node's `GET /service-records?ready=true` via
/// [`IngressPlan::resolve_ports`], where `resolved_ports` reports what the
/// supervisor actually bound (R844-F2) rather than what a mirror asked for.
///
/// Declaring it still implies participation, so every mirror on disk plans
/// byte-identically across that change — and an explicit pin always wins over
/// discovery, exactly as [`UPSTREAM_HOST_FIELD`] does.
const PORT_FIELD: &str = "port";
/// Slot field that opts a slot into the front door and says nothing else:
/// `fronted = true` means "publish me", with the port left to discovery.
///
/// Its own field rather than a reuse of `zone`, because `zone` is overloaded: a
/// CDN-published static slot carries it meaning the *Cloudflare zone*. Keying
/// participation off `zone` would drag every such slot into the ingress plan
/// and fail the apply of mirrors that have no front door at all. Nor can the
/// `[[ingress]]` edge selector serve — every mirror on disk uses the scalar
/// spelling, which yields one selectorless edge that claims everything, so it
/// would drag in exactly the same static slots. The signal has to be slot-side
/// and mean one thing.
///
/// `fronted = false` is not an opt-*out* of a declared `port`: a slot with a
/// port is fronted regardless, which keeps the one silent-de-listing shape this
/// field exists to remove from reappearing under a new spelling.
const FRONTED_FIELD: &str = "fronted";
/// Slot field naming the machine the fronted workload runs on.
const MACHINE_FIELD: &str = "machine";
/// Plural spelling of [`MACHINE_FIELD`], used by placement-list slots such as
/// `[providers.bundle]`. Read as a fallback so a bundle tier is plannable at
/// all — before this, `machines = ["us-east-001"]` was invisible to the planner
/// and every rule derived from a bundle slot resolved no upstream.
///
/// **Read whole** (R844-F3). It used to contribute only its first entry, on the
/// premise that a workload placed on several nodes still answers on any one of
/// them — which R844-F4 disproved by measurement: the service-record store is
/// node-local (a `watch` + a per-node JSON ledger, replicated nowhere), so node
/// A's answer covers node A's workloads and no others. Discarding the rest of
/// the list therefore aimed discovery at a strict subset of the declared
/// placement and rendered a strict subset of the backends — a front door that
/// looks like it worked. The whole list now lands in
/// [`IngressRule::machines`], the fanout asks every entry
/// ([`IngressPlan::workload_machines`]) and the renderer carries every answer
/// ([`IngressRule::upstream_hosts`]).
///
/// Front-door placement remains a different question with its own field —
/// `MirrorConfig::ingress_machines`. Widening the workload's placement set must
/// never be read as deploying a second copy of the workload; it says where the
/// already-declared copies are, so that discovery can find all of them.
const MACHINES_FIELD: &str = "machines";
/// Slot field pinning the address the front door dials, overriding discovery.
const UPSTREAM_HOST_FIELD: &str = "upstream_host";

/// What a `via = "passway"` tunnel dials (R910): the node's sni-demux on
/// loopback.
///
/// `passway-demux` owns `:443` on a door node and splices each connection, by
/// SNI and still encrypted, to the per-tenant passway its route table names.
/// So the tunnel needs no per-tenant port — the demux maps hostname → passway
/// exactly as it does for a browser on a public door — and the scheme is
/// `https` because the TLS handshake cloudflared makes is with passway itself.
pub const PASSWAY_DEMUX_ORIGIN: &str = "https://127.0.0.1:443";

/// One hostname→local-port rule the front door must publish.
///
/// Provider-agnostic by construction: [`service_url`](Self::service_url)
/// renders it for cloudflared, [`passway_upstream`](Self::passway_upstream)
/// for passway's `PASSWAY_UPSTREAMS` grammar (R594-F10 host fan-in).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IngressRule {
    /// Public hostname, e.g. `analytics.yah.dev`.
    pub hostname: String,
    /// Node-local port the fronted workload listens on — `None` until
    /// [`IngressPlan::resolve_ports`] fills it, for a slot that declared
    /// `fronted = true` without pinning a number.
    ///
    /// Optional for the same reason [`upstream_hosts`](Self::upstream_hosts) is
    /// resolved rather than defaulted (R844-F5): once kamaji allocates the port
    /// (`PortAllocator::resolve`), the number the workload actually bound is
    /// unknowable from the mirror, so a rule that carried a `u16` could only
    /// carry a *declaration* — and the front door dialing a declared number
    /// while the supervisor bound another one fails at request time, long after
    /// the apply that looked clean. A declared `port` still wins; discovery
    /// only answers where the mirror stayed silent.
    pub port: Option<u16>,
    /// Mirror provider slot this rule was derived from (`"compute"`, …). Kept
    /// so an error or a summary line can name the slot the operator wrote.
    pub slot: String,
    /// The slot's `use = "<provider-id>"`, when it references an infra-declared
    /// provider. The cloudflare-tunnel arm resolves its account id + API token
    /// through this, exactly as the R2 custom-domain reconciler does.
    pub provider_id: Option<String>,
    /// Every node the fronted **workload** is placed on, in declaration order:
    /// the slot's `machine = "<name>"` (one entry), its `machines = [...]` list
    /// (all of them), or the constraint-resolved placement
    /// [`resolve_ingress_placements`] hands in. Empty when the slot declares no
    /// placement at all.
    ///
    /// A set, not an option (R844-F3). One entry is the common case and stays
    /// exact; a workload at horizontal scale > 1 is a set, and the two facts
    /// this drives — which nodes the discovery fanout must ask, and which node's
    /// `MachineConfig.cloudflared` tunnel the rules publish to — are both
    /// wrong when the set is silently truncated to its first element.
    pub machines: Vec<String>,
    /// Every address the front door dials this workload at — one per live
    /// backend. Empty until [`IngressPlan::resolve_upstreams`] (or
    /// [`resolve_upstreams_from`](IngressPlan::resolve_upstreams_from)) runs, or
    /// a single pinned entry when the slot declares `upstream_host`.
    ///
    /// **Not a defaultable field.** Loopback used to be a safe assumption —
    /// kamaji forked `mesofact-serve --listen 127.0.0.1:<port>` and every front
    /// door was co-located with what it fronted. R599-F12 changed that:
    /// `native_bind_ip` now binds the workload's allocated `MeshAssignment`
    /// mesh IP, so a rule that assumed loopback would dial a port nothing is
    /// listening on — and fail at *request* time, long after the apply that
    /// looked clean. The mesh IP is allocated by yubaba at deploy time and is
    /// therefore unknowable from the mirror, so it has to be resolved, not
    /// guessed.
    ///
    /// **Plural because the fan-out is real** (R844-F3): a workload on N nodes
    /// has N mesh IPs, and passway's `PASSWAY_UPSTREAMS` grammar already load
    /// balances several entries sharing a hostname (`parse_upstream_sets` pushes
    /// into one set per host key). Collapsing to one here would publish one
    /// backend out of N while every line in the mirror still read correctly.
    pub upstream_hosts: Vec<String>,
}

impl IngressRule {
    /// Every `host:port` the front door dials, once resolved — one per backend,
    /// in resolution order.
    ///
    /// Erroring on empty rather than returning an empty vec is the point: a
    /// front door that publishes a hostname with no backend advertises a 502,
    /// which is worse than a failed apply.
    ///
    /// **The single place an undialable rule is reported** (R844-F5). A rule
    /// needs two resolved halves — a port and at least one address — and both
    /// come from the same discovery read, so a rule missing both says so in one
    /// message here rather than failing twice in two different words.
    pub fn upstreams(&self) -> Result<Vec<String>> {
        let (Some(port), false) = (self.port, self.upstream_hosts.is_empty()) else {
            let mut missing: Vec<String> = Vec::new();
            if self.port.is_none() {
                missing.push(format!(
                    "no resolved port: the slot declares `{FRONTED_FIELD} = true` without \
                     `{PORT_FIELD}`, so the number has to come from the node's `resolved_ports` \
                     (R844-F2) and no ready record supplied one"
                ));
            }
            if self.upstream_hosts.is_empty() {
                missing.push(format!(
                    "no resolved upstream address: the workload's mesh IP is allocated at \
                     deploy time (R599-F12), so it cannot come from the mirror"
                ));
            }
            return Err(anyhow::anyhow!(
                "slot [providers.{}] fronted at {} cannot be dialed — {}. Either the fronting \
                 node's `GET /service-records?ready=true` must report a ready record for it, or \
                 the slot must pin `{PORT_FIELD} = <n>` / `{UPSTREAM_HOST_FIELD} = \"<addr>\"` \
                 explicitly.",
                self.slot,
                self.hostname,
                missing.join("; ")
            ));
        };
        Ok(self
            .upstream_hosts
            .iter()
            .map(|host| format!("{host}:{port}"))
            .collect())
    }

    /// Every backend as a **displayable** `host:port`, resolved halves shown and
    /// unresolved ones spelled `<unresolved>` — never an error (R844-T10).
    ///
    /// The read-only counterpart of [`upstreams`](Self::upstreams), for a
    /// renderer whose job is to describe the plan rather than to act on it:
    /// `yah cloud ingress collate` and `yah cloud validate`. Those make no
    /// network call by design, so a rule taking its port from the supervisor
    /// (`fronted = true`, no `port`) is *expected* to be half-resolved there and
    /// reporting it as a failure would train an operator to ignore the output.
    ///
    /// It shows **each half independently**, which is the whole point. The
    /// previous rendering collapsed any error to `<unresolved>:<port_label>` and
    /// so threw away a known address — after R844-F12 the host resolves offline
    /// from the placement machine's declared `mesh_ipv4`, so a portless apex now
    /// reads `100.64.0.3:<unresolved>` and names exactly the one fact that is
    /// genuinely runtime, instead of claiming ignorance of both.
    ///
    /// **Not evidence the front door works.** Nothing here is a measurement:
    /// the address comes from a mirror or a machine toml, so a rule can render
    /// perfectly and still dial nothing. That distinction has cost this camp a
    /// 19-day outage once already, via a pinned `upstream_host` left at
    /// `127.0.0.1` that every collation printed back confidently.
    pub fn upstream_labels(&self) -> Vec<String> {
        let port = self.port_label();
        if self.upstream_hosts.is_empty() {
            return vec![format!("<unresolved>:{port}")];
        }
        self.upstream_hosts
            .iter()
            .map(|host| format!("{host}:{port}"))
            .collect()
    }

    /// This rule's port for a message — the number, or `<unresolved>` before
    /// [`IngressPlan::resolve_ports`] has answered for it.
    ///
    /// Exists so every diagnostic renders an unresolved port the same way. A
    /// call site formatting `Option<u16>` directly prints `None`, which reads
    /// as a bug in the tool rather than a fact about the fleet.
    pub fn port_label(&self) -> String {
        self.port
            .map(|p| p.to_string())
            .unwrap_or_else(|| "<unresolved>".to_string())
    }

    /// The **first** `host:port`, for a renderer that can carry only one backend
    /// per hostname.
    ///
    /// Not a deprecated spelling of [`upstreams`](Self::upstreams): cloudflared's
    /// ingress grammar takes exactly one `service` per hostname rule, and its
    /// high availability comes from running several *connectors* into the tunnel,
    /// not from listing several services. So the tunnel arm genuinely collapses
    /// the set, and does it here in one named place rather than by indexing
    /// `[0]` at each call site.
    pub fn upstream(&self) -> Result<String> {
        Ok(self
            .upstreams()?
            .into_iter()
            .next()
            .expect("upstreams() errors rather than returning empty"))
    }

    /// cloudflared ingress-rule `service` target — the first backend, per
    /// [`upstream`](Self::upstream).
    pub fn service_url(&self) -> Result<String> {
        Ok(format!("http://{}", self.upstream()?))
    }

    /// This rule's `PASSWAY_UPSTREAMS` entries in the R594-F10 host-prefixed
    /// form — **one per backend**, all sharing the hostname.
    ///
    /// Repeating a hostname is the grammar's own load-balancing spelling, not an
    /// abuse of it: passway's `parse_upstream_sets` collects entries into a
    /// `BTreeMap<HostKey, Vec<SocketAddr>>` and builds one load balancer per
    /// host key. Emitting a single entry for a workload on N nodes would send
    /// every request to one of them.
    pub fn passway_upstreams(&self) -> Result<Vec<String>> {
        Ok(self
            .upstreams()?
            .into_iter()
            .map(|addr| format!("{}={addr}", self.hostname))
            .collect())
    }
}

/// What **one declared edge** has to publish.
///
/// A mirror yields one of these per [`IngressEdge`](crate::config::IngressEdge)
/// it declares, with the fronted rules partitioned across them — so two plans
/// from one mirror never publish the same hostname through two front doors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IngressPlan {
    pub provider: IngressProvider,
    /// Derived rules, ordered by hostname so a plan is stable across runs and
    /// two applies produce byte-identical config.
    pub rules: Vec<IngressRule>,
    /// Machines the front door is placed on (R330-F37), in declaration order.
    ///
    /// Never empty when the mirror declares an ingress provider *and* the
    /// fronted slots name machines: it falls back to the union of their
    /// placements, which is the co-located shape every mirror had before this
    /// field existed, widened to every node the workload runs on (R844-F3). It
    /// **is** empty when neither is declared, and each provider arm decides
    /// whether that is an error (the tunnel arm) or a placeholder (passway's
    /// rendered deploy line).
    ///
    /// Independent of [`IngressRule::machines`] by design, even though the
    /// fallback is derived from it: this is where the *front door* runs, that is
    /// where the *workload* runs. Declaring `ingress_machines` fixes this list
    /// and the workload's placement has no further say — which is what lets the
    /// ingress tier be wider (or narrower) than the service tier.
    pub front_doors: Vec<String>,
    /// Cloudflare Tunnel id this edge declared, overriding the fronting
    /// machine's own (W267 Gap 3). `None` means "use the node's" — the common
    /// case, and the only shape that existed before W305 F2.
    pub tunnel_id: Option<String>,
    /// Provider id this edge declared its credentials under (`use = "…"` on the
    /// `[[ingress]]` entry). `None` means "read it off the fronted slot" — the
    /// only shape that existed before R845.
    ///
    /// Kept raw beside the resolved [`provider_id`](Self::provider_id) accessor
    /// on purpose: an apply that wants to prefer a *Cloudflare-kind* slot over
    /// whichever slot happened to sort first can only do that if it can tell an
    /// explicit declaration from a derived one.
    pub edge_provider_id: Option<String>,
    /// This edge's declared appliance image, verbatim from
    /// [`IngressEdge::image`] (R870-F16). `None` is every mirror on disk
    /// today, and means the passway arm of `yah cloud apply` can only print
    /// the manual deploy step — there is no digest-pinned image to push.
    pub image: Option<String>,
    /// This edge's declared bearer auth, verbatim from [`IngressEdge::auth`]
    /// (R870-F26), already validated by
    /// [`MirrorConfig::ingress_edges`](crate::config::MirrorConfig::ingress_edges).
    ///
    /// `Some` is what makes `yah cloud apply`'s Passway push carry the five
    /// `PASSWAY_AUTH_*` variables and the Cluster→File verify-key mount instead
    /// of replacing an authenticated door with an anonymous one. `None` is the
    /// shape every mirror on disk has, and lowers byte-identically to what the
    /// arm produced before this field existed.
    pub auth: Option<PasswayAuth>,
    /// The front door this **tunnel** edge stacks in front of, verbatim from
    /// [`IngressEdge::via`] (R910). `Some` changes what the tunnel dials — the
    /// node's demux rather than the workload — see
    /// [`tunnel_rule`](Self::tunnel_rule). `None` on every other plan.
    pub via: Option<IngressVia>,
    /// `true` on a **passway** plan a `via = "passway"` tunnel edge in the same
    /// mirror stacks in front of (R910). Derived by [`partition`], never
    /// declared.
    ///
    /// It is the passway side's half of the pair, and it changes what that
    /// door is: nothing public reaches it, so it listens on loopback, publishes
    /// no apex record, and can only issue a certificate by DNS-01 — see
    /// [`door_backends`](Self::door_backends). The public appliance
    /// `yah cloud apply` otherwise pushes (manual cluster cert on `0.0.0.0:443`,
    /// `public-ip` taint) is the wrong door for it.
    pub behind_tunnel: bool,
    /// This edge's `[ingress.tunnel_door]`, verbatim (R910-F2). `partition`
    /// guarantees it is `Some` exactly when [`behind_tunnel`](Self::behind_tunnel)
    /// is, with a port for every rule's hostname.
    pub tunnel_door: Option<TunnelDoor>,
}

impl IngressPlan {
    /// The `service` cloudflared dials for `rule`: the workload's first
    /// backend, or — on a `via = "passway"` edge — the node's sni-demux
    /// ([`PASSWAY_DEMUX_ORIGIN`]), independent of where the workload runs.
    pub fn tunnel_service(&self, rule: &IngressRule) -> Result<String> {
        match self.via {
            None => rule.service_url(),
            Some(IngressVia::Passway) => Ok(PASSWAY_DEMUX_ORIGIN.to_string()),
        }
    }

    /// `rule` as one entry of a tunnel's remotely-managed `ingress` list.
    ///
    /// The stacked form carries `originRequest.matchSNItoHost = true`, and the
    /// shape does not work without it: cloudflared would otherwise send the
    /// service URL's host (`127.0.0.1`) as SNI, the demux has no route for that
    /// name, and passway never sees the hostname it holds a certificate for.
    ///
    /// Origin TLS verification is left **on** (`noTLSVerify` is simply not
    /// written, and defaults false). With the SNI set to the real hostname,
    /// passway's own ACME certificate verifies — the hand-enrolled
    /// noisetable R704-T4 door runs exactly this config and serves end to end —
    /// and turning verification off would let anything that binds loopback
    /// `:443` serve the site.
    pub fn tunnel_rule(&self, rule: &IngressRule) -> Result<Value> {
        let service = self.tunnel_service(rule)?;
        Ok(match self.via {
            None => json!({ "hostname": rule.hostname, "service": service }),
            Some(IngressVia::Passway) => json!({
                "hostname": rule.hostname,
                "service": service,
                "originRequest": { "matchSNItoHost": true },
            }),
        })
    }

    /// The loopback socket each hostname's door listens on, for a door behind a
    /// tunnel ([`behind_tunnel`](Self::behind_tunnel)) — sorted by hostname,
    /// one entry per hostname. Empty for any other plan (R910-F2).
    ///
    /// **Loopback**, because the demux owns `:443` and cloudflared dials the
    /// demux, so nothing public ever reaches the door. Each hostname is its own
    /// door with its own certificate — the per-tenant shape yubaba's tenant
    /// tier arms — which is why `[ingress.tunnel_door].ports` is per hostname.
    /// `yah cloud apply` turns each entry into one scoped enrollment.
    pub fn door_backends(&self) -> Vec<(String, std::net::SocketAddr)> {
        let Some(door) = self.tunnel_door.as_ref().filter(|_| self.behind_tunnel) else {
            return Vec::new();
        };
        let mut out = std::collections::BTreeMap::new();
        for rule in &self.rules {
            if let Some(port) = door.ports.get(&rule.hostname) {
                out.insert(
                    rule.hostname.clone(),
                    std::net::SocketAddr::from(([127, 0, 0, 1], *port)),
                );
            }
        }
        out.into_iter().collect()
    }

    /// Every rule rendered as a `PASSWAY_UPSTREAMS` entry, ready to hand to
    /// `PasswayIngressSpec::upstreams`.
    pub fn passway_upstreams(&self) -> Result<Vec<String>> {
        let mut out = Vec::new();
        for rule in &self.rules {
            out.extend(rule.passway_upstreams()?);
        }
        Ok(out)
    }

    /// Fill in the address each rule's front door dials.
    ///
    /// A rule that pinned `upstream_host` on its slot keeps it — an explicit
    /// operator override always wins, and it is the escape hatch for a node
    /// with no mesh plane. Every other rule is handed to `discover`, which the
    /// apply layer backs with the fronting node's
    /// `GET /service-records?ready=true` — the same surface passway's own
    /// `YubabaUpstreams` consumes (R594-F8). That is the seam rule restated:
    /// **an ingress provider derives its config from placement.** A proxy you
    /// hand an address list to is a deployment, not a provider.
    ///
    /// A rule left unresolved is an error here rather than a dead upstream
    /// later. Discovery returning `Ok(None)` for a rule means the control plane
    /// answered and has no ready record on that port — the workload is not up,
    /// so publishing a hostname for it would advertise a 502.
    /// `discover` answers with **every** address serving the rule, not the first
    /// one: a workload at horizontal scale > 1 has one per node it runs on, and
    /// the renderer carries the whole set (R844-F3). An empty vec means the
    /// control plane answered and has no ready record.
    pub fn resolve_upstreams<F>(&mut self, mut discover: F) -> Result<()>
    where
        F: FnMut(&IngressRule) -> Result<Vec<String>>,
    {
        for rule in &mut self.rules {
            if !rule.upstream_hosts.is_empty() {
                continue;
            }
            rule.upstream_hosts = discover(rule)?;
            // Surface the failure with the rule's own context.
            rule.upstreams()?;
        }
        Ok(())
    }

    /// Repoint every rule at this node's **inner door** (R870-F23 step 5).
    ///
    /// A service whose components deploy independently has no single workload a
    /// hostname can front: the outer door's job becomes "reach the thing that
    /// splits the paths", and that thing is a passway on loopback. So every
    /// rule's upstream becomes `127.0.0.1:<port>` and the inner door owns the
    /// fan-out from there.
    ///
    /// **This OVERRIDES, where [`resolve_upstreams`](Self::resolve_upstreams)
    /// and [`resolve_ports`](Self::resolve_ports) fill in.** Those two leave an
    /// operator's `upstream_host` / `port` pin alone, because a pin is an
    /// explicit statement about the same backend discovery would have found.
    /// An inner door is not that: a pin names ONE unit, and fronting a
    /// two-unit service from one of its units serves half the site and 503s the
    /// other half. So the halves are cleared first and then re-resolved through
    /// the same two methods — which keeps this the only place in the crate that
    /// writes those fields, rather than a third one that could drift from their
    /// error handling.
    ///
    /// Idempotent, and byte-identical across two applies: the port is derived
    /// from the service name (`inner_door::listen_port`), not allocated.
    pub fn point_at_inner_door(&mut self, port: u16) -> Result<()> {
        for rule in &mut self.rules {
            rule.port = None;
            rule.upstream_hosts.clear();
        }
        self.resolve_ports(|_| Ok(Some(port)))?;
        self.resolve_upstreams(|_| Ok(vec![crate::inner_door::INNER_DOOR_HOST.to_string()]))
    }

    /// Fill in the node-local port each rule's front door dials.
    ///
    /// The port half of [`resolve_upstreams`](Self::resolve_upstreams), and the
    /// step that lets a mirror say `fronted = true` without pinning a number
    /// (R844-F5). `discover` is backed by the fronting node's
    /// `GET /service-records?ready=true`, whose `resolved_ports` is what the
    /// supervisor **bound** rather than what a mirror asked for — the only
    /// source that stays correct once kamaji allocates the port.
    ///
    /// A rule that declared `port` keeps it: an explicit operator pin always
    /// wins, exactly as `upstream_host` does, which is why every mirror on disk
    /// applies byte-identically across this change.
    ///
    /// **Call this before [`resolve_upstreams`](Self::resolve_upstreams)**, not
    /// after: discovery matches a record *by port*, so a rule whose port is
    /// still `None` cannot pick its address out of a node running several
    /// workloads.
    ///
    /// Leaving a rule unresolved is deliberately **not** an error here.
    /// [`IngressRule::upstreams`] is already the single place an undialable
    /// rule is reported, and a rule that resolved neither half should say that
    /// once rather than twice.
    ///
    /// Pure, like the planner it follows: the caller does the read and hands
    /// the answer in, so `plan_ingress` keeps taking no network and
    /// `xtask/tests/mirror_ingress.rs` keeps planning the real tree as a unit
    /// test. Third instance of that shape, after
    /// [`resolve_ingress_placements`] and
    /// [`resolve_upstreams`](Self::resolve_upstreams).
    pub fn resolve_ports<F>(&mut self, mut discover: F) -> Result<()>
    where
        F: FnMut(&IngressRule) -> Result<Option<u16>>,
    {
        for rule in &mut self.rules {
            if rule.port.is_some() {
                continue;
            }
            rule.port = discover(rule)?;
        }
        Ok(())
    }

    /// Fill in each rule's upstream address from its placement machines'
    /// **declared** mesh addresses — the offline half of upstream resolution
    /// (R844-F12).
    ///
    /// This is what lets a slot drop `upstream_host` without giving up offline
    /// planning. The pin was never a fact only the network knew: a rule's
    /// placement set is already machine *names*
    /// ([`IngressRule::machines`], R844-F3), and every machine's
    /// `[registration].mesh_ipv4` is right there in `.yah/infra/machines/`. So
    /// the pin was a hand-copy of a value the config already stated twice —
    /// `.yah/infra/machines/us-east-001.toml` says `mesh_ipv4 = "100.64.0.3"`
    /// and the apex mirror said `upstream_host = "100.64.0.3"` — with nothing
    /// keeping the two in step. The copy has drifted before: this mirror's pin
    /// was once found still naming `127.0.0.1` after a second front door
    /// existed, and every rendered rule looked correct.
    ///
    /// **Declared, not authoritative.** Run this only where there is no live
    /// read to have — `yah cloud ingress collate`, `yah cloud validate`, the
    /// `xtask` suite. The apply path resolves through
    /// [`resolve_upstreams_from`](Self::resolve_upstreams_from) instead, and
    /// must keep doing so: a service record reports the address the supervisor
    /// actually bound, while this reports what a TOML claims, and when they
    /// disagree the TOML is the one that can be stale. Calling this *before*
    /// discovery would silently make the stale value win, since every resolver
    /// here skips a rule that already has an address — the exact
    /// confidently-wrong shape R844 exists to remove. It is the offline
    /// renderer's answer, not a second source of truth.
    ///
    /// Pure: `mesh_addrs` is handed in as data by a caller that already loaded
    /// the machine tomls ([`machine_mesh_addrs`]), so `plan_ingress` and
    /// everything after it still take no network, no credentials and no
    /// `CloudConfig` — the property `xtask/tests/mirror_ingress.rs` depends on
    /// to plan the camp's real `.yah/services` tree as a unit test. Fourth
    /// instance of that shape, after [`resolve_ingress_placements`],
    /// [`resolve_upstreams`](Self::resolve_upstreams) and
    /// [`resolve_ports`](Self::resolve_ports).
    ///
    /// Silent where it cannot answer, like [`resolve_ports`](Self::resolve_ports):
    /// a machine with no declared `mesh_ipv4` contributes nothing and the rule
    /// stays empty, so [`IngressRule::upstreams`] remains the single place an
    /// undialable rule is reported. A rule that already has an address — a
    /// pinned `upstream_host`, or a discovery answer — is left alone.
    pub fn resolve_upstreams_from_config(&mut self, mesh_addrs: &HashMap<String, String>) {
        for rule in &mut self.rules {
            if !rule.upstream_hosts.is_empty() {
                continue;
            }
            // Declaration order, matching `machines` — the renderer emits one
            // `PASSWAY_UPSTREAMS` entry per backend and a reordered set would
            // look like drift on every apply.
            rule.upstream_hosts = rule
                .machines
                .iter()
                .filter_map(|name| mesh_addrs.get(name).cloned())
                .collect();
        }
    }

    /// Provider id the front door's credentials resolve through — the edge's
    /// own `use`, falling back to the `use` of the first fronted slot that
    /// names one.
    ///
    /// The fallback is why every mirror on disk before R845 keeps working: it
    /// *is* the pre-R845 rule. It is only a fallback, though, because the two
    /// answers are different facts — the slot's `use` says what runs the
    /// compute, the edge's says whose account holds the tunnel — and they
    /// coincide only when the same vendor does both.
    ///
    /// Unlike [`tunnel_id`](Self::tunnel_id), whose fallback (the node's
    /// `MachineConfig.cloudflared`) lives in a config tree this pure planner
    /// deliberately cannot see, this one resolves here: both candidates are
    /// already in the plan.
    pub fn provider_id(&self) -> Option<&str> {
        self.edge_provider_id
            .as_deref()
            .or_else(|| self.slot_provider_ids().next())
    }

    /// Every provider id the fronted slots name, in rule order.
    ///
    /// The apply layer uses this to pick the slot that references a
    /// *Cloudflare-kind* provider rather than whichever slot sorted first —
    /// a distinction [`provider_id`](Self::provider_id) cannot make, because a
    /// pure planner has no view of `.yah/infra/providers/`.
    pub fn slot_provider_ids(&self) -> impl Iterator<Item = &str> {
        self.rules.iter().filter_map(|r| r.provider_id.as_deref())
    }

}

/// The edges this mirror declares — empty when it has none.
///
/// The dispatch-layer predicate, mirroring
/// [`mesofact_bundle::slot_declared`](super::mesofact_bundle::slot_declared):
/// checked before any provider-specific work runs.
pub fn declared(mirror: &MirrorConfig) -> Result<Vec<IngressEdge>> {
    mirror.ingress_edges()
}

/// Resolve the machine each provider slot's `required = { … }` constraint
/// (F16 placement) implies, for slots that declare no literal `machine` /
/// `machines` field (R772).
///
/// [`plan_ingress`] cannot do this itself — it is deliberately pure, with no
/// view of `.yah/infra/machines/`, which is what lets `xtask/tests/
/// mirror_ingress.rs` plan the real tree as a unit test with no config tree to
/// build. So the caller resolves placements *first*, against the machines it
/// already has, and hands the result to `plan_ingress` as data — the same
/// shape [`IngressPlan::resolve_upstreams`] already uses for discovery. This
/// is what makes `providers.bundle.required = { regions, mesh_tags }`
/// plannable at all: before this existed, replacing a bundle slot's literal
/// `machines` with a constraint took `IngressPlan::workload_machine()` from
/// `Some(node)` to `None`, silently un-aiming upstream discovery — measured on
/// `.yah/services/yah-marketing/mirrors/cloud.toml`'s bundle slot, which now
/// uses this fallback for real.
///
/// Takes `&[MachineConfig]` rather than a full `CloudConfig` deliberately: a
/// caller collating every mirror in the workspace (`collate_workspace_ingress`)
/// has no business hard-failing over an unrelated mirror's
/// `providers.X.use = "<id>"` typo, which a full `CloudConfig::load` would do.
///
/// A slot with a literal `machine` / `machines` field is left alone — that
/// field wins in [`plan_ingress`] regardless of what this returns. Only a slot
/// with `required` and no literal placement is resolved, and a match failure
/// is a loud error naming the slot: a front door whose workload cannot be
/// placed is exactly the silent-trap shape this exists to close.
///
/// **Set-valued, and resolving to as many as the constraint declares
/// (R844-F8).** The return type is a placement *set* per role because that is
/// what [`IngressRule::machines`] carries and what the discovery fanout asks.
/// A `required` block with no `replicas` still resolves to exactly one machine
/// — every mirror on disk is that shape, and they all resolve byte-identically
/// — while `replicas = N` resolves to the first N machines the constraint
/// matches.
///
/// **The count is declared, never inferred from the match count.** A constraint
/// matching four nodes and asking for two places on two; otherwise adding a box
/// to the fleet would silently scale a production front door.
///
/// The reason R844-F3 stopped at one, and the invariant that replaces it: this
/// and the deploy-side resolver
/// ([`resolve_bundle_machines`](super::mesofact_bundle::resolve_bundle_machines))
/// must agree **set for set**, not merely in count, or the planner aims
/// discovery at nodes nothing was ever deployed to and the front door renders a
/// *subset* of the backends — the failure that looks like it worked. They now
/// agree by construction rather than by test: both bottom out in the same
/// `select_matching` over the same declaration-ordered `cfg.machines` slice
/// (here via [`resolve_machines_among`], there via `CloudConfig::resolve_machines`).
///
/// A slot declaring a literal `machines = [a, b]` is still untouched by this
/// and read whole by [`plan_ingress`] — that remains the imperative spelling of
/// horizontal scale, beside the derived one.
pub fn resolve_ingress_placements(
    machines: &[MachineConfig],
    mirror: &MirrorConfig,
) -> Result<HashMap<String, Vec<String>>> {
    let mut placements = HashMap::new();
    for (role, slot) in &mirror.providers {
        let fields = slot.fields();
        if fields.contains_key(MACHINE_FIELD) || fields.contains_key(MACHINES_FIELD) {
            continue;
        }
        let Some(required) = slot.required() else {
            continue;
        };
        // R885-T14: the bundle role carries a node capability the mirror's own
        // `required` cannot express. Applied here as well as in the deployer so
        // the two selectors stay set-for-set — a front door aimed at a node the
        // deployer would refuse renders a backend that will never exist.
        let required = required_for_role(role, &required);
        let resolved = resolve_machines_among(machines, &required).with_context(|| {
            format!("resolving placement for [providers.{role}] required = {{ … }}")
        })?;
        placements.insert(
            role.clone(),
            resolved.iter().map(|m| m.name.clone()).collect(),
        );
    }
    Ok(placements)
}

/// The constraint a provider slot is actually placed against — its declared
/// `required = { … }` plus whatever node capability its *role* implies
/// (R885-T14).
///
/// One function so the placement resolver and the candidate widener below
/// cannot drift apart, and so the role→capability mapping lives in exactly one
/// place. Only `providers.bundle` implies one today; every other role passes
/// through byte-identical, which is why this is a clone-on-demand helper rather
/// than a new axis on `RequiredSpec`.
fn required_for_role(role: &str, required: &RequiredSpec) -> RequiredSpec {
    if role == super::mesofact_bundle::SLOT_ROLE {
        super::mesofact_bundle::with_bundle_capability(required)
    } else {
        required.clone()
    }
}

/// Every machine a `required`-constrained slot COULD be placed on, not just
/// where [`resolve_ingress_placements`] resolved it to today (R870-F16).
///
/// A discovery poll list built from the placement set renders exactly as many
/// doors as the workload has replicas — one, for every mirror on disk today —
/// which is a single point of failure baked into the render, not just into the
/// placement: a future `yah cloud migrate` moving the workload to a sibling
/// node leaves every front door polling the node it just vacated until an
/// operator re-applies. Polling the wider candidate set costs nothing extra
/// (discovery.rs's "answered with none retires only its own share" rule) and
/// makes the door follow a move that placement hasn't even made yet.
///
/// Unbounded by [`RequiredSpec::replica_count`] on purpose — that count caps
/// how many machines the workload is placed ON, not how many are eligible TO
/// hold it, and the two must not be conflated here or this collapses back to
/// the placement set it exists to widen.
///
/// A slot with a literal `machine`/`machines` field is absent from the
/// returned map, exactly as in [`resolve_ingress_placements`] — nothing to
/// widen when the operator pinned the node by hand.
pub fn resolve_ingress_candidates(
    machines: &[MachineConfig],
    mirror: &MirrorConfig,
) -> HashMap<String, Vec<String>> {
    let mut candidates = HashMap::new();
    for (role, slot) in &mirror.providers {
        let fields = slot.fields();
        if fields.contains_key(MACHINE_FIELD) || fields.contains_key(MACHINES_FIELD) {
            continue;
        }
        let Some(required) = slot.required() else {
            continue;
        };
        // R885-T14, same reason as in `resolve_ingress_placements`: a node that
        // cannot serve a bundle is not a candidate to hold one, so widening the
        // poll set must not widen past the capability.
        let required = required_for_role(role, &required);
        let matched: Vec<String> = machines
            .iter()
            .filter(|m| required.matches(m))
            .map(|m| m.name.clone())
            .collect();
        candidates.insert(role.clone(), matched);
    }
    candidates
}

/// Every machine's declared mesh address, keyed by machine name (R844-F12).
///
/// The data half of [`IngressPlan::resolve_upstreams_from_config`], split out
/// for the same reason [`resolve_ingress_placements`] is: the planner stays
/// pure and the caller — which has already loaded `.yah/infra/machines/` for
/// placement resolution — does the reading. No new input, just a second lookup
/// over a slice that is already in hand.
///
/// Reads through [`MachineConfig::mesh_ipv4`], so it picks up the same
/// `[registration].mesh_ipv4`-then-legacy-`yubaba_url`-host precedence every
/// other consumer sees; a machine that declares neither is simply absent, and
/// a rule placed only on such machines resolves no address offline. That is
/// the honest answer — silence, reported once by
/// [`IngressRule::upstreams`] — rather than a guess.
pub fn machine_mesh_addrs(machines: &[MachineConfig]) -> HashMap<String, String> {
    machines
        .iter()
        .filter_map(|m| Some((m.name.clone(), m.mesh_ipv4()?.to_string())))
        .collect()
}

/// Derive every declared edge's rules from the mirror's provider slots.
///
/// A slot participates when it declares `fronted = true` **or** a `port`; its
/// `zone` is the public hostname it is fanned in at. Participation without a
/// `zone` is an **error**, not a skip — a mirror that declares a front door and
/// a fronted slot but no hostname is always a typo, and silently dropping it is
/// exactly the failure mode where an operator flips
/// `ingress = "cloudflare-tunnel"` and gets a front door that publishes
/// nothing. A slot with `zone` and neither signal is skipped: that is a
/// CDN-published tier, not a fronted one.
///
/// The two signals are separate as of R844-F5. `port` used to be both the value
/// and the opt-in, so deleting it did not un-pin a port, it removed the slot
/// from the plan — a live hostname silently losing its backend. `port` still
/// implies participation (nothing on disk changes), but a slot may now opt in
/// with `fronted = true` alone and take its port from
/// [`IngressPlan::resolve_ports`].
///
/// `placements` is the pre-resolved output of [`resolve_ingress_placements`] —
/// a fallback for a slot's `machine` field when the slot declares `required`
/// instead of a literal placement. Pass `&HashMap::new()` for a mirror with no
/// constraint-based slots (every slot on disk today, save the one this fallback
/// exists for).
///
/// The derived rules are then **partitioned** across the declared edges by
/// their `slots` / `hostnames` selectors. The partition is required to be total
/// and disjoint (W305 F2): a fronted slot claimed by no edge, or by two, is an
/// error naming both sides. Neither has a safe default — dropping the slot
/// publishes nothing at a hostname the operator declared, and picking one of
/// two edges silently sends a service out through the wrong front door.
///
/// Returns an empty vec when the mirror declares no ingress edge. Plans are in
/// declaration order.
///
/// @yah:ticket(R844-F12, "Derive a rule's upstream host from the placement machine's declared mesh_ipv4 — retire upstream_host without giving up offline planning")
/// @yah:status(review)
/// @yah:assignee(agent:bundle-anthropic-ashguard)
/// @yah:at(2026-09-03T22:18:35Z)
/// @yah:parent(R844)
/// @yah:next("THE SHAPE: when a slot declares no `upstream_host`, fall back to the DECLARED mesh address of each machine in the rule's resolved placement set, instead of leaving upstream_hosts empty for discovery to fill. IngressRule.machines is already the placement set (R844-F3) and `resolve_ingress_placements(machines: &[MachineConfig], mirror)` at ingress.rs:515 already receives every MachineConfig, so the data is in hand at plan time — this is a lookup, not a new input, and plan_ingress keeps taking no network and no CloudConfig. Live discovery via IngressPlan::resolve_upstreams should still WIN when it answers, because it reports what is actually bound; the config fallback is what makes the plan renderable offline rather than what makes it authoritative.")
/// @yah:verify("EQUIVALENCE IS THE TEST, NOT NON-EMPTINESS. With `upstream_host` deleted from .yah/services/yah-marketing/mirrors/cloud.toml, `yah cloud ingress collate` must still render `yah.dev -> 100.64.0.3:8080` on BOTH front doors (us-east-001 and us-south-001), byte-identical to the pinned output, and `cargo test -p xtask --test main mirror_ingress` must be green WITHOUT network. A partial or empty answer that renders a SUBSET of backends looks exactly like success — that is the failure class R844 exists to eliminate and the reason R772 reverted this same deletion once.")
/// @yah:gotcha("WHY THIS IS SAFE AND WHERE ITS LIMIT IS. Safe: .yah/infra/machines/us-east-001.toml:109 declares mesh_ipv4 = \"100.64.0.3\", the apex's live service record reports endpoints [\"100.64.0.3:8080\"], and the two agree — verified against the live fleet 2026-09-03. The existing xtask assertion the_apex_bundle_places_on_the_node_set_its_upstreams_are_pinned_to already performs exactly this offline lookup (its failure message reads \"us-east-001 resolves to mesh address 100.64.0.3\"), so the derivation is proven to work; it is simply not wired into planning. THE LIMIT: R599-F12's doc says native_bind_ip binds the workload's ALLOCATED MeshAssignment, not flatly the node's IP. Those coincide for the apex today, but R844-B11 reports container records advertising a COUNTER-ALLOCATED mesh IP that collides with real node addresses — so this fallback is sound for node-bound NATIVE workloads and its general validity depends on how B11 resolves. Hence depends_on(R844-B11): either land B11 first, or scope the fallback explicitly to the native shape and make it refuse rather than guess for containers.")
/// @yah:depends_on(R844-B11)
/// @yah:handoff("SHIPPED, AND THE PIN IS NOW REDUNDANT RATHER THAN LOAD-BEARING. Two additions to oss/yubaba/crates/cloud/src/reconciler/ingress.rs: `machine_mesh_addrs(&[MachineConfig]) -> HashMap<String,String>` (machine name -> declared `[registration].mesh_ipv4`, read through `MachineConfig::mesh_ipv4()` so it inherits the same registration-then-legacy-url precedence every other consumer sees), and `IngressPlan::resolve_upstreams_from_config(&mesh_addrs)`, which fills each rule's `upstream_hosts` from its placement set in declaration order. Wired into `collate_workspace_ingress` (validate.rs) — the ONE seam, which is why both `yah cloud ingress collate` AND `yah cloud validate` get it, since both call that function (app/yah/cli/src/cloud.rs:3709 and :7521). Exported via reconciler/mod.rs.")
/// @yah:verify("EQUIVALENCE, NOT NON-EMPTINESS, AND AGAINST THE REAL FILE. New `xtask/tests/mirror_ingress.rs::the_apex_renders_the_same_backends_with_upstream_host_deleted` reads .yah/services/yah-marketing/mirrors/cloud.toml OFF DISK, strips the `upstream_host` line from the text, and asserts the pinless render equals the pinned render exactly — `[\"yah.dev=100.64.0.3:8080\"]` both ways. It also asserts the strip actually happened (so a rename cannot make it compare the pinned mirror to itself and pass forever) and that the pinless plan resolves NOTHING before the config pass runs, so the equality provably comes from the derivation and not from some other path supplying the address. cargo test -p xtask --test main mirror_ingress = 11 passed / 0 failed, still with no network, no credentials and no CloudConfig — the purity canary holds.")
/// @yah:verify("Five new unit tests in ingress.rs pin the semantics the xtask test cannot isolate: a pinless slot derives its address; every placement machine contributes a backend IN DECLARATION ORDER (a subset here is the failure that looks like it worked); a pinned `upstream_host` still wins; a machine with no declared mesh address resolves NOTHING rather than falling back to loopback or a neighbour; and a live discovery answer is not overwritten by the declaration. cargo test -p yah-cloud --lib = 997 passed / 0 failed / 4 ignored. cargo test -p yubaba --lib = 632 passed / 0 failed. cargo check -p yah -p xtask --all-targets = exit 0.")
/// @yah:handoff("THE PRECEDENCE IS THE SAFETY PROPERTY, AND IT IS ORDERING, NOT CODE. Config-derived is DECLARED, never authoritative: it runs ONLY where there is no live read to have (collate, validate, xtask). The apply path still resolves through `resolve_upstreams_from` and MUST keep doing so — a service record reports what the supervisor actually bound, this reports what a TOML claims, and when they disagree the TOML is the one that can be stale. Because every resolver here skips a rule that already has an address, calling the config pass BEFORE discovery would silently make the stale value win. That is the confidently-wrong shape R844 exists to remove, so it is asserted as a test (`a_live_answer_is_not_overwritten_by_the_declaration`) rather than left as a convention. The drift is not hypothetical: this mirror's pin was once found still naming 127.0.0.1 after a second front door existed, and every rendered rule looked correct.")
/// @yah:handoff("DEPENDS_ON(R844-B11) IS DISCHARGED, in B11's favour. This ticket's own gotcha said the derivation was \"sound for node-bound NATIVE workloads\" and that its general validity depended on how B11's container mesh-IP bug resolved. B11 (now at review, same session) deleted `alloc_mesh_ip` outright and routed the container tier through `ServerState::workload_bind_ip()` = the node's own mesh address — the same value `admit_bundle` already used. So BOTH tiers now advertise the answering node's own address, which is precisely the fact `.yah/infra/machines/<node>.toml` declares as `[registration].mesh_ipv4`. The two sources agree by construction rather than by coincidence, and this fallback needed no container-specific scoping or refusal.")
pub fn plan_ingress(
    mirror: &MirrorConfig,
    placements: &HashMap<String, Vec<String>>,
) -> Result<Vec<IngressPlan>> {
    let edges = declared(mirror)?;
    if edges.is_empty() {
        return Ok(Vec::new());
    }

    let mut rules = Vec::new();
    for (role, slot) in &mirror.providers {
        let fields = slot.fields();
        let declared_port = fields.get(PORT_FIELD).and_then(|v| v.as_integer());
        let fronted = match fields.get(FRONTED_FIELD) {
            None => false,
            Some(value) => value.as_bool().ok_or_else(|| {
                anyhow::anyhow!(
                    "slot [providers.{role}] {FRONTED_FIELD} = {value} is not a boolean — write \
                     `{FRONTED_FIELD} = true` to put the slot behind the front door. Any other \
                     spelling reads as `not fronted`, which would drop the slot from the plan \
                     silently."
                )
            })?,
        };
        // The opt-in, either spelling. `port` implies it so that every mirror
        // written before `fronted` existed plans identically (R844-F5).
        if declared_port.is_none() && !fronted {
            continue;
        }
        let Some(zone) = fields.get(ZONE_FIELD).and_then(|v| v.as_str()) else {
            let (declared, drop_field) = match declared_port {
                Some(p) => (format!("{PORT_FIELD} = {p}"), PORT_FIELD),
                None => (format!("{FRONTED_FIELD} = true"), FRONTED_FIELD),
            };
            bail!(
                "mirror declares {} ingress edge(s) and slot [providers.{role}] declares \
                 {declared}, but no `zone` — an ingress provider fans a public hostname in to a \
                 node-local port, so it has nothing to publish that slot at. Add \
                 `zone = \"<hostname>\"` to the slot, or drop `{drop_field}` if this slot is \
                 not fronted.",
                edges.len()
            );
        };
        let port = match declared_port {
            Some(p) => Some(u16::try_from(p).with_context(|| {
                format!("slot [providers.{role}] {PORT_FIELD} = {p} is not a valid TCP port")
            })?),
            // Filled by `IngressPlan::resolve_ports` from the node's service
            // records — the port the supervisor actually bound.
            None => None,
        };
        rules.push(IngressRule {
            hostname: zone.to_string(),
            port,
            slot: role.clone(),
            provider_id: slot.provider_id().map(str::to_string),
            machines: declared_machines(&fields)
                .unwrap_or_else(|| placements.get(role).cloned().unwrap_or_default()),
            upstream_hosts: fields
                .get(UPSTREAM_HOST_FIELD)
                .and_then(|v| v.as_str())
                .map(|h| vec![h.to_string()])
                .unwrap_or_default(),
        });
    }

    // Stable order: two applies of an unchanged mirror must produce identical
    // provider config, or every run looks like drift.
    rules.sort_by(|a, b| a.hostname.cmp(&b.hostname));

    if rules.is_empty() {
        bail!(
            "mirror declares {} ingress edge(s) but no provider slot declares `{PORT_FIELD}` or \
             `{FRONTED_FIELD} = true` — there is nothing to publish. Either add `zone` plus one \
             of those to the slot the front door fronts (`{FRONTED_FIELD} = true` takes the port \
             from the node's service records; `{PORT_FIELD}` pins it), or remove the `ingress` \
             declaration.",
            edges.len()
        );
    }

    // A selectorless edge claims everything, which can only be unambiguous when
    // it is the mirror's only one. Two front doors and no way to tell which
    // fronts what is the shape this ticket exists to make expressible — so it
    // has to be *stated*, not resolved by declaration order.
    if edges.len() > 1 {
        if let Some(edge) = edges.iter().find(|e| !e.has_selector()) {
            bail!(
                "{}: a mirror with {} edges needs every edge to name what it fronts. Add \
                 `slots = [...]` or `hostnames = [...]`. Mixing front doors is the whole point \
                 of declaring several, and an implicit catch-all would publish a service \
                 through whichever edge happened to be written first.",
                edge.label(),
                edges.len()
            );
        }
    }

    partition(&edges, rules)
}

/// The placement a slot spells out literally, or `None` when it declares none
/// and a constraint has to answer instead.
///
/// `machine = "<name>"` wins over `machines = [...]` — the pre-existing
/// precedence, kept because the singular form is the narrower statement and an
/// operator who wrote both meant the specific one. The plural form is read
/// **whole**: see [`MACHINES_FIELD`] for why taking only its first entry was a
/// silent subset.
///
/// A declared-but-empty `machines = []` is `None`, not an empty set: it says
/// nothing about placement, so the constraint fallback should still get a turn
/// rather than the slot resolving to "placed nowhere".
fn declared_machines(fields: &std::collections::BTreeMap<String, toml::Value>) -> Option<Vec<String>> {
    if let Some(one) = fields.get(MACHINE_FIELD).and_then(|v| v.as_str()) {
        return Some(vec![one.to_string()]);
    }
    let list: Vec<String> = fields
        .get(MACHINES_FIELD)
        .and_then(|v| v.as_array())?
        .iter()
        .filter_map(|v| v.as_str())
        .map(str::to_string)
        .collect();
    (!list.is_empty()).then_some(list)
}

/// Split derived rules across declared edges, one [`IngressPlan`] each.
///
/// Total and disjoint by construction: every rule lands in exactly one plan or
/// this errors. Preserves declaration order so `yah cloud apply` reports edges
/// in the order the operator wrote them.
fn partition(edges: &[IngressEdge], rules: Vec<IngressRule>) -> Result<Vec<IngressPlan>> {
    let mut buckets: Vec<Vec<IngressRule>> = vec![Vec::new(); edges.len()];

    // R910: (stacked tunnel edge, the door it stacks in front of), by index.
    let mut pairs: std::collections::BTreeSet<(usize, usize)> = std::collections::BTreeSet::new();

    for rule in rules {
        // A `via` edge does not front the rule — it fronts the door that does —
        // so it is set aside rather than counted as a second claimant. Only the
        // terminal claimants have to be exactly one.
        let (stacked, claimants): (Vec<usize>, Vec<usize>) = edges
            .iter()
            .enumerate()
            .filter(|(_, e)| e.claims(&rule.slot, &rule.hostname))
            .map(|(i, _)| i)
            .partition(|i| edges[*i].via.is_some());

        match stacked.as_slice() {
            [] => {}
            [s] => {
                let via = edges[*s].via.expect("partitioned on `via`");
                match claimants.as_slice() {
                    [door] if edges[*door].provider == via.provider() => {
                        pairs.insert((*s, *door));
                        buckets[*s].push(rule.clone());
                    }
                    [door] => bail!(
                        "slot [providers.{}] ({:?}): {} stacks `via = {:?}`, but the edge \
                         fronting that hostname is {} — a tunnel can only stack in front of the \
                         front door it names.",
                        rule.slot,
                        rule.hostname,
                        edges[*s].label(),
                        via.as_str(),
                        edges[*door].label()
                    ),
                    [] => bail!(
                        "slot [providers.{}] ({:?}) is claimed only by {}, which stacks `via = \
                         {:?}` — but no `provider = {:?}` edge claims it, so the tunnel would dial \
                         a demux route nothing serves. Declare that edge for {:?} on the same \
                         machines, or drop `via` so the tunnel dials the workload itself.",
                        rule.slot,
                        rule.hostname,
                        edges[*s].label(),
                        via.as_str(),
                        via.provider().as_str(),
                        rule.hostname
                    ),
                    // Two terminal claimants: the arm below names them.
                    _ => {}
                }
            }
            many => bail!(
                "slot [providers.{}] ({:?}) is claimed by {} stacked edges — {}. One hostname has \
                 one route through a tunnel; narrow the selectors so exactly one claims it.",
                rule.slot,
                rule.hostname,
                many.len(),
                many.iter()
                    .map(|i| edges[*i].label())
                    .collect::<Vec<_>>()
                    .join(" and ")
            ),
        }

        match claimants.as_slice() {
            [i] => buckets[*i].push(rule),
            [] => bail!(
                "slot [providers.{}] is fronted at {:?} but no `[[ingress]]` edge claims it — \
                 the partition has a hole, so that hostname would be published by nothing while \
                 the declaration says otherwise. Add {:?} to an edge's `slots`, or {:?} to its \
                 `hostnames`.",
                rule.slot,
                rule.hostname,
                rule.slot,
                rule.hostname
            ),
            many => bail!(
                "slot [providers.{}] ({:?}) is claimed by {} edges — {}. One hostname cannot be \
                 published through two front doors: DNS points one way, so the second is dead \
                 config that looks live. Narrow the selectors so exactly one claims it.",
                rule.slot,
                rule.hostname,
                many.len(),
                many.iter()
                    .map(|i| edges[*i].label())
                    .collect::<Vec<_>>()
                    .join(" and ")
            ),
        }
    }

    let mut plans = Vec::with_capacity(edges.len());
    for (edge, rules) in edges.iter().zip(buckets) {
        if rules.is_empty() {
            bail!(
                "{}: fronts nothing. Its selector matches no slot that declares `zone` plus \
                 `{PORT_FIELD}` or `{FRONTED_FIELD} = true` — a typo'd slot name is otherwise \
                 invisible, because the front door still deploys and simply publishes an empty \
                 rule set.",
                edge.label()
            );
        }
        // Front-door placement: the edge's own list wins, and falls back to the
        // fronted workload's own nodes — the co-located shape, which stays the
        // default because it is what every mirror written before this field
        // meant.
        //
        // R844-F3: the fallback is the UNION of the fronted slots' placements,
        // not the first one that named a node. Co-location at horizontal scale
        // > 1 means one front door per node the workload runs on; picking the
        // first left the other nodes' copies with no door in front of them, so
        // scaling the workload silently did not scale the front door. This
        // widens the INGRESS tier only — nothing here deploys a workload, and
        // the set it unions over is the placement the mirror already declared.
        let front_doors = if edge.machines.is_empty() {
            let mut out: Vec<String> = Vec::new();
            for machine in rules.iter().flat_map(|r| r.machines.iter()) {
                if !out.contains(machine) {
                    out.push(machine.clone());
                }
            }
            out
        } else {
            edge.machines.clone()
        };
        plans.push(IngressPlan {
            provider: edge.provider,
            rules,
            front_doors,
            tunnel_id: edge.tunnel_id.clone(),
            edge_provider_id: edge.provider_id.clone(),
            image: edge.image.clone(),
            auth: edge.auth.clone(),
            via: edge.via,
            behind_tunnel: false,
            tunnel_door: edge.tunnel_door.clone(),
        });
    }

    // R910: a stacked pair is ONE door seen from two sides, so both sides must
    // describe the same door. Checked on the finished plans because
    // `front_doors` only exists once the fallback above has run.
    for &(s, d) in &pairs {
        let (tunnel, door) = (&plans[s], &plans[d]);
        let same_machines = |a: &[String], b: &[String]| {
            a.iter().all(|m| b.contains(m)) && b.iter().all(|m| a.contains(m))
        };
        // The tunnel dials its OWN node's loopback demux: a tunnel machine with
        // no door routes to nothing, and a door machine with no tunnel is a
        // loopback listener the world cannot reach.
        if !same_machines(&tunnel.front_doors, &door.front_doors) {
            bail!(
                "{} runs on {:?} but the {} it stacks via runs on {:?} — the tunnel dials the \
                 demux on its own node's loopback, so both edges must name the same machines.",
                edges[s].label(),
                tunnel.front_doors,
                edges[d].label(),
                door.front_doors
            );
        }
        // A door behind a tunnel listens on loopback and issues by DNS-01, so
        // it is not also a public door for some other hostname.
        if let Some(h) = door
            .rules
            .iter()
            .map(|r| &r.hostname)
            .find(|h| !tunnel.rules.iter().any(|r| &r.hostname == *h))
        {
            bail!(
                "{} fronts {h:?}, which the tunnel stacked in front of it ({}) does not — a \
                 passway door behind a tunnel listens on loopback, so it cannot also be the \
                 public door for another hostname. Add {h:?} to the tunnel edge, or give it a \
                 passway edge of its own.",
                edges[d].label(),
                edges[s].label()
            );
        }
    }
    for &(_, d) in &pairs {
        plans[d].behind_tunnel = true;
    }
    // R910-F2: the door's `[ingress.tunnel_door]` is required exactly on the
    // side of a pair, and must place every hostname — a hostname with no port
    // is a route the tunnel publishes to a door that is never enrolled.
    for (i, plan) in plans.iter().enumerate() {
        match (&plan.tunnel_door, plan.behind_tunnel) {
            (None, false) => {}
            (Some(_), false) => bail!(
                "{}: declares `[ingress.tunnel_door]`, but no `via = \"passway\"` tunnel edge \
                 stacks in front of it — a public door issues and listens on its own terms. Add \
                 the tunnel edge, or drop the table.",
                edges[i].label()
            ),
            (None, true) => bail!(
                "{}: sits behind a `via = \"passway\"` tunnel, so it listens on loopback and \
                 issues by DNS-01 — declare `[ingress.tunnel_door]` on it with contact_email, \
                 zone_id, token_secret, and a loopback port per hostname in `ports`.",
                edges[i].label()
            ),
            (Some(door), true) => {
                if let Some(h) = plan
                    .rules
                    .iter()
                    .map(|r| &r.hostname)
                    .find(|h| !door.ports.contains_key(*h))
                {
                    bail!(
                        "{}: `[ingress.tunnel_door].ports` names no port for {h:?}, which this \
                         door fronts",
                        edges[i].label()
                    );
                }
                if let Some(h) = door
                    .ports
                    .keys()
                    .find(|h| !plan.rules.iter().any(|r| &r.hostname == *h))
                {
                    bail!(
                        "{}: `[ingress.tunnel_door].ports` names {h:?}, which this door does not \
                         front — a typo here is a door enrolled for a hostname nothing routes",
                        edges[i].label()
                    );
                }
            }
        }
    }
    Ok(plans)
}

// ── collation: what each NODE must run (W305 F2) ─────────────────────────────

/// One service's planned edge, tagged with where it was declared.
///
/// The collator's input unit. Carrying `(service, env)` is not decoration: a
/// collated front door is derived from several services at once, so every
/// conflict has to be able to name which declarations disagree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlannedEdge {
    pub service: String,
    pub env: String,
    pub plan: IngressPlan,
}

impl PlannedEdge {
    /// `service/env`, the label every collation message points at.
    pub fn label(&self) -> String {
        format!("{}/{}", self.service, self.env)
    }
}

/// One front-door appliance a node has to run, derived from every service edge
/// that fronts through it.
///
/// **Nothing declares this.** It is a pure function of the services' `[[ingress]]`
/// edges, which is the direction W305 F2 fixes: the node used to carry its own
/// `cloudflared` cohort declaration (W267 Gap 3) and there was no mechanism
/// making the two agree. A derived view cannot disagree with its inputs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeFrontDoor {
    /// Machine the appliance runs on.
    pub machine: String,
    /// Which appliance — one passway or one cloudflared per (machine, cohort).
    pub provider: IngressProvider,
    /// Tunnel id for the rented arm when an edge named one, else `None` meaning
    /// "the node's own `MachineConfig.cloudflared`". Part of the grouping key:
    /// a node fronting two cohorts runs two connectors, which is exactly the
    /// case Gap 3 could not model.
    pub tunnel_id: Option<String>,
    /// The union of every fronting edge's rules, ordered by hostname.
    pub rules: Vec<IngressRule>,
    /// `service/env` labels that contributed, in sorted order — the provenance
    /// an operator needs to answer "why is this hostname on this box".
    pub sources: Vec<String>,
    /// The bearer auth this appliance runs with (R870-F26), or `None` for an
    /// anonymous door.
    ///
    /// **Not part of the grouping key, and it must not become one.** passway's
    /// auth policy is PROCESS-WIDE — `PASSWAY_AUTH_REQUIRED_PREFIXES` has no
    /// hostname dimension — so one node's passway appliance has exactly one
    /// auth config. Keying on it would model two appliances that cannot both
    /// exist; instead [`collate_front_doors`] rejects contributors that
    /// disagree, the same way it rejects two upstreams for one hostname.
    pub auth: Option<PasswayAuth>,
    /// Hostnames on this door that belong to a **stacked** tunnel→passway pair
    /// on this node (R910), sorted.
    ///
    /// Both sides carry it. On a `cloudflare-tunnel` door it means "this rule
    /// dials the demux, not its upstream"; on a `passway` door it means "this
    /// hostname reaches me through the tunnel" — so it has no apex A record
    /// (`plan_passway_apex` skips it) and its rule's upstream is still the
    /// real backend. One field rather than one per side because it is one
    /// fact, and a door that could say it on one side only would let the two
    /// disagree.
    pub stacked: Vec<String>,
}

impl NodeFrontDoor {
    /// The whole appliance's `PASSWAY_UPSTREAMS` set — every service fronting
    /// through this node, in one env var. This is the fan-in the per-node
    /// process was always doing implicitly; collation is what makes it
    /// computable before the deploy rather than observable after it.
    pub fn passway_upstreams(&self) -> Result<Vec<String>> {
        let mut out = Vec::new();
        for rule in &self.rules {
            out.extend(rule.passway_upstreams()?);
        }
        Ok(out)
    }
}

/// What every node in the camp must run, plus the edges nothing could place.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Collation {
    /// Front doors, sorted by `(machine, provider, tunnel_id)`.
    pub front_doors: Vec<NodeFrontDoor>,
    /// Labels of declared edges with no machine to run on — neither the edge's
    /// own `machines` nor the fronted slot's placement named one. Returned
    /// rather than dropped: an edge that collates onto no node publishes
    /// nothing, and that is invisible from the mirror that declared it.
    pub unplaced: Vec<String>,
}

/// Collate every service's planned edges into the per-node front doors they
/// imply (W305 F2).
///
/// Grouped by `(machine, provider, tunnel_id)` — one appliance per cohort per
/// node, which is the fan-in argument
/// [`MirrorConfig::ingress`](crate::MirrorConfig::ingress) already makes, now
/// applied *across* services instead of within one.
///
/// Three conflicts are rejected, all of which are today invisible because each
/// service's apply only ever sees its own mirror:
///
/// 1. **One hostname, two providers.** DNS points one way, so the second
///    declaration is dead config that reads as live.
/// 2. **One hostname, two upstreams.** Whichever service applied last wins on
///    the box, so the front door's behaviour depends on apply order.
/// 3. **One passway appliance, two auth policies** (R870-F26). Auth is
///    per-process with no hostname dimension, so the same last-apply-wins
///    hazard decides whether every hostname on the node needs a bearer.
///
/// Deterministic: front doors sorted by key, rules by hostname, sources sorted.
pub fn collate_front_doors(planned: &[PlannedEdge]) -> Result<Collation> {
    // Conflict pass first — a conflicting declaration must not produce a
    // half-built collation that a caller might act on.
    let mut owner: std::collections::BTreeMap<&str, (&PlannedEdge, &IngressRule)> =
        std::collections::BTreeMap::new();
    //
    // R910: a stacked tunnel is not a second front door for its hostnames — it
    // is the way in to the passway door that fronts them — so it takes no part
    // in either conflict here, and gets its own check below.
    for edge in planned.iter().filter(|e| e.plan.via.is_none()) {
        for rule in &edge.plan.rules {
            match owner.get(rule.hostname.as_str()) {
                None => {
                    owner.insert(rule.hostname.as_str(), (edge, rule));
                }
                Some((first_edge, first_rule)) => {
                    if first_edge.plan.provider != edge.plan.provider {
                        bail!(
                            "hostname {:?} is fronted by two different providers — {} declares \
                             {:?} and {} declares {:?}. DNS points one way, so one of them is \
                             dead config that still reads as live. Pick one front door for that \
                             hostname.",
                            rule.hostname,
                            first_edge.label(),
                            first_edge.plan.provider.as_str(),
                            edge.label(),
                            edge.plan.provider.as_str()
                        );
                    }
                    // The whole upstream SET is the compared value, not just its
                    // first entry: two services declaring the same hostname over
                    // overlapping-but-unequal backend sets is the same
                    // last-apply-wins hazard as two disjoint ones (R844-F3).
                    if (first_rule.port, &first_rule.upstream_hosts)
                        != (rule.port, &rule.upstream_hosts)
                    {
                        bail!(
                            "hostname {:?} is fronted at two different upstreams — {} \
                             (providers.{}, port {}) and {} (providers.{}, port {}). One front \
                             door publishes one rule per hostname, so whichever service applies \
                             last wins on the box.",
                            rule.hostname,
                            first_edge.label(),
                            first_rule.slot,
                            first_rule.port_label(),
                            edge.label(),
                            rule.slot,
                            rule.port_label()
                        );
                    }
                }
            }
        }
    }

    // R910, the cross-service half of `partition`'s pair rule: every hostname a
    // stacked tunnel routes must be fronted by the door it names ON EACH
    // machine the tunnel runs on. `partition` proves it within one mirror;
    // collation is where another service's declaration could break it.
    for edge in planned.iter().filter(|e| e.plan.via.is_some()) {
        let via = edge.plan.via.expect("filtered on `via`");
        for rule in &edge.plan.rules {
            let doors: std::collections::BTreeSet<&str> = planned
                .iter()
                .filter(|e| e.plan.via.is_none() && e.plan.provider == via.provider())
                .filter(|e| e.plan.rules.iter().any(|r| r.hostname == rule.hostname))
                .flat_map(|e| e.plan.front_doors.iter().map(String::as_str))
                .collect();
            if let Some(machine) = edge
                .plan
                .front_doors
                .iter()
                .find(|m| !doors.contains(m.as_str()))
            {
                let fronted = if doors.is_empty() {
                    String::new()
                } else {
                    format!(
                        " (it is fronted on {})",
                        doors.iter().copied().collect::<Vec<_>>().join(", ")
                    )
                };
                bail!(
                    "hostname {:?}: {} stacks a cloudflare tunnel `via = {:?}` on {machine}, but \
                     no {:?} door fronts that hostname there{fronted}. The tunnel dials its own \
                     node's loopback demux, so the pair has to share a machine.",
                    rule.hostname,
                    edge.label(),
                    via.as_str(),
                    via.provider().as_str(),
                );
            }
        }
    }

    type Key = (String, &'static str, Option<String>);
    let mut grouped: std::collections::BTreeMap<Key, NodeFrontDoor> =
        std::collections::BTreeMap::new();
    let mut unplaced = Vec::new();

    for edge in planned {
        if edge.plan.front_doors.is_empty() {
            unplaced.push(edge.label());
            continue;
        }
        for machine in &edge.plan.front_doors {
            let key: Key = (
                machine.clone(),
                edge.plan.provider.as_str(),
                edge.plan.tunnel_id.clone(),
            );
            let door = grouped.entry(key).or_insert_with(|| NodeFrontDoor {
                machine: machine.clone(),
                provider: edge.plan.provider,
                tunnel_id: edge.plan.tunnel_id.clone(),
                rules: Vec::new(),
                sources: Vec::new(),
                auth: None,
                stacked: Vec::new(),
            });
            // Conflict 3 (R870-F26, reshaped by R556-F6): one passway process
            // holds ONE verifier, but its protected prefixes are host-scoped —
            // `PASSWAY_AUTH_REQUIRED_PREFIXES` takes `<hostname>=<prefix>`. So
            // each authed edge contributes its prefixes scoped to its OWN
            // hostnames, an anonymous edge contributes nothing, and a public
            // site and a confidential tenant share the appliance. What still
            // cannot be merged is two different verifiers (key/kid/iss/aud):
            // whichever applied last would decide which tokens the other
            // service's door accepts.
            if let Some(edge_auth) = &edge.plan.auth {
                let scoped =
                    edge_auth.scoped_to(edge.plan.rules.iter().map(|r| r.hostname.as_str()));
                match &mut door.auth {
                    None => {
                        door.auth = Some(PasswayAuth {
                            require_prefixes: scoped,
                            ..edge_auth.clone()
                        });
                    }
                    Some(existing) if existing.same_verifier(edge_auth) => {
                        existing.require_prefixes.extend(scoped);
                        existing.require_prefixes.sort();
                        existing.require_prefixes.dedup();
                    }
                    Some(existing) => bail!(
                        "front door on {machine} is declared with two different bearer \
                         verifiers — {} declares aud {:?} (kid {:?}, iss {:?}) and {} declares \
                         aud {:?} (kid {:?}, iss {:?}). passway holds ONE verifier per process; \
                         protected prefixes are per-hostname but key/kid/iss/aud are not. Make \
                         the four agree across `[ingress.auth]` tables, or give one service its \
                         own front-door node.",
                        door.sources.join(", "),
                        existing.aud,
                        existing.kid,
                        existing.iss,
                        edge.label(),
                        edge_auth.aud,
                        edge_auth.kid,
                        edge_auth.iss,
                    ),
                }
            }
            for rule in &edge.plan.rules {
                // The same (service, env) can reach one node through several
                // edges; the conflict pass has already proven identical
                // hostnames carry identical rules, so dedup is safe here.
                if !door.rules.iter().any(|r| r.hostname == rule.hostname) {
                    door.rules.push(rule.clone());
                }
            }
            let label = edge.label();
            if !door.sources.contains(&label) {
                door.sources.push(label);
            }
        }
    }

    let mut front_doors: Vec<NodeFrontDoor> = grouped.into_values().collect();

    // R910: mark both sides of every stacked pair. The check above has proven
    // a passway door carries each hostname on each tunnel machine, so this
    // only records what that check found.
    for edge in planned.iter().filter(|e| e.plan.via.is_some()) {
        let via = edge.plan.via.expect("filtered on `via`");
        for door in front_doors
            .iter_mut()
            .filter(|d| edge.plan.front_doors.contains(&d.machine))
        {
            let this_tunnel =
                door.provider == edge.plan.provider && door.tunnel_id == edge.plan.tunnel_id;
            if !this_tunnel && door.provider != via.provider() {
                continue;
            }
            for rule in &edge.plan.rules {
                if door.rules.iter().any(|r| r.hostname == rule.hostname)
                    && !door.stacked.contains(&rule.hostname)
                {
                    door.stacked.push(rule.hostname.clone());
                }
            }
        }
    }

    for door in &mut front_doors {
        door.rules.sort_by(|a, b| a.hostname.cmp(&b.hostname));
        door.sources.sort();
        door.stacked.sort();
    }
    unplaced.sort();
    unplaced.dedup();

    Ok(Collation {
        front_doors,
        unplaced,
    })
}

// ── cloudflare-tunnel arm ────────────────────────────────────────────────────

/// Ensure the tunnel's remotely-managed ingress config publishes `plan`'s
/// rules.
///
/// Token-form tunnels keep their ingress rules in Cloudflare's API rather than
/// in a file on the box (W267 §Granularity), so this is an API-call job, not a
/// config render.
///
/// **A failed API call is never read as "delete every hostname rule."** The
/// GET's error propagates and no PUT is attempted — the same rule the
/// sovereign arm follows for a failed `GET /service-records` (W267 §"The seam,
/// settled", constraint 2). Rules for hostnames this mirror does not own are
/// preserved verbatim, because one tunnel multiplexes every service on the
/// node.
///
/// Idempotent: when the merged config equals the live one, no PUT is made.
///
/// Required token scope: `Cloudflare Tunnel: Edit`.
pub async fn ensure_tunnel_ingress(
    cf: &CloudflareClient,
    account_id: &str,
    tunnel_id: &str,
    plan: &IngressPlan,
) -> Result<TunnelIngressOutcome> {
    let live = cf
        .tunnel_configuration(account_id, tunnel_id)
        .await
        .with_context(|| format!("reading ingress configuration of tunnel {tunnel_id}"))?;

    let live_ingress = live
        .get("ingress")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();

    let merged = merge_tunnel_ingress(&live_ingress, plan)?;
    if merged == live_ingress {
        debug!(tunnel_id, "tunnel ingress already current — skipping PUT");
        return Ok(TunnelIngressOutcome::AlreadyCurrent);
    }

    // Preserve every sibling key of the config object (warp-routing,
    // originRequest defaults, …) — we own `ingress` and nothing else.
    let mut config = live;
    config
        .as_object_mut()
        .expect("tunnel_configuration always yields a JSON object")
        .insert("ingress".into(), Value::Array(merged));

    cf.put_tunnel_configuration(account_id, tunnel_id, &config)
        .await
        .with_context(|| format!("writing ingress configuration of tunnel {tunnel_id}"))?;
    info!(
        tunnel_id,
        rules = plan.rules.len(),
        "tunnel ingress configuration updated"
    );
    Ok(TunnelIngressOutcome::Updated)
}

/// Resolve Cloudflare credentials from the mirror's own provider slot and
/// publish `plan`'s rules to `tunnel_id`.
///
/// The apply-layer entry point: credentials come from
/// `.yah/infra/providers/<provider_id>.toml` (the slot's `use = "…"`), the same
/// route [`ensure_r2_custom_domain`](super::domain::ensure_r2_custom_domain)
/// takes, so a mirror never has to name its account twice.
pub async fn publish_tunnel_ingress(
    workspace_root: &std::path::Path,
    provider_id: &str,
    tunnel_id: &str,
    plan: &IngressPlan,
) -> Result<TunnelIngressOutcome> {
    let cf_provider = super::cf_creds::CfProvider::resolve(workspace_root, provider_id)?;
    let account_id = cf_provider.account_id.clone();
    let cf = CloudflareClient::new(cf_provider.api_token()?);
    ensure_tunnel_ingress(&cf, &account_id, tunnel_id, plan).await
}

/// Result of an [`ensure_tunnel_ingress`] pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TunnelIngressOutcome {
    /// Live config already published every planned rule — no write made.
    AlreadyCurrent,
    /// The tunnel's ingress config was rewritten.
    Updated,
}

/// Merge planned rules into a tunnel's live ingress list.
///
/// cloudflared requires the list to end with a catch-all rule (no `hostname`);
/// everything before it is matched top-down. So:
///
/// - a live rule whose hostname this plan owns is **replaced** (the plan is
///   authoritative for its own hostnames);
/// - a live rule for any other hostname is **kept verbatim**, including fields
///   this crate does not model (`path`, `originRequest`, …) — one tunnel fans
///   in every service on the node, and stomping a neighbour's rule because we
///   don't parse its options would take that service down;
/// - the live catch-all is preserved if present, else `http_status:404` is
///   appended.
///
/// Each planned rule renders through [`IngressPlan::tunnel_rule`], so a
/// `via = "passway"` plan replaces an owned hostname's live rule with the
/// demux service plus `originRequest.matchSNItoHost` (R910) — and, just as
/// importantly, a plain plan still replaces one that carried them.
fn merge_tunnel_ingress(live: &[Value], plan: &IngressPlan) -> Result<Vec<Value>> {
    let rules = &plan.rules;
    let owned: std::collections::BTreeSet<&str> =
        rules.iter().map(|r| r.hostname.as_str()).collect();

    let mut out: Vec<Value> = Vec::with_capacity(live.len() + rules.len());
    let mut catch_all: Option<Value> = None;

    for rule in live {
        match rule.get("hostname").and_then(Value::as_str) {
            // The trailing catch-all — hold it back so it stays last.
            None | Some("") => catch_all = Some(rule.clone()),
            Some(host) if owned.contains(host) => {} // replaced below
            Some(_) => out.push(rule.clone()),
        }
    }

    for rule in rules {
        out.push(plan.tunnel_rule(rule)?);
    }

    out.push(catch_all.unwrap_or_else(|| json!({ "service": "http_status:404" })));
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MirrorShape;
    use std::collections::BTreeMap;

    fn mirror(ingress: IngressProvider, slots: &str) -> MirrorConfig {
        mirror_placed(ingress, &[], slots)
    }

    /// [`mirror`] with an explicit front-door placement list (R330-F37) — the
    /// legacy single-edge spelling, `ingress` + `ingress_machines`.
    fn mirror_placed(
        ingress: IngressProvider,
        ingress_machines: &[&str],
        slots: &str,
    ) -> MirrorConfig {
        let mut m = mirror_edges(vec![], slots);
        m.ingress = ingress.into();
        m.ingress_machines = ingress_machines.iter().map(|s| s.to_string()).collect();
        m
    }

    /// A mirror declaring `[[ingress]]` edges (W305 F2).
    fn mirror_edges(edges: Vec<IngressEdge>, slots: &str) -> MirrorConfig {
        let providers: BTreeMap<String, crate::MirrorProviderSlot> =
            toml::from_str(slots).expect("slot fixture parses");
        MirrorConfig {
            schema_version: 1,
            shape: MirrorShape::SingleMachine,
            ingress: crate::config::IngressDecl::Edges(edges),
            ingress_machines: Vec::new(),
            providers,
            drivers: Default::default(),
            asset_aliases: Default::default(),
            build: Default::default(),
        }
    }

    /// One edge, spelled the way an operator writes it in TOML.
    fn edge(provider: IngressProvider, machines: &[&str], slots: &[&str]) -> IngressEdge {
        IngressEdge {
            provider,
            machines: machines.iter().map(|s| s.to_string()).collect(),
            slots: slots.iter().map(|s| s.to_string()).collect(),
            hostnames: Vec::new(),
            tunnel_id: None,
            provider_id: None,
            image: None,
            auth: None,
            via: None,
            tunnel_door: None,
        }
    }

    /// The single plan a one-edge mirror yields.
    fn only_plan(m: &MirrorConfig) -> IngressPlan {
        let mut plans = plan_ingress(m, &HashMap::new()).expect("mirror plans");
        assert_eq!(plans.len(), 1, "fixture declares exactly one edge");
        plans.remove(0)
    }

    // ── plan_ingress ──

    #[test]
    fn no_ingress_field_plans_nothing() {
        let m = mirror(
            IngressProvider::None,
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        assert!(declared(&m).unwrap().is_empty());
        assert_eq!(plan_ingress(&m, &HashMap::new()).unwrap(), vec![]);
    }

    #[test]
    fn derives_a_rule_per_fronted_slot_sorted_by_hostname() {
        let m = mirror(
            IngressProvider::CloudflareTunnel,
            "[compute]\nuse = \"hetzner\"\nmachine = \"us-east-001\"\nzone = \"z.yah.dev\"\nport = 8080\n\
             [receiver]\nuse = \"cloudflare\"\nzone = \"a.yah.dev\"\nport = 9090\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.provider, IngressProvider::CloudflareTunnel);
        assert_eq!(
            plan.rules,
            vec![
                IngressRule {
                    hostname: "a.yah.dev".into(),
                    port: Some(9090),
                    slot: "receiver".into(),
                    provider_id: Some("cloudflare".into()),
                    machines: Vec::new(),
                    upstream_hosts: Vec::new(),
                },
                IngressRule {
                    hostname: "z.yah.dev".into(),
                    port: Some(8080),
                    slot: "compute".into(),
                    provider_id: Some("hetzner".into()),
                    machines: vec!["us-east-001".into()],
                    upstream_hosts: Vec::new(),
                },
            ]
        );
        // Credentials + placement are read off the slots, not asked for twice.
        assert_eq!(plan.provider_id(), Some("cloudflare"));
        assert_eq!(plan.workload_machines(), vec!["us-east-001"]);
        // With no `ingress_machines`, the front door falls back to the fronted
        // workload's node — the co-located shape every mirror had before.
        assert_eq!(plan.front_doors, vec!["us-east-001".to_string()]);
    }

    #[test]
    fn slot_without_the_opt_in_marker_is_skipped() {
        let m = mirror(
            IngressProvider::Passway,
            "[static]\nuse = \"cloudflare\"\nbucket = \"b\"\n\
             [compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules.len(), 1);
        assert_eq!(plan.rules[0].slot, "compute");
    }

    #[test]
    fn a_cdn_slots_zone_does_not_drag_it_into_the_plan() {
        // The real shape of .yah/services/yah-analytics/mirrors/cloud.toml: a
        // CDN-published static tier carries `zone` meaning the *Cloudflare
        // zone*, not a front door. Keying participation off `zone` would fail
        // this mirror's apply the moment `ingress` was declared.
        let m = mirror(
            IngressProvider::CloudflareTunnel,
            "[static]\nuse = \"cloudflare\"\nbucket = \"yah-app-dev\"\n\
             zone = \"analytics.yah.dev\"\n\
             [compute]\nuse = \"hetzner\"\nmachine = \"yah-cloud-1\"\n\
             zone = \"analytics.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules.len(), 1, "only the opted-in slot is fronted");
        assert_eq!(plan.rules[0].slot, "compute");
    }

    #[test]
    fn opt_in_without_zone_is_an_error_naming_the_slot() {
        let m = mirror(
            IngressProvider::CloudflareTunnel,
            "[compute]\nuse = \"hetzner\"\nport = 8080\n",
        );
        let err = plan_ingress(&m, &HashMap::new()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("providers.compute"), "got: {msg}");
        assert!(msg.contains("zone"), "got: {msg}");
    }

    // ── front-door placement (R330-F37) ──

    #[test]
    fn front_doors_are_independent_of_where_the_fronted_workload_runs() {
        // The whole point of the field: N front doors over ONE deployment. The
        // workload stays pinned to east; the ingress tier spans east + west.
        let m = mirror_placed(
            IngressProvider::Passway,
            &["us-east-001", "us-west-001"],
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\nupstream_host = \"100.64.0.3\"\n",
        );
        let plan = only_plan(&m);
        assert_eq!(
            plan.front_doors,
            vec!["us-east-001".to_string(), "us-west-001".to_string()]
        );
        // …and the workload placement is untouched, so discovery still asks the
        // node that actually holds the deployment — one node, not two, even
        // though the front door now spans two.
        assert_eq!(plan.workload_machines(), vec!["us-east-001"]);
    }

    #[test]
    fn a_bundle_slots_machines_list_is_read_whole_as_placement() {
        // `[providers.bundle]` spells placement `machines`, not `machine`.
        // Before R330-F37 the planner only read the singular, so every rule
        // derived from a bundle slot had no placement and discovery had no node
        // to ask. R844-F3: it then read only the FIRST entry, which is the same
        // bug one node further along — a workload declared at horizontal scale
        // 2 had its second node dropped from discovery and from the co-located
        // front-door fallback, and the apply still looked clean.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\", \"us-west-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules[0].machines, vec!["us-east-001", "us-west-001"]);
        assert_eq!(plan.workload_machines(), vec!["us-east-001", "us-west-001"]);
        // Co-located fallback: one front door per node the workload runs on.
        assert_eq!(
            plan.front_doors,
            vec!["us-east-001".to_string(), "us-west-001".to_string()]
        );
    }

    #[test]
    fn an_empty_machines_list_leaves_the_constraint_fallback_its_turn() {
        // `machines = []` states nothing about placement. Reading it as "placed
        // on the empty set" would shadow the `required` fallback and un-aim
        // discovery, which is the R772 failure with a different spelling.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = []\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let placements = HashMap::from([("bundle".to_string(), vec!["us-east-001".to_string()])]);
        let mut plans = plan_ingress(&m, &placements).expect("mirror plans");
        assert_eq!(plans.remove(0).rules[0].machines, vec!["us-east-001"]);
    }

    #[test]
    fn a_constraint_resolved_placement_set_reaches_every_rule() {
        // The third instance of "caller resolves, planner receives data": the
        // planner never sees `.yah/infra/machines/`, so a set-valued placement
        // arrives as data exactly like a literal list would.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nrequired = { regions = [\"us-east\"] }\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let placements = HashMap::from([(
            "bundle".to_string(),
            vec!["us-east-001".to_string(), "us-south-001".to_string()],
        )]);
        let plan = plan_ingress(&m, &placements)
            .expect("mirror plans")
            .remove(0);
        assert_eq!(plan.rules[0].machines, vec!["us-east-001", "us-south-001"]);
        assert_eq!(
            plan.front_doors,
            vec!["us-east-001".to_string(), "us-south-001".to_string()]
        );
    }

    /// R870-F16 — the whole defect half (a) exists to fix: a `required` that
    /// MATCHES several machines still PLACES on however many `replicas` asked
    /// for (one, by default), and the candidate set must not collapse to that
    /// narrower number. A test that only exercised the multi-placement case
    /// (like the one above, which pre-resolves a 2-machine `placements` map by
    /// hand) would pass today without this ticket's fix.
    #[test]
    fn the_candidate_set_is_wider_than_the_placement_set() {
        // R885-T14: the slot under test is `bundle`, so every node here has to
        // declare `cap:bundle-serving` or neither the placement nor the
        // candidate set has anything to pick from — the widening this test is
        // about happens strictly *within* the capable pool.
        fn machine(name: &str, region: &str) -> MachineConfig {
            toml::from_str(&format!(
                "name = \"{name}\"\nprovider = \"static\"\n\
                 mesh_tags = [\"cap:bundle-serving\"]\n\
                 hosts_mirrors = []\nssh_keys = []\nregion = \"{region}\"\n"
            ))
            .expect("machine config parses")
        }
        let machines = vec![
            machine("us-east-001", "us-east"),
            machine("us-south-001", "us-east"),
            machine("us-west-001", "us-west"),
        ];
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nrequired = { regions = [\"us-east\"] }\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );

        let placements = resolve_ingress_placements(&machines, &m).expect("placements resolve");
        assert_eq!(
            placements.get("bundle"),
            Some(&vec!["us-east-001".to_string()]),
            "no `replicas` declared means exactly one placement (R844-F8's default)"
        );

        let candidates = resolve_ingress_candidates(&machines, &m);
        assert_eq!(
            candidates.get("bundle"),
            Some(&vec!["us-east-001".to_string(), "us-south-001".to_string()]),
            "both us-east machines are ELIGIBLE even though only one is PLACED — the door \
             should still be able to poll the one placement didn't pick"
        );
    }

    #[test]
    fn the_co_located_fallback_unions_two_slots_placements() {
        // Two fronted slots on two nodes, no `ingress_machines`. Taking the
        // first rule's node left the second slot's copy with no door in front of
        // it — and the mirror still read as if both were fronted.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachine = \"us-east-001\"\n\
             zone = \"a.yah.dev\"\nport = 8080\n\
             [compute]\nuse = \"hetzner\"\nmachine = \"us-west-001\"\n\
             zone = \"b.yah.dev\"\nport = 9090\n",
        );
        let plan = only_plan(&m);
        assert_eq!(
            plan.front_doors,
            vec!["us-east-001".to_string(), "us-west-001".to_string()]
        );
    }

    #[test]
    fn a_singular_machine_field_still_wins_over_the_plural_one() {
        let m = mirror(
            IngressProvider::Passway,
            "[compute]\nuse = \"hetzner\"\nmachine = \"pinned\"\n\
             machines = [\"ignored\"]\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules[0].machines, vec!["pinned"]);
    }

    #[test]
    fn front_door_placement_without_a_front_door_is_an_error() {
        // A silent skip here is the same failure as `port` with no `zone`: the
        // operator names placement, gets nothing, and nothing says why.
        let m = mirror_placed(
            IngressProvider::None,
            &["us-west-001"],
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let err = plan_ingress(&m, &HashMap::new()).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("ingress_machines"), "got: {msg}");
        assert!(msg.contains("us-west-001"), "got: {msg}");
    }

    #[test]
    fn every_front_door_gets_the_same_upstream_set() {
        // Fanning the front door out must not fan the *rules* out — one
        // rendered copy of the site, so no cache coherence to settle. The plan
        // is shared across placements by construction; this pins that the
        // upstream set is a property of the plan, not of a placement.
        let m = mirror_placed(
            IngressProvider::Passway,
            &["us-east-001", "us-west-001", "us-south-001"],
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\nupstream_host = \"100.64.0.3\"\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.front_doors.len(), 3);
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:8080".to_string()]
        );
    }

    #[test]
    fn ingress_with_no_fronted_slot_is_an_error() {
        let m = mirror(
            IngressProvider::Passway,
            "[static]\nuse = \"cloudflare\"\nbucket = \"b\"\n",
        );
        let err = plan_ingress(&m, &HashMap::new()).unwrap_err();
        assert!(format!("{err:#}").contains("no provider slot declares `port`"));
    }

    // ── `fronted`: participation split from the port value (R844-F5) ──

    #[test]
    fn a_fronted_slot_with_no_port_is_planned_rather_than_skipped() {
        // The finding this ticket exists for: before the split, deleting `port`
        // did not un-pin a port — it removed the slot from the plan entirely,
        // so a live hostname silently lost its backend while the mirror still
        // read as if it were fronted.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nfronted = true\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules.len(), 1);
        assert_eq!(plan.rules[0].hostname, "yah.dev");
        assert_eq!(plan.rules[0].port, None, "the port is discovery's to answer");
        assert_eq!(plan.rules[0].machines, vec!["us-east-001"]);
        assert_eq!(plan.front_doors, vec!["us-east-001".to_string()]);
    }

    #[test]
    fn a_declared_port_still_fronts_without_the_new_field() {
        // The migration is additive: every mirror on disk predates `fronted`
        // and must plan byte-identically.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachine = \"us-east-001\"\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules.len(), 1);
        assert_eq!(plan.rules[0].port, Some(8080));
    }

    #[test]
    fn a_slot_with_neither_signal_is_still_skipped() {
        // A CDN-published static tier carries `zone` meaning the CLOUDFLARE
        // zone. Keying participation off it would drag every such slot into the
        // plan, which is why `fronted` exists at all.
        let m = mirror(
            IngressProvider::Passway,
            "[static]\nuse = \"cloudflare\"\nbucket = \"b\"\nzone = \"cdn.yah.dev\"\n\
             [bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nfronted = true\n",
        );
        let plan = only_plan(&m);
        assert_eq!(
            plan.rules.iter().map(|r| r.slot.as_str()).collect::<Vec<_>>(),
            vec!["bundle"]
        );
    }

    #[test]
    fn fronted_without_a_zone_is_the_same_error_as_port_without_one() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nfronted = true\n",
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("providers.bundle"), "got: {msg}");
        assert!(msg.contains("fronted = true"), "names the signal: {msg}");
        assert!(msg.contains("zone"), "got: {msg}");
    }

    #[test]
    fn a_non_boolean_fronted_is_an_error_rather_than_a_silent_skip() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nfronted = \"yes\"\n",
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("is not a boolean"), "got: {msg}");
        assert!(msg.contains("providers.bundle"), "got: {msg}");
    }

    #[test]
    fn the_empty_plan_error_names_both_participation_spellings() {
        let m = mirror(
            IngressProvider::Passway,
            "[static]\nuse = \"cloudflare\"\nbucket = \"b\"\n",
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("fronted = true"), "got: {msg}");
        assert!(msg.contains("`port`"), "got: {msg}");
    }

    // ── resolve_ports (R844-F5) ──

    #[test]
    fn resolve_ports_fills_a_portless_rule_from_discovery() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nfronted = true\nupstream_host = \"100.64.0.3\"\n",
        );
        let mut plan = only_plan(&m);
        // What kamaji allocated and the supervisor reported as `resolved_ports`
        // — a number no mirror could have known.
        plan.resolve_ports(|rule| {
            assert_eq!(rule.slot, "bundle");
            Ok(Some(43117))
        })
        .unwrap();
        assert_eq!(plan.rules[0].port, Some(43117));
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:43117"]
        );
    }

    #[test]
    fn a_declared_port_wins_over_discovery() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nport = 8080\n\
             fronted = true\nupstream_host = \"100.64.0.3\"\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_ports(|_| panic!("discovery must not run for a pinned port"))
            .unwrap();
        assert_eq!(plan.rules[0].port, Some(8080));
    }

    #[test]
    fn an_unresolved_port_is_one_combined_error_not_a_panic() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nfronted = true\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_ports(|_| Ok(None)).unwrap();
        // Neither half resolved: one message naming both, from the single place
        // an undialable rule is reported.
        let msg = format!("{:#}", plan.rules[0].service_url().unwrap_err());
        assert!(msg.contains("no resolved port"), "got: {msg}");
        assert!(msg.contains("no resolved upstream address"), "got: {msg}");
        assert!(msg.contains("providers.bundle"), "got: {msg}");
        assert_eq!(plan.rules[0].port_label(), "<unresolved>");
    }

    #[test]
    fn a_resolved_port_with_no_backend_still_says_so() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nfronted = true\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_ports(|_| Ok(Some(43117))).unwrap();
        let err = plan.resolve_upstreams(|_| Ok(Vec::new())).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no resolved upstream address"), "got: {msg}");
        assert!(!msg.contains("no resolved port"), "port resolved: {msg}");
    }

    // ── resolve_upstreams_from_config (R844-F12) ──

    fn addrs(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(n, a)| (n.to_string(), a.to_string()))
            .collect()
    }

    #[test]
    fn a_pinless_slot_takes_its_address_from_the_placement_machines_declaration() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        assert!(
            plan.rules[0].upstream_hosts.is_empty(),
            "nothing pins it, so the planner leaves it for a resolver"
        );
        plan.resolve_upstreams_from_config(&addrs(&[("us-east-001", "100.64.0.3")]));
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:8080"],
            "the exact string the pinned mirror renders — equivalence is the claim"
        );
    }

    #[test]
    fn every_placement_machine_contributes_a_backend_in_declaration_order() {
        // Horizontal scale > 1: taking the first entry would render a subset,
        // which is the failure that looks like it worked (R844-F3/F4).
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\n\
             machines = [\"us-east-001\", \"us-west-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams_from_config(&addrs(&[
            ("us-west-001", "100.64.0.1"),
            ("us-east-001", "100.64.0.3"),
        ]));
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:8080", "yah.dev=100.64.0.1:8080"],
            "declaration order, not map order — a reordered set reads as drift \
             on every apply"
        );
    }

    #[test]
    fn a_pinned_upstream_host_still_wins_over_the_declaration() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\nupstream_host = \"10.0.0.9\"\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams_from_config(&addrs(&[("us-east-001", "100.64.0.3")]));
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=10.0.0.9:8080"],
            "an explicit operator override is the escape hatch for a node whose \
             declared address is wrong — the derivation must not overwrite it"
        );
    }

    #[test]
    fn a_machine_with_no_declared_address_resolves_nothing_rather_than_guessing() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"dev-box\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams_from_config(&addrs(&[("us-east-001", "100.64.0.3")]));
        // Silence, reported once by the single undialable-rule error site —
        // never a fallback to loopback or to some other node's address.
        let msg = format!("{:#}", plan.passway_upstreams().unwrap_err());
        assert!(msg.contains("no resolved upstream address"), "got: {msg}");
        assert!(!msg.contains("no resolved port"), "port is pinned: {msg}");
    }

    #[test]
    fn a_live_answer_is_not_overwritten_by_the_declaration() {
        // Precedence, stated as a test because the ordering is the whole
        // safety property: discovery reports what the supervisor bound, the
        // declaration reports what a TOML claims, and running this pass after
        // discovery must leave the measured answer alone.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams(|_| Ok(vec!["100.64.0.42".to_string()]))
            .unwrap();
        plan.resolve_upstreams_from_config(&addrs(&[("us-east-001", "100.64.0.3")]));
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.42:8080"],
            "a stale machine toml must not win over a live read"
        );
    }

    // ── upstream_labels (R844-T10) ──

    #[test]
    fn a_half_resolved_rule_labels_the_half_it_knows() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
             zone = \"yah.dev\"\nfronted = true\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams_from_config(&addrs(&[("us-east-001", "100.64.0.3")]));
        // The address is a config fact and resolves offline; the port is a
        // runtime fact and cannot. Reporting the first as unknown too — which
        // the old `<unresolved>:<port>` fallback did — discards a fact the tool
        // is holding.
        assert_eq!(
            plan.rules[0].upstream_labels(),
            vec!["100.64.0.3:<unresolved>"]
        );
        assert!(
            plan.rules[0].upstreams().is_err(),
            "and it is still undialable — a label is not a resolution"
        );
    }

    #[test]
    fn a_rule_with_neither_half_says_so_once_per_line() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nzone = \"yah.dev\"\nfronted = true\n",
        );
        let plan = only_plan(&m);
        assert_eq!(
            plan.rules[0].upstream_labels(),
            vec!["<unresolved>:<unresolved>"]
        );
    }

    #[test]
    fn every_backend_gets_its_own_label() {
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\n\
             machines = [\"us-east-001\", \"us-west-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams_from_config(&addrs(&[
            ("us-east-001", "100.64.0.3"),
            ("us-west-001", "100.64.0.1"),
        ]));
        assert_eq!(
            plan.rules[0].upstream_labels(),
            vec!["100.64.0.3:8080", "100.64.0.1:8080"],
            "collating one backend out of N is the subset failure this view exists \
             to catch, so the view must not collapse the set either"
        );
    }

    // ── declared edges (W305 F2) ──

    /// The whole reason the field became a list: one mirror, two front doors.
    const MIXED_SLOTS: &str = "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\"]\n\
         zone = \"yah.dev\"\nport = 8080\nupstream_host = \"100.64.0.3\"\n\
         [internal]\nuse = \"hetzner\"\nmachine = \"us-west-001\"\n\
         zone = \"admin.yah.dev\"\nport = 9443\nupstream_host = \"100.64.0.4\"\n";

    #[test]
    fn two_edges_split_the_rules_and_keep_their_own_placement() {
        let m = mirror_edges(
            vec![
                edge(IngressProvider::Passway, &["us-east-001"], &["bundle"]),
                edge(
                    IngressProvider::CloudflareTunnel,
                    &["us-west-001"],
                    &["internal"],
                ),
            ],
            MIXED_SLOTS,
        );
        let plans = plan_ingress(&m, &HashMap::new()).unwrap();
        assert_eq!(plans.len(), 2, "one plan per declared edge");

        // Declaration order, and each edge publishes only what it claims.
        assert_eq!(plans[0].provider, IngressProvider::Passway);
        assert_eq!(
            plans[0].passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:8080"]
        );
        assert_eq!(plans[0].front_doors, vec!["us-east-001".to_string()]);

        assert_eq!(plans[1].provider, IngressProvider::CloudflareTunnel);
        assert_eq!(plans[1].rules.len(), 1);
        assert_eq!(plans[1].rules[0].hostname, "admin.yah.dev");
        assert_eq!(plans[1].front_doors, vec!["us-west-001".to_string()]);
    }

    #[test]
    fn an_edge_may_select_by_hostname_instead_of_by_slot() {
        let m = mirror_edges(
            vec![
                IngressEdge {
                    hostnames: vec!["yah.dev".into()],
                    ..edge(IngressProvider::Passway, &["us-east-001"], &[])
                },
                IngressEdge {
                    hostnames: vec!["admin.yah.dev".into()],
                    ..edge(IngressProvider::CloudflareTunnel, &["us-west-001"], &[])
                },
            ],
            MIXED_SLOTS,
        );
        let plans = plan_ingress(&m, &HashMap::new()).unwrap();
        assert_eq!(plans[0].rules[0].hostname, "yah.dev");
        assert_eq!(plans[1].rules[0].hostname, "admin.yah.dev");
    }

    #[test]
    fn a_slot_no_edge_claims_is_an_error_naming_it() {
        // The hole this catches is invisible from the mirror: the front door
        // deploys, the site serves, and `admin.yah.dev` resolves to nothing.
        let m = mirror_edges(
            vec![
                edge(IngressProvider::Passway, &["us-east-001"], &["bundle"]),
                edge(IngressProvider::Passway, &["us-west-001"], &["nonexistent"]),
            ],
            MIXED_SLOTS,
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("internal"), "names the unclaimed slot: {msg}");
        assert!(msg.contains("admin.yah.dev"), "got: {msg}");
    }

    #[test]
    fn a_slot_two_edges_claim_is_an_error_naming_both() {
        let m = mirror_edges(
            vec![
                edge(IngressProvider::Passway, &["us-east-001"], &["bundle"]),
                IngressEdge {
                    hostnames: vec!["yah.dev".into()],
                    ..edge(IngressProvider::Passway, &["us-west-001"], &["internal"])
                },
            ],
            MIXED_SLOTS,
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("claimed by 2 edges"), "got: {msg}");
        assert!(msg.contains("slots = [\"bundle\"]"), "got: {msg}");
    }

    // ── R910: a tunnel stacked `via` the node's passway ──

    /// The compute slot of noisetable-api's staging mirror.
    const STACKED_SLOTS: &str = "[compute]\nkind = \"static\"\nmachine = \"us-west-011\"\n\
         zone = \"api-staging.noisetable.com\"\nport = 4332\n";

    /// The door noisetable R704-T4 hand-enrolled, as a mirror declares it: a
    /// passway edge and a tunnel edge stacked via it, same hostname.
    fn stacked_pair(door_machines: &[&str], tunnel_machines: &[&str]) -> Vec<IngressEdge> {
        vec![
            IngressEdge {
                hostnames: vec!["api-staging.noisetable.com".into()],
                tunnel_door: Some(staging_door(&[("api-staging.noisetable.com", 8445)])),
                ..edge(IngressProvider::Passway, door_machines, &[])
            },
            IngressEdge {
                hostnames: vec!["api-staging.noisetable.com".into()],
                via: Some(IngressVia::Passway),
                provider_id: Some("cloudflare-tunnel-staging".into()),
                ..edge(IngressProvider::CloudflareTunnel, tunnel_machines, &[])
            },
        ]
    }

    /// The `[ingress.tunnel_door]` a stacked door declares (R910-F2).
    fn staging_door(ports: &[(&str, u16)]) -> TunnelDoor {
        TunnelDoor {
            contact_email: "ops@noisetable.com".into(),
            zone_id: "zone-1".into(),
            token_secret: "noisetable/staging/cf-dns".into(),
            ports: ports.iter().map(|(h, p)| (h.to_string(), *p)).collect(),
        }
    }

    fn stacked_err(edges: Vec<IngressEdge>, slots: &str) -> String {
        format!(
            "{:#}",
            plan_ingress(&mirror_edges(edges, slots), &HashMap::new()).unwrap_err()
        )
    }

    #[test]
    fn a_tunnel_via_passway_and_its_door_plan_as_one_stacked_pair() {
        let plans = plan_ingress(
            &mirror_edges(stacked_pair(&["us-west-011"], &["us-west-011"]), STACKED_SLOTS),
            &HashMap::new(),
        )
        .expect("the stacked pair plans");
        assert_eq!(plans.len(), 2);
        let (door, tunnel) = (&plans[0], &plans[1]);
        assert!(door.behind_tunnel, "the passway side is derived as behind the tunnel");
        assert_eq!(door.via, None);
        assert_eq!(tunnel.via, Some(IngressVia::Passway));
        assert!(!tunnel.behind_tunnel);
        assert_eq!(door.rules, tunnel.rules, "one rule, carried by both sides");
        assert_eq!(door.front_doors, tunnel.front_doors);
    }

    #[test]
    fn without_via_the_same_two_edges_are_still_a_conflict() {
        // The pre-R910 rule is untouched for every edge that does not opt in.
        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[1].via = None;
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(msg.contains("claimed by 2 edges"), "got: {msg}");
    }

    #[test]
    fn a_via_tunnel_with_no_passway_door_is_refused() {
        let edges = vec![stacked_pair(&[], &["us-west-011"]).remove(1)];
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(
            msg.contains("no `provider = \"passway\"` edge claims it"),
            "got: {msg}"
        );
    }

    #[test]
    fn a_via_tunnel_on_another_machine_than_its_door_is_refused() {
        let msg = stacked_err(stacked_pair(&["us-west-011"], &["us-west-013"]), STACKED_SLOTS);
        assert!(msg.contains("must name the same machines"), "got: {msg}");
        assert!(msg.contains("us-west-013"), "got: {msg}");
    }

    #[test]
    fn a_door_behind_a_tunnel_cannot_also_front_a_public_hostname() {
        let slots = format!(
            "{STACKED_SLOTS}[site]\nkind = \"static\"\nmachine = \"us-west-011\"\n\
             zone = \"staging.noisetable.com\"\nport = 8080\n"
        );
        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[0].hostnames.push("staging.noisetable.com".into());
        let msg = stacked_err(edges, &slots);
        assert!(msg.contains("cannot also be the public door"), "got: {msg}");
        assert!(msg.contains("staging.noisetable.com"), "got: {msg}");
    }

    #[test]
    fn via_on_a_passway_edge_is_refused_rather_than_ignored() {
        let edges = vec![IngressEdge {
            via: Some(IngressVia::Passway),
            ..edge(IngressProvider::Passway, &["us-west-011"], &[])
        }];
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(
            msg.contains("only a `provider = \"cloudflare-tunnel\"` edge can stack"),
            "got: {msg}"
        );
    }

    #[test]
    fn via_is_spelled_in_mirror_toml_as_a_kebab_case_provider() {
        let edge: IngressEdge = toml::from_str(
            "provider = \"cloudflare-tunnel\"\nvia = \"passway\"\nhostnames = [\"a.yah.dev\"]\n",
        )
        .expect("`via` parses");
        assert_eq!(edge.via, Some(IngressVia::Passway));
    }

    #[test]
    fn a_door_behind_a_tunnel_enrolls_one_loopback_backend_per_hostname() {
        let plans = plan_ingress(
            &mirror_edges(stacked_pair(&["us-west-011"], &["us-west-011"]), STACKED_SLOTS),
            &HashMap::new(),
        )
        .unwrap();
        assert_eq!(
            plans[0].door_backends(),
            vec![(
                "api-staging.noisetable.com".to_string(),
                "127.0.0.1:8445".parse().unwrap()
            )]
        );
        assert!(plans[1].door_backends().is_empty(), "the tunnel side enrolls nothing");
    }

    #[test]
    fn a_door_behind_a_tunnel_without_its_table_is_refused() {
        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[0].tunnel_door = None;
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(msg.contains("declare `[ingress.tunnel_door]`"), "got: {msg}");
    }

    #[test]
    fn a_tunnel_door_must_place_exactly_the_hostnames_it_fronts() {
        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[0].tunnel_door = Some(staging_door(&[("staging.noisetable.com", 8445)]));
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(
            msg.contains("names no port for \"api-staging.noisetable.com\""),
            "got: {msg}"
        );

        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[0].tunnel_door = Some(staging_door(&[
            ("api-staging.noisetable.com", 8445),
            ("typo.noisetable.com", 8446),
        ]));
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(msg.contains("\"typo.noisetable.com\""), "got: {msg}");
    }

    #[test]
    fn a_tunnel_door_on_a_public_door_or_on_the_tunnel_edge_is_refused() {
        let mut public = stacked_pair(&["us-west-011"], &["us-west-011"]);
        public.remove(1);
        let msg = stacked_err(public, STACKED_SLOTS);
        assert!(
            msg.contains("no `via = \"passway\"` tunnel edge stacks in front of it"),
            "got: {msg}"
        );

        let mut on_tunnel = stacked_pair(&["us-west-011"], &["us-west-011"]);
        on_tunnel[1].tunnel_door = Some(staging_door(&[("api-staging.noisetable.com", 8445)]));
        let msg = stacked_err(on_tunnel, STACKED_SLOTS);
        assert!(msg.contains("only the `provider = \"passway\"` edge"), "got: {msg}");
    }

    #[test]
    fn two_hostnames_cannot_share_a_door_port() {
        let mut edges = stacked_pair(&["us-west-011"], &["us-west-011"]);
        edges[0].tunnel_door = Some(staging_door(&[
            ("api-staging.noisetable.com", 8445),
            ("staging.noisetable.com", 8445),
        ]));
        let msg = stacked_err(edges, STACKED_SLOTS);
        assert!(msg.contains("the same port 8445"), "got: {msg}");
    }

    #[test]
    fn tunnel_door_is_spelled_as_a_table_under_the_passway_edge() {
        let edge: IngressEdge = toml::from_str(
            "provider = \"passway\"\nhostnames = [\"a.yah.dev\"]\n\n[tunnel_door]\n\
             contact_email = \"ops@yah.dev\"\nzone_id = \"z\"\ntoken_secret = \"yah/cf-dns\"\n\
             ports = { \"a.yah.dev\" = 8445 }\n",
        )
        .expect("`[ingress.tunnel_door]` parses");
        assert_eq!(edge.tunnel_door.unwrap().ports.get("a.yah.dev"), Some(&8445));
    }

    #[test]
    fn an_edge_whose_selector_matches_nothing_is_an_error() {
        // A typo'd slot name otherwise deploys a front door that publishes an
        // empty rule set — a working appliance serving nothing.
        let m = mirror_edges(
            vec![
                edge(IngressProvider::Passway, &["us-east-001"], &["bundle"]),
                edge(IngressProvider::Passway, &["us-west-001"], &["internl"]),
                edge(IngressProvider::Passway, &["us-south-001"], &["internal"]),
            ],
            MIXED_SLOTS,
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("fronts nothing"), "got: {msg}");
        assert!(msg.contains("internl"), "names the typo: {msg}");
    }

    #[test]
    fn several_edges_require_every_one_to_say_what_it_fronts() {
        let m = mirror_edges(
            vec![
                edge(IngressProvider::Passway, &["us-east-001"], &[]),
                edge(
                    IngressProvider::CloudflareTunnel,
                    &["us-west-001"],
                    &["internal"],
                ),
            ],
            MIXED_SLOTS,
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("needs every edge to name what it fronts"), "got: {msg}");
    }

    #[test]
    fn one_selectorless_edge_still_fronts_everything() {
        // The legacy shape, expressed as a list. It must keep meaning what
        // `ingress = "passway"` meant, or migrating a mirror silently drops
        // slots.
        let m = mirror_edges(
            vec![edge(IngressProvider::Passway, &["us-east-001"], &[])],
            MIXED_SLOTS,
        );
        let plan = only_plan(&m);
        assert_eq!(plan.rules.len(), 2);
    }

    #[test]
    fn the_legacy_scalar_spelling_plans_the_same_edge_as_the_list_form() {
        // `ingress = "passway"` + `ingress_machines` is kept as shorthand, not
        // deprecated — one service, one front door is the common case. What
        // must not happen is the two spellings drifting.
        let slots = "[compute]\nuse = \"hetzner\"\nmachine = \"us-east-001\"\n\
                     zone = \"a.yah.dev\"\nport = 8080\n";
        let scalar = only_plan(&mirror_placed(
            IngressProvider::Passway,
            &["us-east-001", "us-south-001"],
            slots,
        ));
        let listed = only_plan(&mirror_edges(
            vec![edge(
                IngressProvider::Passway,
                &["us-east-001", "us-south-001"],
                &[],
            )],
            slots,
        ));
        assert_eq!(scalar, listed);
    }

    #[test]
    fn placement_declared_twice_is_an_error_not_a_precedence_rule() {
        let mut m = mirror_edges(
            vec![edge(IngressProvider::Passway, &["us-east-001"], &[])],
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        m.ingress_machines = vec!["us-west-001".into()];
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("stated twice"), "got: {msg}");
        assert!(msg.contains("us-west-001"), "got: {msg}");
    }

    #[test]
    fn an_edge_may_name_its_own_tunnel_overriding_the_nodes() {
        // W267 Gap 3, from the service side: which cohort a service fronts
        // through is a property of the service, so a node fronting two cohorts
        // never has to enumerate them.
        let m = mirror_edges(
            vec![IngressEdge {
                tunnel_id: Some("cohort-b-tunnel".into()),
                ..edge(IngressProvider::CloudflareTunnel, &["us-east-001"], &[])
            }],
            "[compute]\nuse = \"cloudflare\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        assert_eq!(only_plan(&m).tunnel_id.as_deref(), Some("cohort-b-tunnel"));
    }

    #[test]
    fn an_edge_may_name_the_account_its_tunnel_belongs_to() {
        // R845: the fronted slot's compute is an inline `kind = "static"` box —
        // a borrowed machine with no credentials to reference — so there is no
        // slot `use` to read the Cloudflare account off. The edge names it.
        let m = mirror_edges(
            vec![IngressEdge {
                provider_id: Some("cloudflare".into()),
                ..edge(IngressProvider::CloudflareTunnel, &["borrowed-01"], &[])
            }],
            "[compute]\nkind = \"static\"\nmachine = \"borrowed-01\"\n\
             zone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.edge_provider_id.as_deref(), Some("cloudflare"));
        assert_eq!(plan.provider_id(), Some("cloudflare"));
        // The slot still names nothing — that is the whole point. Before this
        // field the only way to satisfy the lookup was to write
        // `use = "cloudflare"` on the compute slot and lie about what runs it.
        assert_eq!(plan.slot_provider_ids().next(), None);
    }

    #[test]
    fn an_edge_use_overrides_the_fronted_slots_own_provider() {
        // The two facts are unrelated: hetzner runs the compute, cloudflare
        // holds the tunnel. Reading the account off the slot conflates them.
        let m = mirror_edges(
            vec![IngressEdge {
                provider_id: Some("cloudflare".into()),
                ..edge(IngressProvider::CloudflareTunnel, &["us-east-001"], &[])
            }],
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.provider_id(), Some("cloudflare"));
        assert_eq!(plan.slot_provider_ids().collect::<Vec<_>>(), vec!["hetzner"]);
    }

    #[test]
    fn without_an_edge_use_the_fronted_slot_still_answers() {
        // Every mirror on disk before R845 — yah-marketing's bundle slot among
        // them — declares no edge `use`, and must plan identically.
        let m = mirror_edges(
            vec![edge(IngressProvider::CloudflareTunnel, &["us-east-001"], &[])],
            "[compute]\nuse = \"cloudflare\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        assert_eq!(plan.edge_provider_id, None);
        assert_eq!(plan.provider_id(), Some("cloudflare"));
    }

    #[test]
    fn edge_use_round_trips_through_the_mirror_toml_as_use() {
        // Spelled `use` on the edge exactly as it is on a slot — one word for
        // one concept, or an operator has to learn two.
        let decl: crate::config::IngressDecl = toml::from_str(
            "[[ingress]]\nprovider = \"cloudflare-tunnel\"\nuse = \"cloudflare\"\n",
        )
        .map(|w: EdgeWrapper| w.ingress)
        .expect("edge fixture parses");
        let crate::config::IngressDecl::Edges(edges) = decl else {
            panic!("expected the list form");
        };
        assert_eq!(edges[0].provider_id.as_deref(), Some("cloudflare"));
        let back = toml::to_string(&edges[0]).expect("edge serializes");
        assert!(back.contains("use = \"cloudflare\""), "got: {back}");
    }

    #[derive(serde::Deserialize)]
    struct EdgeWrapper {
        ingress: crate::config::IngressDecl,
    }

    #[test]
    fn an_edge_that_fronts_with_nothing_is_rejected() {
        let m = mirror_edges(
            vec![edge(IngressProvider::None, &["us-east-001"], &[])],
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let msg = format!("{:#}", plan_ingress(&m, &HashMap::new()).unwrap_err());
        assert!(msg.contains("fronts nothing"), "got: {msg}");
    }

    #[test]
    fn both_spellings_round_trip_through_toml() {
        // The list form has to survive save/load, and the scalar form has to
        // keep parsing — every mirror on disk is written in it.
        let scalar: MirrorConfig = toml::from_str(
            "schema_version = 1\nshape = \"single-machine\"\ningress = \"passway\"\n\
             ingress_machines = [\"us-east-001\"]\n",
        )
        .expect("scalar spelling parses");
        assert_eq!(scalar.ingress_edges().unwrap().len(), 1);

        let listed: MirrorConfig = toml::from_str(
            "schema_version = 1\nshape = \"single-machine\"\n\
             [[ingress]]\nprovider = \"passway\"\nslots = [\"bundle\"]\n\
             [[ingress]]\nprovider = \"cloudflare-tunnel\"\nhostnames = [\"x.yah.dev\"]\n",
        )
        .expect("list spelling parses");
        let edges = listed.ingress_edges().unwrap();
        assert_eq!(edges.len(), 2);
        assert_eq!(edges[0].slots, vec!["bundle".to_string()]);
        assert_eq!(edges[1].provider, IngressProvider::CloudflareTunnel);

        let back: MirrorConfig = toml::from_str(&toml::to_string_pretty(&listed).unwrap())
            .expect("list spelling round-trips");
        assert_eq!(back.ingress_edges().unwrap(), edges);
    }

    #[test]
    fn a_misspelled_provider_says_what_the_legal_values_are() {
        // Why IngressDecl deserializes by hand: `#[serde(untagged)]` reports
        // only "data did not match any variant of untagged enum IngressDecl",
        // which names neither the field nor the vocabulary. A config value that
        // fails to say what is wrong with it is the same class of defect W305
        // is about.
        let err = toml::from_str::<MirrorConfig>(
            "schema_version = 1\nshape = \"single-machine\"\n\
             [[ingress]]\nprovider = \"passwya\"\n",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("passwya"), "names the bad value: {msg}");
        assert!(msg.contains("passway"), "names the legal ones: {msg}");

        // Same for the scalar spelling.
        let err = toml::from_str::<MirrorConfig>(
            "schema_version = 1\nshape = \"single-machine\"\ningress = \"pasway\"\n",
        )
        .unwrap_err();
        assert!(err.to_string().contains("pasway"), "got: {err}");
    }

    // ── point_at_inner_door (R870-F23 step 5) ──

    /// The override, and the thing that makes it not a `resolve_*` call: an
    /// operator's pinned `port` / `upstream_host` names ONE unit, and fronting
    /// a two-unit service from one of its units serves half the site and 503s
    /// the other half. So the pin has to lose here, unlike everywhere else.
    #[test]
    fn an_inner_door_overrides_a_pinned_upstream_rather_than_deferring_to_it() {
        let mut p = plan(IngressProvider::Passway, &["us-east-001"], "noisetable.com", 8080);
        // The pin every mirror on disk carries.
        assert_eq!(p.rules[0].upstream_hosts, vec!["100.64.0.5".to_string()]);

        p.point_at_inner_door(14210).unwrap();

        assert_eq!(p.rules[0].upstream_hosts, vec!["127.0.0.1".to_string()]);
        assert_eq!(p.rules[0].port, Some(14210));
        assert_eq!(
            p.passway_upstreams().unwrap(),
            vec!["noisetable.com=127.0.0.1:14210".to_string()]
        );
    }

    /// Every rule of a multi-hostname edge is repointed — an apex and its `www`
    /// go through the same door, and leaving one behind would front half the
    /// hostnames from the bundle and half from the inner door.
    #[test]
    fn every_rule_of_an_edge_is_repointed_not_just_the_first() {
        let mut p = plan(IngressProvider::Passway, &["us-east-001"], "noisetable.com", 8080);
        p.rules.push(IngressRule {
            hostname: "www.noisetable.com".into(),
            port: None,
            slot: "compute".into(),
            provider_id: None,
            machines: Vec::new(),
            upstream_hosts: Vec::new(),
        });
        p.point_at_inner_door(14210).unwrap();
        assert_eq!(
            p.passway_upstreams().unwrap(),
            vec![
                "noisetable.com=127.0.0.1:14210".to_string(),
                "www.noisetable.com=127.0.0.1:14210".to_string(),
            ]
        );
    }

    /// Idempotent, because the number is derived rather than allocated: two
    /// applies of an unchanged tree render byte-identical config, which is the
    /// property every other resolver in this file also holds.
    #[test]
    fn repointing_twice_renders_the_same_config() {
        let mut once = plan(IngressProvider::Passway, &["us-east-001"], "noisetable.com", 8080);
        once.point_at_inner_door(14210).unwrap();
        let mut twice = once.clone();
        twice.point_at_inner_door(14210).unwrap();
        assert_eq!(once, twice);
    }

    // ── collation: what each NODE runs (W305 F2) ──

    fn planned(service: &str, plan: IngressPlan) -> PlannedEdge {
        PlannedEdge {
            service: service.into(),
            env: "prod".into(),
            plan,
        }
    }

    /// A one-rule plan for `hostname`, fronted on `machines`.
    fn plan(provider: IngressProvider, machines: &[&str], hostname: &str, port: u16) -> IngressPlan {
        IngressPlan {
            provider,
            rules: vec![IngressRule {
                hostname: hostname.into(),
                port: Some(port),
                slot: "compute".into(),
                provider_id: None,
                machines: Vec::new(),
                upstream_hosts: vec!["100.64.0.5".into()],
            }],
            front_doors: machines.iter().map(|s| s.to_string()).collect(),
            tunnel_id: None,
            edge_provider_id: None,
            image: None,
            auth: None,
            via: None,
            behind_tunnel: false,
            tunnel_door: None,
        }
    }

    /// [`plan`] as a cloudflare tunnel stacked `via` the node's passway (R910).
    fn via_passway(machines: &[&str], hostname: &str, port: u16) -> IngressPlan {
        IngressPlan {
            via: Some(IngressVia::Passway),
            ..plan(IngressProvider::CloudflareTunnel, machines, hostname, port)
        }
    }

    #[test]
    fn a_stacked_pair_collates_and_both_of_its_doors_know_it() {
        // The noisetable R704-T4 door: one hostname under two providers, which
        // is a conflict for every shape except this one.
        let mut door = plan(
            IngressProvider::Passway,
            &["us-west-011"],
            "api-staging.noisetable.com",
            4332,
        );
        door.behind_tunnel = true;
        let c = collate_front_doors(&[
            planned("noisetable-api", door),
            planned(
                "noisetable-api",
                via_passway(&["us-west-011"], "api-staging.noisetable.com", 4332),
            ),
        ])
        .expect("a stacked pair is not a two-provider conflict");
        assert_eq!(c.front_doors.len(), 2, "one cloudflared and one passway on the node");
        for d in &c.front_doors {
            assert_eq!(d.machine, "us-west-011");
            assert_eq!(
                d.stacked,
                vec!["api-staging.noisetable.com".to_string()],
                "the {} side must record the pair",
                d.provider.as_str()
            );
        }
    }

    #[test]
    fn a_stacked_tunnel_on_a_node_its_door_is_not_on_is_a_conflict() {
        let err = collate_front_doors(&[
            planned(
                "svc-door",
                plan(IngressProvider::Passway, &["us-west-011"], "a.yah.dev", 8080),
            ),
            planned("svc-tunnel", via_passway(&["us-west-013"], "a.yah.dev", 8080)),
        ])
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("on us-west-013"), "names the tunnel's node: {msg}");
        assert!(msg.contains("fronted on us-west-011"), "names where the door is: {msg}");
        assert!(msg.contains("svc-tunnel/prod"), "got: {msg}");
    }

    #[test]
    fn a_stacked_tunnel_does_not_license_a_direct_one_for_the_same_hostname() {
        // A tunnel dialing the workload plus a tunnel dialing the demux is not
        // a pair: the `via` names passway, and no passway door exists.
        let err = collate_front_doors(&[
            planned(
                "svc-a",
                plan(IngressProvider::CloudflareTunnel, &["us-west-011"], "a.yah.dev", 8080),
            ),
            planned("svc-b", via_passway(&["us-west-011"], "a.yah.dev", 8080)),
        ])
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("no \"passway\" door fronts that hostname"), "got: {msg}");
    }

    #[test]
    fn only_the_stacked_hostnames_on_a_shared_node_are_marked() {
        // Another service's plain passway hostname on the same node must stay
        // an apex origin — the mark is per hostname, not per door.
        let c = collate_front_doors(&[
            planned(
                "svc-public",
                plan(IngressProvider::Passway, &["us-west-011"], "public.yah.dev", 9090),
            ),
            planned(
                "svc-stacked",
                plan(IngressProvider::Passway, &["us-west-011"], "stacked.yah.dev", 8080),
            ),
            planned("svc-stacked", via_passway(&["us-west-011"], "stacked.yah.dev", 8080)),
        ])
        .unwrap();
        let passway = c
            .front_doors
            .iter()
            .find(|d| d.provider == IngressProvider::Passway)
            .unwrap();
        assert_eq!(passway.rules.len(), 2);
        assert_eq!(passway.stacked, vec!["stacked.yah.dev".to_string()]);
    }

    #[test]
    fn two_services_fronting_one_node_collate_into_one_appliance() {
        // The fact no per-service apply can see: us-east-001 runs ONE passway,
        // and its upstream set is the union of every service pointed at it.
        let c = collate_front_doors(&[
            planned(
                "yah-marketing",
                plan(IngressProvider::Passway, &["us-east-001"], "yah.dev", 8080),
            ),
            planned(
                "yah-issues",
                plan(
                    IngressProvider::Passway,
                    &["us-east-001"],
                    "issues.yah.dev",
                    8731,
                ),
            ),
        ])
        .unwrap();

        assert_eq!(c.front_doors.len(), 1, "one appliance, not one per service");
        let door = &c.front_doors[0];
        assert_eq!(door.machine, "us-east-001");
        assert_eq!(
            door.passway_upstreams().unwrap(),
            vec!["issues.yah.dev=100.64.0.5:8731", "yah.dev=100.64.0.5:8080"]
        );
        assert_eq!(
            door.sources,
            vec!["yah-issues/prod".to_string(), "yah-marketing/prod".to_string()],
            "provenance answers `why is this hostname on this box`"
        );
        assert!(c.unplaced.is_empty());
        assert_eq!(door.auth, None, "neither edge declared any");
    }

    fn analytics_auth() -> PasswayAuth {
        PasswayAuth {
            key_secret: "cheers/yah-camp/verify".into(),
            kid: "YOHV4Riq-g8fX4uYl8rTjQ".into(),
            iss: "yah-camp".into(),
            aud: "analytics.yah.dev".into(),
            require_prefixes: vec!["/".into()],
        }
    }

    /// R556-F6: the shape R870-F26 had to refuse. A confidential tenant and a
    /// public site share one node's door; the authed edge's prefixes are
    /// scoped to ITS hostnames, so the public site stays anonymous.
    #[test]
    fn an_authed_and_an_anonymous_service_share_one_door_host_scoped() {
        let mut authed = plan(IngressProvider::Passway, &["us-east-001"], "analytics.yah.dev", 8444);
        authed.auth = Some(analytics_auth());
        let anonymous = plan(IngressProvider::Passway, &["us-east-001"], "yah.dev", 8080);

        for order in [
            [planned("yah-analytics", authed.clone()), planned("yah-marketing", anonymous.clone())],
            [planned("yah-marketing", anonymous.clone()), planned("yah-analytics", authed.clone())],
        ] {
            let c = collate_front_doors(&order).expect("host-scoped auth shares the appliance");
            assert_eq!(c.front_doors.len(), 1);
            let auth = c.front_doors[0].auth.as_ref().expect("the authed edge's auth survives");
            assert_eq!(
                auth.require_prefixes,
                vec!["analytics.yah.dev=/".to_string()],
                "scoped to analytics only — never a bare `/` that would cover yah.dev"
            );
            assert_eq!(auth.aud, "analytics.yah.dev");
        }
    }

    /// Two authed services with the same verifier merge their host-scoped
    /// prefixes; two DIFFERENT verifiers are still refused — passway holds one
    /// `CheersAuth` per process.
    #[test]
    fn one_node_cannot_front_two_services_with_different_verifiers() {
        let mut authed = plan(IngressProvider::Passway, &["us-east-001"], "analytics.yah.dev", 8444);
        authed.auth = Some(analytics_auth());

        let mut same = authed.clone();
        same.rules[0].hostname = "reports.yah.dev".into();
        let c = collate_front_doors(&[
            planned("yah-analytics", authed.clone()),
            planned("yah-reports", same),
        ])
        .expect("same verifier is one appliance");
        assert_eq!(c.front_doors.len(), 1);
        assert_eq!(
            c.front_doors[0].auth.as_ref().unwrap().require_prefixes,
            vec!["analytics.yah.dev=/".to_string(), "reports.yah.dev=/".to_string()]
        );

        let mut other = authed.clone();
        other.rules[0].hostname = "reports.yah.dev".into();
        other.auth.as_mut().unwrap().aud = "reports.yah.dev".into();
        let err = collate_front_doors(&[
            planned("yah-analytics", authed),
            planned("yah-reports", other),
        ])
        .expect_err("one passway process cannot hold two verifiers")
        .to_string();
        assert!(err.contains("us-east-001"), "names the node: {err}");
        assert!(
            err.contains("yah-analytics/prod") && err.contains("yah-reports/prod"),
            "names both declarations: {err}"
        );
    }

    #[test]
    fn one_service_across_three_origins_collates_to_three_appliances() {
        let c = collate_front_doors(&[planned(
            "yah-marketing",
            plan(
                IngressProvider::Passway,
                &["us-east-001", "us-south-001", "us-west-001"],
                "yah.dev",
                8080,
            ),
        )])
        .unwrap();
        assert_eq!(c.front_doors.len(), 3);
        // Every origin serves the identical set — N front doors, ONE deployment.
        for door in &c.front_doors {
            assert_eq!(
                door.passway_upstreams().unwrap(),
                vec!["yah.dev=100.64.0.5:8080"]
            );
        }
    }

    #[test]
    fn two_cohorts_on_one_node_are_two_connectors_not_a_conflict() {
        // W267 Gap 3's actual case, and the reason `tunnel_id` is in the
        // grouping key: one box, two orange networks, two cloudflared processes.
        let mut a = plan(
            IngressProvider::CloudflareTunnel,
            &["us-east-001"],
            "a.yah.dev",
            8080,
        );
        a.tunnel_id = Some("cohort-a".into());
        let mut b = plan(
            IngressProvider::CloudflareTunnel,
            &["us-east-001"],
            "b.yah.dev",
            8081,
        );
        b.tunnel_id = Some("cohort-b".into());

        let c = collate_front_doors(&[planned("svc-a", a), planned("svc-b", b)]).unwrap();
        assert_eq!(c.front_doors.len(), 2);
        assert_eq!(
            c.front_doors
                .iter()
                .map(|d| d.tunnel_id.clone())
                .collect::<Vec<_>>(),
            vec![Some("cohort-a".into()), Some("cohort-b".into())]
        );
    }

    #[test]
    fn one_hostname_through_two_providers_is_a_conflict_naming_both_services() {
        let err = collate_front_doors(&[
            planned(
                "yah-marketing",
                plan(IngressProvider::Passway, &["us-east-001"], "yah.dev", 8080),
            ),
            planned(
                "yah-legacy",
                plan(
                    IngressProvider::CloudflareTunnel,
                    &["us-west-001"],
                    "yah.dev",
                    8080,
                ),
            ),
        ])
        .unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("two different providers"), "got: {msg}");
        assert!(msg.contains("yah-marketing/prod"), "got: {msg}");
        assert!(msg.contains("yah-legacy/prod"), "got: {msg}");
    }

    #[test]
    fn one_hostname_at_two_upstreams_is_a_conflict() {
        // Apply order would decide which one the box ends up with.
        let err = collate_front_doors(&[
            planned(
                "svc-a",
                plan(IngressProvider::Passway, &["us-east-001"], "yah.dev", 8080),
            ),
            planned(
                "svc-b",
                plan(IngressProvider::Passway, &["us-east-001"], "yah.dev", 9090),
            ),
        ])
        .unwrap_err();
        assert!(
            format!("{err:#}").contains("two different upstreams"),
            "got: {err:#}"
        );
    }

    #[test]
    fn an_edge_with_nowhere_to_run_is_reported_not_dropped() {
        let c = collate_front_doors(&[planned(
            "yah-marketing",
            plan(IngressProvider::Passway, &[], "yah.dev", 8080),
        )])
        .unwrap();
        assert!(c.front_doors.is_empty());
        assert_eq!(c.unplaced, vec!["yah-marketing/prod".to_string()]);
    }

    // ── the swap the seam exists for ──

    #[test]
    fn same_mirror_plans_identical_rules_under_either_provider() {
        let slots = "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n";
        let tunnel = only_plan(&mirror(IngressProvider::CloudflareTunnel, slots));
        let passway = only_plan(&mirror(IngressProvider::Passway, slots));
        // Only the provider tag differs — flipping the field is the whole edit.
        assert_ne!(tunnel.provider, passway.provider);
        assert_eq!(tunnel.rules, passway.rules);
    }

    #[test]
    fn renders_both_provider_forms_from_one_rule() {
        let r = rule("a.yah.dev", 8080);
        assert_eq!(r.service_url().unwrap(), "http://100.64.0.5:8080");
        assert_eq!(
            r.passway_upstreams().unwrap(),
            vec!["a.yah.dev=100.64.0.5:8080"]
        );
    }

    #[test]
    fn a_rule_with_two_backends_renders_both_passway_entries() {
        // R844-F3, the renderer half: passway's grammar load-balances repeated
        // hostnames (`parse_upstream_sets` builds one set per host key), so a
        // workload on two nodes must emit two entries. Collapsing to one is
        // invisible in the config and sends every request to one node.
        let mut r = rule("a.yah.dev", 8080);
        r.upstream_hosts = vec!["100.64.0.5".into(), "100.64.0.9".into()];
        assert_eq!(
            r.passway_upstreams().unwrap(),
            vec!["a.yah.dev=100.64.0.5:8080", "a.yah.dev=100.64.0.9:8080"]
        );
        // The tunnel arm genuinely cannot: one `service` per hostname rule, HA
        // by connector count. It collapses in ONE named place.
        assert_eq!(r.service_url().unwrap(), "http://100.64.0.5:8080");
    }

    #[test]
    fn a_plan_at_scale_two_renders_every_backend() {
        // End to end through the planner: two declared nodes, two discovered
        // addresses, two rendered upstreams. The assertion that fails if any
        // stage collapses the set.
        let m = mirror(
            IngressProvider::Passway,
            "[bundle]\nuse = \"cloudflare\"\nmachines = [\"us-east-001\", \"us-west-001\"]\n\
             zone = \"yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        assert_eq!(plan.workload_machines(), vec!["us-east-001", "us-west-001"]);
        plan.resolve_upstreams(|r| {
            assert_eq!(r.machines, vec!["us-east-001", "us-west-001"]);
            Ok(vec!["100.64.0.3".into(), "100.64.0.8".into()])
        })
        .unwrap();
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["yah.dev=100.64.0.3:8080", "yah.dev=100.64.0.8:8080"]
        );
    }

    // ── resolve_upstreams (R599-F12: no loopback default) ──

    #[test]
    fn an_unresolved_rule_renders_nothing_rather_than_dialing_loopback() {
        let m = mirror(
            IngressProvider::CloudflareTunnel,
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let plan = only_plan(&m);
        // Before R599-F12 this silently produced http://127.0.0.1:8080 and the
        // failure only showed up as a 502 at request time.
        let err = plan.rules[0].service_url().unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("service-records"), "got: {msg}");
        assert!(msg.contains("upstream_host"), "got: {msg}");
    }

    #[test]
    fn discovery_fills_the_upstream_from_placement() {
        let m = mirror(
            IngressProvider::Passway,
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams(|r| {
            assert_eq!(r.port, Some(8080));
            Ok(vec!["100.64.0.7".into()])
        })
        .unwrap();
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["a.yah.dev=100.64.0.7:8080"]
        );
    }

    #[test]
    fn an_explicit_upstream_host_wins_over_discovery() {
        let m = mirror(
            IngressProvider::Passway,
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n\
             upstream_host = \"127.0.0.1\"\n",
        );
        let mut plan = only_plan(&m);
        plan.resolve_upstreams(|_| panic!("discovery must not run for a pinned slot"))
            .unwrap();
        assert_eq!(
            plan.passway_upstreams().unwrap(),
            vec!["a.yah.dev=127.0.0.1:8080"]
        );
    }

    #[test]
    fn no_ready_record_is_an_error_not_an_empty_upstream() {
        let m = mirror(
            IngressProvider::CloudflareTunnel,
            "[compute]\nuse = \"hetzner\"\nzone = \"a.yah.dev\"\nport = 8080\n",
        );
        let mut plan = only_plan(&m);
        let err = plan.resolve_upstreams(|_| Ok(Vec::new())).unwrap_err();
        assert!(format!("{err:#}").contains("no resolved upstream address"));
    }

    // ── merge_tunnel_ingress ──

    /// A rule with its upstream already resolved to a mesh address — what a
    /// plan looks like after `resolve_upstreams`.
    fn rule(hostname: &str, port: u16) -> IngressRule {
        IngressRule {
            hostname: hostname.into(),
            port: Some(port),
            slot: "compute".into(),
            provider_id: None,
            machines: Vec::new(),
            upstream_hosts: vec!["100.64.0.5".into()],
        }
    }

    #[test]
    fn merge_appends_catch_all_when_tunnel_is_empty() {
        let out = merge_tunnel_ingress(&[], &tunnel(vec![rule("a.yah.dev", 8080)])).unwrap();
        assert_eq!(
            out,
            vec![
                json!({"hostname": "a.yah.dev", "service": "http://100.64.0.5:8080"}),
                json!({"service": "http_status:404"}),
            ]
        );
    }

    #[test]
    fn merge_keeps_a_neighbours_rule_verbatim_including_unmodelled_fields() {
        let live = vec![
            json!({
                "hostname": "other.yah.dev",
                "service": "http://127.0.0.1:9999",
                "path": "/api/*",
                "originRequest": {"noTLSVerify": true}
            }),
            json!({"service": "http_status:404"}),
        ];
        let out = merge_tunnel_ingress(&live, &tunnel(vec![rule("a.yah.dev", 8080)])).unwrap();
        assert_eq!(
            out[0], live[0],
            "neighbour rule must survive byte-identical"
        );
        assert_eq!(
            out[1],
            json!({"hostname": "a.yah.dev", "service": "http://100.64.0.5:8080"})
        );
        assert_eq!(out[2], json!({"service": "http_status:404"}));
    }

    #[test]
    fn merge_replaces_an_owned_hostname_and_keeps_the_live_catch_all() {
        let live = vec![
            json!({"hostname": "a.yah.dev", "service": "http://127.0.0.1:1111"}),
            json!({"service": "http_status:503"}),
        ];
        let out = merge_tunnel_ingress(&live, &tunnel(vec![rule("a.yah.dev", 8080)])).unwrap();
        assert_eq!(
            out,
            vec![
                json!({"hostname": "a.yah.dev", "service": "http://100.64.0.5:8080"}),
                json!({"service": "http_status:503"}),
            ]
        );
    }

    #[test]
    fn merge_is_idempotent() {
        let plan = tunnel(vec![rule("a.yah.dev", 8080)]);
        let once = merge_tunnel_ingress(&[], &plan).unwrap();
        let twice = merge_tunnel_ingress(&once, &plan).unwrap();
        assert_eq!(once, twice);
    }

    /// A tunnel plan over `rules`, dialing the workload.
    fn tunnel(rules: Vec<IngressRule>) -> IngressPlan {
        IngressPlan {
            rules,
            ..plan(IngressProvider::CloudflareTunnel, &["us-east-001"], "unused", 1)
        }
    }

    #[test]
    fn a_via_passway_rule_renders_the_live_stacked_config_exactly() {
        // Byte-for-byte the config noisetable R704-T4 PUT by hand on tunnel
        // 1b41587a and verified end to end. Before R910 an apply REPLACED this
        // rule with `http://<compute>` and no originRequest — routing the
        // tunnel around passway — so the equality is the fix, and merging it
        // into itself is the no-PUT proof.
        let mut stacked = tunnel(vec![rule("api-staging.noisetable.com", 4332)]);
        stacked.via = Some(IngressVia::Passway);
        let live = vec![
            json!({
                "hostname": "api-staging.noisetable.com",
                "service": "https://127.0.0.1:443",
                "originRequest": {"matchSNItoHost": true},
            }),
            json!({"service": "http_status:404"}),
        ];
        assert_eq!(merge_tunnel_ingress(&live, &stacked).unwrap(), live);
        assert_eq!(
            merge_tunnel_ingress(&[], &stacked).unwrap(),
            live,
            "an empty tunnel renders the same config"
        );
    }

    #[test]
    fn merge_treats_empty_hostname_as_the_catch_all() {
        // Cloudflare renders the trailing rule with `hostname: ""` in some
        // responses; it must not be mistaken for a routable hostname.
        let live = vec![json!({"hostname": "", "service": "http_status:404"})];
        let out = merge_tunnel_ingress(&live, &tunnel(vec![rule("a.yah.dev", 8080)])).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(
            out[1],
            json!({"hostname": "", "service": "http_status:404"})
        );
    }
}