canic-host 0.110.0

Host-side App build and desired-state Fleet reconciliation library for Canic workspaces
Documentation
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
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
use super::*;
use crate::{
    fleet_ensure::{
        model::{
            CanisterRuntimeStatus, CurrentFleetProtocolAction, EffectRecord, EffectState,
            EnsureAction, FleetEnsureCompletion, FleetEnsureJournalRecord, FleetEnsureStateRecord,
            FleetObservation, LiveCanister, RootManagementCanisterObservation,
            RootManagementObservation, RootOwnedCanisterLifecycle,
        },
        ops::{
            EffectObservation, EffectOutcome, EffectRetry, EnsurePaths, EnsurePlatform,
            IcpEnsurePlatform, IcpEnsurePlatformError, action_sha256, read_journal,
            read_root_start_authority, read_state, write_journal, write_plan, write_state,
        },
        workflow,
    },
    network::{NetworkEnrollmentOptions, enroll_network},
    release_build::{finalize_release_build_from_manifest, plan_release_build_for_profile},
    release_set::{
        ApplicationArtifactBuildOutput, ApplicationArtifactBuildTarget, ApplicationArtifactUnion,
        CanicInfrastructureArtifactManifest, CurrentReleaseSetManifest,
    },
    test_support::temp_dir,
};
use canic_control_plane::{
    dto::template::TemplateChunkSetPrepareInput,
    ids::{TemplateId, TemplateVersion},
};
use canic_core::{
    cdk::{
        types::Cycles,
        utils::hash::{hex_bytes, sha256_hex},
    },
    dto::pool::{CanisterPoolAsset, CanisterPoolAssetOrigin, CanisterPoolAssetStatus},
    dto::{
        component_provisioning::{
            FleetComponentProvisioningOperation, FleetComponentProvisioningPlan,
            FleetComponentProvisioningPrepareRequest,
        },
        fleet_registry::FleetRegistryVersion,
    },
    ids::{
        CanisterRole, ComponentDeploymentConfigurationDigest, FleetCoordinatorBinding, FleetKey,
        FleetRegistryAuthority, FleetSubnetRootReleaseSet, ReleaseBuildNonce, ReleaseSetDigest,
    },
    role_contract::{ProtocolProfileDigest, RoleCapabilityKey},
};
use flate2::{Compression, GzBuilder};
#[cfg(unix)]
use std::os::unix::fs::{PermissionsExt, symlink};
use std::{collections::BTreeSet, fs, io, io::Write as _};

#[test]
fn fresh_pool_creation_funding_preserves_toko_shaped_readiness_floor() {
    assert_eq!(
        fresh_pool_creation_funding(1_900_000_000_000)
            .expect("compile Toko-shaped fresh pool funding"),
        3_000_000_000_000
    );
}

#[test]
fn estate_seed_retains_explicit_fleet_id_independent_from_operator() {
    let fleet_id = "a5".repeat(32);
    let coordinator = Principal::from_slice(&[2]).to_text();
    let seed: EstateSeed = toml::from_str(&format!(
        r#"
schema_version = 1
fleet_id = "{fleet_id}"
coordinator = "{coordinator}"
roots = []
"#
    ))
    .expect("estate seed with retained Fleet ID");

    assert_eq!(seed.fleet_id.to_string(), fleet_id);
}

#[test]
fn retained_pool_imports_above_root_initialisation_maximum_reject_during_generation() {
    let operator = Principal::from_slice(&[31]).to_text();
    let coordinator_subnet = Principal::from_slice(&[32]).to_text();
    let placement = Principal::from_slice(&[33]).to_text();
    let root = Principal::from_slice(&[34]).to_text();
    let source = multi_component_source(&operator, &coordinator_subnet, &placement);
    let seed = EstateSeed {
        schema_version: 1,
        fleet_id: "a4".repeat(32).parse().expect("Fleet ID"),
        fresh_estate: false,
        coordinator: Principal::from_slice(&[35]).to_text(),
        treasury: None,
        cycles_ledger: mainnet_cycles_ledger(),
        management_creation_fee_cycles: None,
        roots: vec![RootSeed {
            placement_subnet: placement,
            root: root.clone(),
            store: Principal::from_slice(&[36]).to_text(),
            pool_imports: [37, 38, 39]
                .map(|byte| Principal::from_slice(&[byte]).to_text())
                .to_vec(),
        }],
    };

    assert!(matches!(
        validate_identity_seed(&source, &seed),
        Err(FleetGenerateError::PoolImportCapacity(
            RootPoolImportCapacityError {
                import_count: 3,
                maximum_size: 2,
                root: rejected_root,
            }
        )) if rejected_root == root
    ));
}

#[test]
fn treasury_adoption_requires_one_observed_seeded_identity() {
    let seed = EstateSeed {
        schema_version: 1,
        fleet_id: "a6".repeat(32).parse().expect("Fleet ID"),
        fresh_estate: false,
        coordinator: Principal::from_slice(&[3]).to_text(),
        treasury: None,
        cycles_ledger: mainnet_cycles_ledger(),
        management_creation_fee_cycles: None,
        roots: Vec::new(),
    };
    let observed = BTreeMap::<String, ObservedCanister>::new();
    let treasury = seed
        .treasury
        .as_ref()
        .map_or(seed.coordinator.as_str(), |treasury| {
            treasury.principal.as_str()
        });

    assert!(!observed.contains_key(treasury));
}

#[test]
fn release_build_network_must_match_the_selected_environment() {
    let release_build_id =
        ReleaseBuildId::from_nonce(ReleaseBuildNonce::from_random_bytes([7; 32]));

    require_release_build_network(
        release_build_id,
        BuildNetwork::Ic,
        "staging",
        BuildNetwork::Ic,
    )
    .expect("IC artifact is admitted for an IC environment");
    assert!(matches!(
        require_release_build_network(
            release_build_id,
            BuildNetwork::Local,
            "staging",
            BuildNetwork::Ic,
        ),
        Err(FleetGenerateError::Release(reason))
            if reason.contains("targets local") && reason.contains("requires ic")
    ));
}

#[test]
fn retained_identities_and_controller_sets_are_exact() {
    let principal = Principal::from_slice(&[5]).to_text();
    let foreign = Principal::from_slice(&[6]).to_text();
    let mut identities = BTreeSet::new();

    insert_seed_identity(&mut identities, "Coordinator", &principal).expect("first role");
    assert!(matches!(
        insert_seed_identity(&mut identities, "Root", &principal),
        Err(FleetGenerateError::SeedTopology(_))
    ));
    require_exact_controllers(&principal, vec![principal.clone()], vec![principal.clone()])
        .expect("exact controller set");
    assert!(matches!(
        require_exact_controllers(
            &principal,
            vec![principal.clone(), foreign],
            vec![principal.clone()]
        ),
        Err(FleetGenerateError::ControllerMismatch { .. })
    ));
}

#[test]
fn management_runtime_and_module_observations_fail_closed() {
    assert!(matches!(
        parse_observed_runtime_status("root", "running"),
        Ok(CanisterRuntimeStatus::Running)
    ));
    assert!(matches!(
        parse_observed_runtime_status("root", "STOPPED"),
        Ok(CanisterRuntimeStatus::Stopped)
    ));
    assert!(matches!(
        parse_observed_runtime_status("root", "stopping"),
        Ok(CanisterRuntimeStatus::Stopping)
    ));
    assert!(matches!(
        parse_observed_runtime_status("root", "starting"),
        Err(FleetGenerateError::CanisterUnavailable { .. })
    ));

    let uppercase = "AB".repeat(32);
    let normalized = normalize_observed_module_sha256("root", &format!("0x{uppercase}"))
        .expect("valid observed module hash");
    assert_eq!(normalized, uppercase.to_ascii_lowercase());
    let non_hex = "gg".repeat(32);
    for invalid in ["ab", non_hex.as_str()] {
        assert!(matches!(
            normalize_observed_module_sha256("root", invalid),
            Err(FleetGenerateError::CanisterUnavailable { .. })
        ));
    }
}

#[test]
fn root_policy_drift_requires_the_reviewed_reinstall() {
    let operator = Principal::from_slice(&[11]);
    let source = multi_component_source(
        &operator.to_text(),
        &principal_text(12),
        &principal_text(13),
    );
    let root = source.fleet_subnet_roots.first().expect("Root policy");
    let expected = RootDesiredPolicy {
        component_admissions: Vec::new(),
        component_topology_digest: canic_core::ids::ComponentTopologyDigest::from_bytes([14; 32]),
        funding: root_funding(source.funding_profile, &root.root_funding),
        installation_controller: operator,
        limits: root_limits(root),
    };
    let mut retained = expected.clone();
    retained.limits.canister_pool.canister_cycles = Cycles::new(2_000_000_000_000);

    require_root_policy_convergence(
        "retained-root",
        &retained,
        &expected,
        Some(&"15".repeat(32)),
        &"16".repeat(32),
    )
    .expect("old pool policy converges through current Root reinstall");
    assert!(matches!(
        require_root_policy_convergence(
            "retained-root",
            &retained,
            &expected,
            Some(&"16".repeat(32)),
            &"16".repeat(32),
        ),
        Err(FleetGenerateError::SeedTopology(_))
    ));
    require_root_policy_convergence(
        "retained-root",
        &expected,
        &expected,
        Some(&"16".repeat(32)),
        &"16".repeat(32),
    )
    .expect("matching current policy needs no reinstall");
}

#[test]
fn multi_root_generation_joins_topology_by_typed_subnet_identity() {
    let (first_subnet, second_subnet) = divergent_principal_order_pair();
    let first_text = first_subnet.to_text();
    let second_text = second_subnet.to_text();
    let operator = Principal::from_slice(&[41]).to_text();
    let coordinator_subnet = Principal::from_slice(&[42]).to_text();
    let source_template = multi_component_source(&operator, &coordinator_subnet, &first_text)
        .fleet_subnet_roots
        .remove(0);
    let mut sources = vec![source_template.clone(), source_template];
    sources[0].placement_subnet.clone_from(&first_text);
    sources[1].placement_subnet.clone_from(&second_text);
    sources.sort_by(|left, right| left.placement_subnet.cmp(&right.placement_subnet));
    let mut seeds = vec![
        RootSeed {
            placement_subnet: first_text,
            root: Principal::from_slice(&[43]).to_text(),
            store: Principal::from_slice(&[44]).to_text(),
            pool_imports: Vec::new(),
        },
        RootSeed {
            placement_subnet: second_text,
            root: Principal::from_slice(&[45]).to_text(),
            store: Principal::from_slice(&[46]).to_text(),
            pool_imports: Vec::new(),
        },
    ];
    seeds.sort_by(|left, right| left.placement_subnet.cmp(&right.placement_subnet));
    let mut planned = sources
        .iter()
        .enumerate()
        .map(|(index, source)| PlannedFleetSubnetRootTopology {
            placement_subnet: parse_subnet("test Root", &source.placement_subnet)
                .expect("typed test Subnet"),
            component_admissions: Vec::new(),
            component_topology_digest: canic_core::ids::ComponentTopologyDigest::from_bytes(
                [u8::try_from(index + 1).expect("bounded test index"); 32],
            ),
            limits: root_limits(source),
        })
        .collect::<Vec<_>>();
    planned.sort_by_key(|root| root.placement_subnet);

    let text_order = sources
        .iter()
        .map(|root| root.placement_subnet.clone())
        .collect::<Vec<_>>();
    let typed_order = planned
        .iter()
        .map(|root| root.placement_subnet.to_string())
        .collect::<Vec<_>>();
    assert_ne!(
        text_order, typed_order,
        "fixture must exercise divergent orders"
    );

    let bindings =
        bind_root_generation_inputs(&sources, &seeds, &planned).expect("exact typed Subnet join");
    assert_eq!(bindings.len(), 2);
    for binding in bindings {
        assert_eq!(
            binding.source.placement_subnet,
            binding.planned.placement_subnet.to_string()
        );
        assert_eq!(
            binding.seed.placement_subnet,
            binding.planned.placement_subnet.to_string()
        );
    }
}

#[test]
fn separate_treasury_seed_carries_exact_placement() {
    let coordinator = Principal::from_slice(&[8]).to_text();
    let treasury = Principal::from_slice(&[9]).to_text();
    let subnet = Principal::from_slice(&[10]).to_text();
    let fleet_id = "a9".repeat(32);
    let seed: EstateSeed = toml::from_str(&format!(
        r#"
schema_version = 1
fleet_id = "{fleet_id}"
coordinator = "{coordinator}"
roots = []

[treasury]
principal = "{treasury}"
subnet = "{subnet}"
"#
    ))
    .expect("typed treasury seed");

    assert_eq!(
        seed.treasury,
        Some(TreasurySeed {
            principal: treasury,
            subnet,
        })
    );
}

#[test]
fn protected_policy_and_estate_seed_have_distinct_authority_shapes() {
    let principal = Principal::from_slice(&[7]).to_text();
    let source = format!(
        r#"
schema_version = 1
funding_profile = "preview_multi_subnet"
operator = "{principal}"

[admission]
principals = ["{principal}"]

[coordinator.subnet]
kind = "explicit"
subnet = "{principal}"
acknowledge_fiduciary_cost = false

[coordinator.creation_funding]
kind = "cycles"
cycles = "140T"

[coordinator.root_funding]
minimum_reserve_cycles = "80T"
window_secs = 7776000
maximum_cycles = "30T"
maximum_automatic_grants = 2
maximum_automatic_cycles = "60T"

[[fleet_subnet_roots]]
placement_subnet = "{principal}"
component_admissions = {{ app = 1 }}

[fleet_subnet_roots.component_group_placements]
app = [0]

[fleet_subnet_roots.canister_pool]
minimum_size = 2
maximum_size = 2
canister_cycles = "5T"

[fleet_subnet_roots.root_funding]
request_threshold = "10T"
target_balance = "30T"
cooldown_secs = 2592000
window_secs = 7776000
maximum_cycles = "30T"
maximum_automatic_grants = 2
maximum_automatic_cycles = "60T"

[fleet_subnet_roots.limits]
maximum_component_instances = 8
maximum_registry_bytes = 1048576
maximum_wasm_store_bytes = 1048576
maximum_group_placements = 8

[fleet_subnet_roots.limits.cycles_funding]
window_secs = 2592000
maximum_cycles = "30T"

[fleet_subnet_roots.root_creation_funding]
kind = "cycles"
cycles = "30T"

[fleet_subnet_roots.wasm_store_creation_funding]
kind = "cycles"
cycles = "10T"
"#
    );
    let source: FleetSource = toml::from_str(&source).expect("protected policy shape");
    let seed: EstateSeed = toml::from_str(&format!(
        r#"
schema_version = 1
fleet_id = "{}"
coordinator = "{principal}"

[[roots]]
placement_subnet = "{principal}"
root = "{principal}"
store = "{principal}"
pool_imports = []
"#,
        "a7".repeat(32)
    ))
    .expect("estate identity seed shape");

    assert_eq!(source.fleet_subnet_roots.len(), 1);
    assert_eq!(seed.treasury, None);
    assert_eq!(seed.roots.len(), 1);
}

#[test]
fn human_admission_principals_compile_to_one_canonical_set() {
    let (first, second) = divergent_principal_order_pair();
    let authored = [
        first.to_text(),
        second.to_text(),
        Principal::from_slice(&[73; 29]).to_text(),
    ];
    let mut canonical = authored
        .iter()
        .map(|value| Principal::from_text(value).expect("typed admission Principal"))
        .collect::<Vec<_>>();
    canonical.sort_unstable();

    let mut expected = None;
    for order in [
        [0, 1, 2],
        [0, 2, 1],
        [1, 0, 2],
        [1, 2, 0],
        [2, 0, 1],
        [2, 1, 0],
    ] {
        let values = order.map(|index| authored[index].clone());
        let compiled = compile_source_admission_policy(&values)
            .expect("human-authored Principal set compiles");
        assert_eq!(compiled.fleet_principals, canonical);
        if let Some(expected) = &expected {
            assert_eq!(&compiled, expected);
        } else {
            expected = Some(compiled);
        }
    }

    let duplicate = authored[0].clone();
    assert!(matches!(
        compile_source_admission_policy(&[duplicate.clone(), duplicate.clone()]),
        Err(FleetGenerateError::Authority(reason)) if reason.contains(&duplicate)
    ));
    assert!(matches!(
        compile_source_admission_policy(&[Principal::anonymous().to_text()]),
        Err(FleetGenerateError::Authority(reason)) if reason.contains("anonymous")
    ));
}

#[test]
fn protected_policy_rejects_unsuffixed_cycle_amounts_before_generation() {
    let principal = Principal::from_slice(&[8]).to_text();
    let source = multi_component_source_toml(&principal, &principal, &principal);
    for invalid in [
        source.replacen(
            "canister_cycles = \"5T\"",
            "canister_cycles = \"5000000000000\"",
            1,
        ),
        source.replacen(
            "canister_cycles = \"5T\"",
            "canister_cycles = 5000000000000",
            1,
        ),
    ] {
        assert!(
            toml::from_str::<FleetSource>(&invalid).is_err(),
            "accepted unsuffixed human cycle authority"
        );
    }
}

#[test]
fn generation_rejects_component_demand_above_pool_target_before_observation() {
    let root = temp_dir("fleet-generate-pool-capacity");
    let app_config = root.join("apps/demo/canic.toml");
    let source_path = root.join("deployments/staging.toml");
    let seed_path = root.join("deployments/staging.estate.toml");
    fs::create_dir_all(app_config.parent().expect("App config parent"))
        .expect("create App config parent");
    fs::create_dir_all(source_path.parent().expect("source parent")).expect("create source parent");
    fs::write(&app_config, multi_component_config()).expect("write App config");
    let operator = principal_text(20);
    let coordinator = principal_text(21);
    let fleet_root = principal_text(22);
    let store = principal_text(23);
    let pool_one = principal_text(24);
    let pool_two = principal_text(25);
    let placement = principal_text(26);
    let coordinator_subnet = principal_text(27);
    let source = multi_component_source_toml(&operator, &coordinator_subnet, &placement).replacen(
        "canister_cycles = \"5T\"",
        "canister_cycles = \"4.8T\"",
        1,
    );
    fs::write(&source_path, source).expect("write insufficient pool source");
    fs::write(
        &seed_path,
        retained_estate_seed_toml(
            "a8".repeat(32).parse().expect("Fleet ID"),
            &coordinator,
            &placement,
            &fleet_root,
            &store,
            [&pool_one, &pool_two],
        ),
    )
    .expect("write estate seed");
    let request = FleetGenerateRequest {
        app_config: &app_config,
        environment: "local",
        fleet: "staging",
        icp_executable: "must-not-run",
        release_build_id: ReleaseBuildId::from_nonce(ReleaseBuildNonce::from_random_bytes([9; 32])),
        root: &root,
        seed: &seed_path,
        source: &source_path,
    };

    assert!(matches!(
        generate_desired_fleet(&request),
        Err(FleetGenerateError::ComponentPoolCapacity(
            RootPoolCapacityError::Insufficient {
                component_spec,
                pool_target_cycles: 4_800_000_000_000,
                required_cycles: 5_000_000_000_000,
                root,
            }
        )) if component_spec.as_str() == "app" && root == fleet_root
    ));
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "one retained-estate journey keeps generation, convergence, conservation, and replay together"
)]
fn generated_multi_component_retained_estate_plans_applies_and_replays_without_effect() {
    let root = temp_dir("fleet-generate-retained-journey");
    let app_config = root.join("apps/demo/canic.toml");
    fs::create_dir_all(app_config.parent().expect("App config parent"))
        .expect("create App config parent");
    fs::write(&app_config, multi_component_config()).expect("write App config");
    let canonical_network_id = enroll_test_network(&root);
    let config = AppConfigSnapshot::load(&app_config).expect("load App config");
    let operator = principal_text(20);
    let coordinator = principal_text(21);
    let fleet_root = principal_text(22);
    let store = principal_text(23);
    let pool_one = principal_text(24);
    let pool_two = principal_text(25);
    let placement = principal_text(26);
    let coordinator_subnet = principal_text(27);
    let (admission_first, admission_second) = divergent_principal_order_pair();
    let mut authored_admission = vec![
        operator.clone(),
        admission_first.to_text(),
        admission_second.to_text(),
    ];
    authored_admission.sort();
    let mut canonical_admission = authored_admission
        .iter()
        .map(|value| Principal::from_text(value).expect("typed admission Principal"))
        .collect::<Vec<_>>();
    canonical_admission.sort_unstable();
    assert_ne!(
        authored_admission
            .iter()
            .map(|value| Principal::from_text(value).expect("typed authored Principal"))
            .collect::<Vec<_>>(),
        canonical_admission,
        "fixture must distinguish display-text and typed Principal order"
    );
    let mut source = multi_component_source(&operator, &coordinator_subnet, &placement);
    source.admission.principals.clone_from(&authored_admission);
    let seed = EstateSeed {
        schema_version: 1,
        fleet_id: "a8".repeat(32).parse().expect("Fleet ID"),
        fresh_estate: false,
        coordinator: coordinator.clone(),
        treasury: None,
        cycles_ledger: mainnet_cycles_ledger(),
        management_creation_fee_cycles: None,
        roots: vec![RootSeed {
            placement_subnet: placement.clone(),
            root: fleet_root.clone(),
            store: store.clone(),
            pool_imports: vec![pool_one.clone(), pool_two.clone()],
        }],
    };
    validate_identity_seed(&source, &seed).expect("retained identities");
    let root_inputs = source
        .fleet_subnet_roots
        .iter()
        .map(|root| PlannedFleetSubnetRootTopologyInput {
            placement_subnet: parse_subnet("Root", &root.placement_subnet).expect("Root Subnet"),
            component_admissions: root
                .component_admissions
                .iter()
                .map(
                    |(component_spec, maximum_root_instances)| RootComponentAdmissionInput {
                        component_spec: component_spec.clone(),
                        maximum_root_instances: *maximum_root_instances,
                    },
                )
                .collect(),
            limits: root_limits(root),
        })
        .collect();
    let topology =
        plan_initial_fleet_topology(config.model(), root_inputs).expect("initial Fleet topology");
    let release_build =
        plan_release_build_for_profile(&root, crate::build_profile::CanisterBuildProfile::Fast)
            .expect("plan retained release build");
    let release_build_id = release_build.record.release_build_id;
    persist_test_release_authority(&root, &config, release_build_id);
    let source_path = root.join("deployments/retained-multi-component.toml");
    let seed_path = root.join("deployments/retained-multi-component.estate.toml");
    fs::create_dir_all(source_path.parent().expect("deployment parent"))
        .expect("create deployment parent");
    let source_document = multi_component_source_toml(&operator, &coordinator_subnet, &placement)
        .replacen(
            &format!("principals = [\"{operator}\"]"),
            &format!(
                "principals = [{}]",
                authored_admission
                    .iter()
                    .map(|principal| format!("\"{principal}\""))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            1,
        );
    fs::write(&source_path, source_document).expect("write protected Fleet source");
    fs::write(
        &seed_path,
        retained_estate_seed_toml(
            seed.fleet_id,
            &coordinator,
            &placement,
            &fleet_root,
            &store,
            [&pool_one, &pool_two],
        ),
    )
    .expect("write retained estate seed");
    let retained_authority = retained_root_authority(
        canonical_network_id,
        config.model().app_id().clone(),
        seed.fleet_id,
        &source,
        &topology.fleet_subnet_roots[0],
        &operator,
        &coordinator,
        &coordinator_subnet,
        &fleet_root,
        &store,
        release_build_id,
    );
    let retained_pool = retained_pool_response(
        retained_authority.binding.limits.canister_pool.clone(),
        &store,
        &pool_one,
        &pool_two,
    );
    let coordinator_module_hash = "83".repeat(32);
    let root_module_hash = "84".repeat(32);
    let store_module_hash = "85".repeat(32);
    let write_icp = |root_runtime_status| {
        write_fake_icp(
            &root,
            FakeIcpFixture {
                authority: &retained_authority,
                coordinator: &coordinator,
                coordinator_module_hash: &coordinator_module_hash,
                fleet_root: &fleet_root,
                operator: &operator,
                pool: &retained_pool,
                public_cycle_balance: None,
                root_module_hash: &root_module_hash,
                root_runtime_status,
                root_status_error: None,
                store: &store,
                store_has_root_controller: false,
                store_module_hash: &store_module_hash,
            },
        )
    };
    let icp = write_icp("stopped");
    let request = FleetGenerateRequest {
        app_config: &app_config,
        environment: "local",
        fleet: "retained-multi-component",
        icp_executable: icp.to_str().expect("fake ICP path"),
        release_build_id,
        root: &root,
        seed: &seed_path,
        source: &source_path,
    };
    let preserved_output = root.join("fleets/retained-multi-component.toml");
    fs::create_dir_all(preserved_output.parent().expect("desired output parent"))
        .expect("create desired output parent");
    fs::write(&preserved_output, b"retained desired authority\n")
        .expect("write retained desired authority");
    let Err(stopped) = generate_desired_fleet(&request) else {
        panic!("a stopped retained Root requires a separately reviewed same-ID Start");
    };
    let stopped_message = stopped.to_string();
    assert!(matches!(
        stopped,
        FleetGenerateError::StoppedRootStartRequired(details)
        if matches!(details.as_ref(), StoppedRootStartPrerequisite {
            controller,
            fleet,
            module_sha256,
            root: stopped_root,
            subnet,
            ..
        } if controller == &operator
            && fleet == "retained-multi-component"
            && module_sha256 == &root_module_hash
            && stopped_root == &fleet_root
            && subnet == &placement)
    ));
    let Err(repeated) = generate_desired_fleet(&request) else {
        panic!("the same stopped Root prerequisite must remain deterministic");
    };
    assert_eq!(repeated.to_string(), stopped_message);
    assert!(
        !root.join("root-status-count").exists(),
        "the no-effect generator must not query a stopped Root"
    );
    assert_eq!(
        fs::read(&preserved_output).expect("read preserved desired authority"),
        b"retained desired authority\n"
    );

    write_icp("running");
    let generated = generate_desired_fleet(&request).expect("generate from live retained estate");
    assert_eq!(generated.observed_canisters, 5);
    assert_eq!(generated.observed_controlled_cycles, 319_900_000_000_000);
    assert_eq!(generated.release_build_id, release_build_id);
    let desired = generated.desired;
    assert_eq!(
        desired
            .bootstrap
            .as_ref()
            .expect("generated bootstrap authority")
            .admission
            .fleet_principals,
        canonical_admission,
        "human-authored Principal text order must not affect runtime authority"
    );
    let observed = [
        (&coordinator, 270_000_000_000_000_u128, &coordinator_subnet),
        (&fleet_root, 30_000_000_000_000, &placement),
        (&store, 10_000_000_000_000, &placement),
        (&pool_one, 4_900_000_000_000, &placement),
        (&pool_two, 5_000_000_000_000, &placement),
    ]
    .into_iter()
    .map(|(principal, cycles, subnet)| {
        (
            principal.clone(),
            ObservedCanister {
                cycles,
                module_sha256: None,
                subnet: subnet.clone(),
            },
        )
    })
    .collect::<BTreeMap<_, _>>();
    assert_eq!(
        desired
            .canisters
            .iter()
            .filter(|canister| canister.kind == DesiredCanisterKind::Pool)
            .count(),
        2,
        "both paid pool assets remain explicitly retained"
    );
    assert_eq!(desired.ledger_fee_cycles, "0.1B");
    assert_eq!(desired.management_creation_fee_cycles, "0B");
    assert_eq!(desired.material_cycle_threshold, "0.001B");
    assert_eq!(desired.maximum_observation_burn_cycles, "1T");
    for value in [
        &desired.ledger_fee_cycles,
        &desired.management_creation_fee_cycles,
        &desired.material_cycle_threshold,
        &desired.maximum_observation_burn_cycles,
        &desired.maximum_update_burn_cycles,
    ]
    .into_iter()
    .chain(
        desired
            .canisters
            .iter()
            .flat_map(|canister| [&canister.initial_cycles, &canister.minimum_cycles]),
    ) {
        Cycles::from_human_config_str(value).expect("generated cycle value uses compact units");
    }

    let fresh_seed_path = root.join("deployments/fresh-multi-component.estate.toml");
    let fresh_id = initialize_fresh_estate_seed(&FreshEstateSeedRequest {
        cycles_ledger: &mainnet_cycles_ledger(),
        management_creation_fee_cycles: 500_000_000_000,
        seed: &fresh_seed_path,
        source: &source_path,
    })
    .expect("initialize durable fresh estate seed");
    let repeated_id = initialize_fresh_estate_seed(&FreshEstateSeedRequest {
        cycles_ledger: &mainnet_cycles_ledger(),
        management_creation_fee_cycles: 500_000_000_000,
        seed: &fresh_seed_path,
        source: &source_path,
    })
    .expect("replay durable fresh estate seed");
    assert_eq!(repeated_id, fresh_id);
    let fresh = generate_desired_fleet(&FleetGenerateRequest {
        app_config: &app_config,
        environment: "local",
        fleet: "fresh-multi-component",
        icp_executable: icp.to_str().expect("fake ICP path"),
        release_build_id,
        root: &root,
        seed: &fresh_seed_path,
        source: &source_path,
    })
    .expect("generate literally empty estate");
    assert_eq!(fresh.observed_canisters, 0);
    assert_eq!(fresh.observed_controlled_cycles, 0);
    assert_eq!(fresh.desired.treasury, "coordinator");
    assert_eq!(fresh.desired.management_creation_fee_cycles, "500B");
    let fresh_seed = fs::read_to_string(&fresh_seed_path).expect("read fresh estate seed");
    assert!(fresh_seed.contains("management_creation_fee_cycles = \"500B\""));
    let invalid_fresh_seed_path = root.join("deployments/fresh-invalid-units.estate.toml");
    fs::write(
        &invalid_fresh_seed_path,
        fresh_seed.replace(
            "management_creation_fee_cycles = \"500B\"",
            "management_creation_fee_cycles = \"500000000000\"",
        ),
    )
    .expect("write invalid fresh estate seed fixture");
    assert!(matches!(
        generate_desired_fleet(&FleetGenerateRequest {
            app_config: &app_config,
            environment: "local",
            fleet: "fresh-invalid-units",
            icp_executable: icp.to_str().expect("fake ICP path"),
            release_build_id,
            root: &root,
            seed: &invalid_fresh_seed_path,
            source: &source_path,
        }),
        Err(FleetGenerateError::FreshSeedConflict(_))
    ));
    assert!(
        fresh
            .desired
            .bootstrap
            .as_ref()
            .is_some_and(|bootstrap| bootstrap.fresh_estate)
    );
    assert!(
        fresh
            .desired
            .canisters
            .iter()
            .all(|canister| canister.principal.is_none())
    );
    let fresh_store = fresh
        .desired
        .canisters
        .iter()
        .find(|canister| canister.kind == DesiredCanisterKind::Store)
        .expect("fresh Store");
    assert_eq!(fresh_store.controller_canisters, ["root-0"]);
    let fresh_pools = fresh
        .desired
        .canisters
        .iter()
        .filter(|canister| canister.kind == DesiredCanisterKind::Pool)
        .collect::<Vec<_>>();
    assert_eq!(fresh_pools.len(), 2);
    assert!(
        fresh_pools
            .iter()
            .all(|canister| canister.controller_canisters == ["root-0"])
    );
    let fresh_artifacts =
        crate::fleet_ensure::ops::resolve_desired_artifacts(&root, &fresh.desired)
            .expect("resolve fresh release artifacts");
    let mut insufficient_fresh = fresh.desired.clone();
    for pool in insufficient_fresh
        .canisters
        .iter_mut()
        .filter(|canister| canister.kind == DesiredCanisterKind::Pool)
    {
        pool.initial_cycles = "1.9T".to_string();
        pool.minimum_cycles = "1.9T".to_string();
    }
    let insufficient_error = crate::fleet_ensure::policy::compile_plan(
        &insufficient_fresh,
        &fresh_artifacts,
        &[],
        &"73".repeat(32),
        &insufficient_fresh.fleet,
        &FleetObservation {
            additional_controlled_cycles: BTreeMap::new(),
            canisters: insufficient_fresh
                .canisters
                .iter()
                .map(|canister| (canister.name.clone(), None))
                .collect(),
            ledger_fee_cycles: 100_000_000,
            operator_cycles: u128::MAX,
            protocol_ready: BTreeMap::new(),
        },
        1_800_000_000_000_000_000,
    )
    .expect_err("fresh pool funding without its execution margin rejects before effects");
    assert!(matches!(
        insufficient_error,
        crate::fleet_ensure::policy::EnsurePolicyError::FreshPoolCreationFundingInsufficient {
            admissible_burn_cycles: 1_100_000_000_000,
            creation_funding_cycles: 1_900_000_000_000,
            readiness_floor_cycles: 1_900_000_000_000,
            required_creation_funding_cycles: 3_000_000_000_000,
            shortfall_cycles: 1_100_000_000_000,
            ..
        }
    ));
    let fresh_plan = crate::fleet_ensure::policy::compile_plan(
        &fresh.desired,
        &fresh_artifacts,
        &[],
        &"74".repeat(32),
        &fresh.desired.fleet,
        &FleetObservation {
            additional_controlled_cycles: BTreeMap::new(),
            canisters: fresh
                .desired
                .canisters
                .iter()
                .map(|canister| (canister.name.clone(), None))
                .collect(),
            ledger_fee_cycles: 100_000_000,
            operator_cycles: u128::MAX,
            protocol_ready: BTreeMap::new(),
        },
        1_800_000_000_000_000_000,
    )
    .expect("compile fresh estate creation plan");
    let ordered_fresh_actions = workflow::ordered_actions(&fresh_plan);
    let root_install_index = ordered_fresh_actions
        .iter()
        .position(|action| {
            matches!(
                action,
                EnsureAction::Install {
                    canic_init: Some(DesiredCanisterInit::Root { root }),
                    name,
                    ..
                } if root == "root-0" && name == "root-0"
            )
        })
        .expect("fresh Root installation action");
    for pool in &fresh_pools {
        let pool_plan = fresh_plan
            .canisters
            .iter()
            .find(|canister| canister.name == pool.name)
            .expect("fresh pool plan");
        assert!(pool_plan.actions.iter().any(|action| {
            matches!(
                action,
                EnsureAction::Create {
                    controller_canisters,
                    controllers,
                    ..
                } if controller_canisters == &["root-0"]
                    && controllers == std::slice::from_ref(&fresh.desired.operator)
            )
        }));
        let finalization_index = ordered_fresh_actions
            .iter()
            .position(|action| {
                matches!(
                    action,
                    EnsureAction::SetControllers {
                        controller_canisters,
                        controllers,
                        name,
                        ..
                    } if name == &pool.name
                        && controller_canisters == &["root-0"]
                        && controllers.is_empty()
                )
            })
            .expect("fresh pool final controller action");
        assert!(finalization_index > root_install_index);
    }
    assert!(
        fresh_plan
            .canisters
            .iter()
            .all(|canister| canister.disposition
                == crate::fleet_ensure::model::CanisterDisposition::Create)
    );
    let created = fresh_plan
        .canisters
        .iter()
        .flat_map(|canister| &canister.actions)
        .filter_map(|action| match action {
            EnsureAction::Create {
                ledger,
                name,
                requested_initial_cycles,
                ..
            } => Some((ledger, name, *requested_initial_cycles)),
            _ => None,
        })
        .collect::<Vec<_>>();
    assert_eq!(created.len(), fresh.desired.canisters.len());
    assert!(
        created
            .iter()
            .all(|(ledger, _, _)| { *ledger == &fresh.desired.cycles_ledger })
    );
    for pool in &fresh_pools {
        let (_, _, funded) = created
            .iter()
            .find(|(_, name, _)| name.as_str() == pool.name.as_str())
            .expect("fresh pool creation is reviewed directly");
        assert_eq!(pool.initial_cycles, "6.1T");
        assert_eq!(pool.minimum_cycles, "5T");
        assert_eq!(
            pool.initial_cycles
                .parse::<Cycles>()
                .map(|cycles| cycles.to_u128()),
            Ok(*funded),
        );
    }
    let legacy_pool = fresh_pools.first().expect("first fresh pool");
    let mut legacy_desired = fresh.desired.clone();
    let legacy_desired_pool = legacy_desired
        .canisters
        .iter_mut()
        .find(|canister| canister.name == legacy_pool.name)
        .expect("Toko-shaped published-line pool");
    legacy_desired_pool.initial_cycles = "1.9T".to_string();
    legacy_desired_pool.minimum_cycles = "1.9T".to_string();
    let legacy_principal = Principal::from_slice(&[91]).to_text();
    let mut legacy_state = read_state(
        &EnsurePaths::under(&root, "local", "legacy-underfunded-pool"),
        "legacy-underfunded-pool",
    )
    .expect("construct legacy underfunded state");
    legacy_state
        .pending_principals
        .insert(legacy_pool.name.clone(), legacy_principal.clone());
    let legacy_action = EnsureAction::Create {
        controller_canisters: legacy_pool.controller_canisters.clone(),
        controllers: vec![fresh.desired.operator.clone()],
        created_at_time: 1_800_000_000_000_000_000,
        ledger: fresh.desired.cycles_ledger.clone(),
        name: legacy_pool.name.clone(),
        requested_initial_cycles: 1_900_000_000_000,
        subnet: legacy_pool.subnet.clone(),
    };
    let legacy_record = EffectRecord {
        action_sha256: action_sha256(&legacy_action),
        created_principal: Some(legacy_principal),
        destination_post_cycles: None,
        destination_pre_cycles: None,
        post_cycles: Some(1_899_998_056_000),
        pre_cycles: None,
        pre_canister_version: None,
        progress_identity: Some("legacy-first-live-balance".to_string()),
        receipt: Some("legacy-create-receipt".to_string()),
        state: EffectState::Applied,
    };
    let legacy_error = workflow::retain_applied_create_authority::<io::Error>(
        &legacy_desired,
        &legacy_action,
        &legacy_record,
        &mut legacy_state,
    )
    .expect_err("underfunded published-line pool stops before controller finalization");
    assert!(matches!(
        legacy_error,
        workflow::EnsureWorkflowError::FreshPoolCreationUnderfunded(details)
        if matches!(details.as_ref(), workflow::FreshPoolCreationUnderfundedError {
            live_balance_cycles: 1_899_998_056_000,
            maximum_observation_burn_cycles: 1_000_000_000_000,
            pre_finalization_shortfall_cycles: 100_001_944_000,
            readiness_floor_cycles: 1_900_000_000_000,
            readiness_shortfall_cycles: 1_944_000,
            remaining_controller_burn_cycles: 100_000_000_000,
            requested_creation_funding_cycles: 1_900_000_000_000,
            required_pre_finalization_balance_cycles: 2_000_000_000_000,
            ..
        })
    ));
    let requested = created
        .iter()
        .try_fold(0_u128, |total, (_, _, amount)| total.checked_add(*amount))
        .expect("fresh funding sum");
    let expected_fees = u128::try_from(created.len())
        .expect("bounded canister count")
        .checked_mul(500_100_000_000)
        .expect("fresh fee sum");
    assert_eq!(
        fresh_plan.conservation.maximum_new_funding_cycles,
        requested
    );
    assert_eq!(
        fresh_plan.conservation.maximum_unavoidable_fee_cycles,
        expected_fees
    );
    assert_eq!(
        fresh_plan.conservation.maximum_operator_debit_cycles,
        requested + expected_fees
    );
    assert!(fresh_plan.canisters.iter().all(|canister| {
        canister
            .actions
            .iter()
            .all(|action| !matches!(action, EnsureAction::Fund { .. }))
    }));

    let fresh_apply_root = root.join("fresh-controller-finalization");
    copy_test_tree(&root.join("artifacts"), &fresh_apply_root.join("artifacts"))
        .expect("copy fresh release artifacts");
    let fresh_apply_paths = EnsurePaths::under(
        &fresh_apply_root,
        &fresh.desired.environment,
        &fresh.desired.fleet,
    );
    write_plan(&fresh_apply_paths, &fresh_plan).expect("retain literal fresh plan");
    write_state(
        &fresh_apply_paths,
        &read_state(&fresh_apply_paths, &fresh.desired.fleet)
            .expect("construct fresh application state"),
    )
    .expect("retain fresh application state");
    write_journal(
        &fresh_apply_paths,
        &FleetEnsureJournalRecord {
            completion: FleetEnsureCompletion::InProgress,
            effects: Vec::new(),
            fleet: fresh.desired.fleet.clone(),
            initial_controlled_cycles: 0,
            initial_operator_cycles: u128::MAX,
            operation_id: fresh_plan.operation_id.clone(),
            plan_sha256: fresh_plan.plan_sha256.clone(),
            schema_version: FLEET_ENSURE_SCHEMA_VERSION,
            stalled_observations: 0,
        },
    )
    .expect("retain fresh application journal");
    let fresh_finalizations = workflow::ordered_actions(&fresh_plan)
        .into_iter()
        .filter(|action| matches!(action, EnsureAction::SetControllers { .. }))
        .map(action_sha256)
        .collect::<Vec<_>>();
    let fresh_creates = workflow::ordered_actions(&fresh_plan)
        .into_iter()
        .filter(|action| matches!(action, EnsureAction::Create { .. }))
        .map(action_sha256)
        .collect::<Vec<_>>();
    assert_eq!(fresh_finalizations.len(), 2);
    assert_eq!(fresh_creates.len(), fresh.desired.canisters.len());
    let mut fresh_apply_platform = crate::fleet_ensure::tests::MockPlatform::new(
        fresh.desired.clone(),
        Vec::<LiveCanister>::new(),
    );
    fresh_apply_platform.set_operator_cycles(u128::MAX);
    fresh_apply_platform.require_root_owned_topology();
    fresh_apply_platform.stall_before_mutation(fresh_finalizations[0].clone(), 1);
    fresh_apply_platform.fail_once(fresh_finalizations[0].clone());

    let before_finalization_error = workflow::apply(
        &fresh_apply_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &fresh_plan.plan_sha256,
        &mut fresh_apply_platform,
    )
    .expect_err("interrupt before the first controller finalization");
    assert!(
        matches!(
            before_finalization_error,
            workflow::EnsureWorkflowError::Platform(_)
        ),
        "unexpected pre-finalization error: {before_finalization_error:?}"
    );
    let mut before_finalization = read_state(&fresh_apply_paths, &fresh.desired.fleet)
        .expect("read pre-finalization fresh authority");
    assert_eq!(
        before_finalization.pending_principals.len(),
        fresh.desired.canisters.len()
    );
    assert!(before_finalization.principals.is_empty());
    assert_eq!(
        before_finalization.retained_cycles_by_principal.len(),
        fresh.desired.canisters.len()
    );
    assert_eq!(
        before_finalization.topology.len(),
        fresh.desired.canisters.len()
    );
    let mut before_finalization_journal = read_journal(&fresh_apply_paths)
        .expect("read pre-finalization journal")
        .expect("pre-finalization journal");
    assert_eq!(before_finalization_journal.effects.len(), 9);
    assert_eq!(
        before_finalization_journal.effects[8].state,
        EffectState::Intent
    );
    assert_eq!(
        fresh_apply_platform.mutation_count(&fresh_finalizations[0]),
        0
    );

    let removed_intent = before_finalization_journal
        .effects
        .pop()
        .expect("remove first finalization intent");
    assert_eq!(removed_intent.state, EffectState::Intent);
    assert_eq!(before_finalization_journal.effects.len(), 8);
    write_journal(&fresh_apply_paths, &before_finalization_journal)
        .expect("restore published pre-finalization journal shape");
    before_finalization.retained_cycles_by_principal.clear();
    before_finalization.topology.clear();
    write_state(&fresh_apply_paths, &before_finalization)
        .expect("restore published pre-finalization state shape");

    let after_first_effect_error = workflow::apply(
        &fresh_apply_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &fresh_plan.plan_sha256,
        &mut fresh_apply_platform,
    )
    .expect_err("interrupt after the first controller finalization effect");
    assert!(
        matches!(
            after_first_effect_error,
            workflow::EnsureWorkflowError::Platform(_)
        ),
        "unexpected post-effect error: {after_first_effect_error:?}"
    );
    let after_first_effect = read_journal(&fresh_apply_paths)
        .expect("read first-finalization interruption journal")
        .expect("first-finalization interruption journal");
    assert_eq!(after_first_effect.effects[8].state, EffectState::Intent);
    let reconstructed_state = read_state(&fresh_apply_paths, &fresh.desired.fleet)
        .expect("read reconstructed fresh authority");
    assert_eq!(
        reconstructed_state.retained_cycles_by_principal.len(),
        fresh.desired.canisters.len()
    );
    assert_eq!(
        reconstructed_state.topology.len(),
        fresh.desired.canisters.len()
    );
    assert_eq!(
        fresh_apply_platform.mutation_count(&fresh_finalizations[0]),
        1
    );

    let fresh_terminal = workflow::apply(
        &fresh_apply_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &fresh_plan.plan_sha256,
        &mut fresh_apply_platform,
    )
    .expect("resume both fresh controller finalizations");
    assert!(fresh_terminal.terminal);
    assert_eq!(fresh_terminal.effects_applied, 10);
    for hash in &fresh_creates {
        assert_eq!(fresh_apply_platform.mutation_count(hash), 1);
    }
    for hash in &fresh_finalizations {
        assert_eq!(fresh_apply_platform.mutation_count(hash), 1);
    }
    for pool in &fresh_pools {
        assert!(
            fresh_apply_platform
                .live_controllers(&pool.name)
                .is_some_and(|controllers| controllers == ["created-root-0"])
        );
    }
    let fresh_terminal_state =
        read_state(&fresh_apply_paths, &fresh.desired.fleet).expect("read terminal fresh state");
    assert!(fresh_terminal_state.pending_principals.is_empty());
    assert_eq!(
        fresh_terminal_state.principals.len(),
        fresh.desired.canisters.len()
    );
    let controller_replay_plan = workflow::plan(
        &fresh_apply_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        1_800_000_000_000_000_100,
        &mut fresh_apply_platform,
    )
    .expect("plan effect-free fresh replay");
    assert!(workflow::ordered_actions(&controller_replay_plan.plan).is_empty());
    let controller_replay = workflow::apply(
        &fresh_apply_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &controller_replay_plan.plan.plan_sha256,
        &mut fresh_apply_platform,
    )
    .expect("apply effect-free fresh replay");
    assert!(controller_replay.terminal);
    assert_eq!(controller_replay.effects_applied, 0);

    let mut retained_root_only_plan = fresh_plan.clone();
    for canister in retained_root_only_plan
        .canisters
        .iter_mut()
        .filter(|canister| {
            fresh.desired.canisters.iter().any(|configured| {
                configured.name == canister.name && configured.kind == DesiredCanisterKind::Pool
            })
        })
    {
        canister
            .actions
            .retain(|action| !matches!(action, EnsureAction::SetControllers { .. }));
        for action in &mut canister.actions {
            if let EnsureAction::Create { controllers, .. } = action {
                controllers.clear();
            }
        }
    }
    retained_root_only_plan.plan_sha256 =
        crate::fleet_ensure::policy::expected_plan_sha256(&retained_root_only_plan);
    let retained_root = root.join("retained-root-only-resume");
    copy_test_tree(&root.join("artifacts"), &retained_root.join("artifacts"))
        .expect("copy retained release artifacts");
    let retained_paths = EnsurePaths::under(
        &retained_root,
        &fresh.desired.environment,
        &fresh.desired.fleet,
    );
    write_plan(&retained_paths, &retained_root_only_plan)
        .expect("retain exact pre-correction Root-only plan");
    write_state(
        &retained_paths,
        &read_state(&retained_paths, &fresh.desired.fleet).expect("fresh retained state"),
    )
    .expect("retain empty fresh state");
    let mut retained_platform = crate::fleet_ensure::tests::MockPlatform::new(
        fresh.desired.clone(),
        Vec::<LiveCanister>::new(),
    );
    retained_platform.set_operator_cycles(u128::MAX);
    for pool in &fresh_pools {
        retained_platform.defer_created_until_root_install(&pool.name, "root-0");
    }
    let retained_actions = workflow::ordered_actions(&retained_root_only_plan);
    let pool_creates = retained_actions
        .iter()
        .filter(|action| {
            matches!(
                action,
                EnsureAction::Create { name, .. }
                    if fresh_pools.iter().any(|pool| pool.name == *name)
            )
        })
        .map(|action| action_sha256(action))
        .collect::<Vec<_>>();
    assert_eq!(pool_creates.len(), 2);
    retained_platform.fail_once(pool_creates[1].clone());
    write_journal(
        &retained_paths,
        &FleetEnsureJournalRecord {
            completion: FleetEnsureCompletion::InProgress,
            effects: Vec::new(),
            fleet: fresh.desired.fleet.clone(),
            initial_controlled_cycles: 0,
            initial_operator_cycles: retained_platform.operator_cycles(),
            operation_id: retained_root_only_plan.operation_id.clone(),
            plan_sha256: retained_root_only_plan.plan_sha256.clone(),
            schema_version: FLEET_ENSURE_SCHEMA_VERSION,
            stalled_observations: 0,
        },
    )
    .expect("retain empty pre-correction journal");
    assert!(matches!(
        workflow::apply(
            &retained_root,
            &fresh.desired,
            &"74".repeat(32),
            &fresh.desired.fleet,
            &retained_root_only_plan.plan_sha256,
            &mut retained_platform,
        ),
        Err(workflow::EnsureWorkflowError::Platform(_))
    ));
    let interrupted = read_journal(&retained_paths)
        .expect("read interrupted Root-only journal")
        .expect("interrupted Root-only journal");
    assert_eq!(interrupted.effects[3].state, EffectState::Issued);
    assert_eq!(interrupted.effects[4].state, EffectState::Intent);

    let resumed = workflow::apply(
        &retained_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &retained_root_only_plan.plan_sha256,
        &mut retained_platform,
    )
    .expect("resume Root-only creates through exact Root installation");
    assert!(resumed.terminal);
    for create in &pool_creates {
        assert_eq!(retained_platform.mutation_count(create), 1);
    }
    assert_eq!(
        retained_platform.duplicate_create_response_count(&pool_creates[1]),
        1
    );
    let replay_plan = workflow::plan(
        &retained_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        1_800_000_000_000_000_100,
        &mut retained_platform,
    )
    .expect("plan terminal Root-only replay");
    assert!(workflow::ordered_actions(&replay_plan.plan).is_empty());
    let replay = workflow::apply(
        &retained_root,
        &fresh.desired,
        &"74".repeat(32),
        &fresh.desired.fleet,
        &replay_plan.plan.plan_sha256,
        &mut retained_platform,
    )
    .expect("apply effect-free Root-only replay");
    assert!(replay.terminal);
    assert_eq!(replay.effects_applied, 0);

    let root_status_count = root.join("root-status-count");
    if root_status_count.exists() {
        fs::remove_file(&root_status_count).expect("clear retained Root observation count");
    }
    let fresh_source_digest = "75".repeat(32);
    let mut fresh_platform = IcpEnsurePlatform::new(
        fresh.desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let public_fresh_plan = workflow::plan(
        &root,
        &fresh.desired,
        &fresh_source_digest,
        &fresh.desired.fleet,
        1_800_000_000_000_000_001,
        &mut fresh_platform,
    )
    .expect("public Fleet Ensure plans a literally empty estate");
    assert_eq!(public_fresh_plan.effects_applied, 0);
    assert!(!public_fresh_plan.terminal);
    assert!(
        public_fresh_plan
            .plan
            .canisters
            .iter()
            .all(|canister| canister.disposition
                == crate::fleet_ensure::model::CanisterDisposition::Create)
    );
    assert_eq!(
        public_fresh_plan
            .plan
            .conservation
            .maximum_operator_debit_cycles,
        fresh_plan.conservation.maximum_operator_debit_cycles
    );
    assert!(
        !root_status_count.exists(),
        "an unallocated fresh Root must not be queried before reviewed creation"
    );

    let empty_fresh_state = read_state(
        &EnsurePaths::under(
            &root,
            &fresh.desired.environment,
            "fresh-unallocated-negative",
        ),
        "fresh-unallocated-negative",
    )
    .expect("construct empty current state");
    let mut retained_missing_desired = fresh.desired.clone();
    retained_missing_desired.fleet = "retained-missing-root".to_string();
    retained_missing_desired
        .bootstrap
        .as_mut()
        .expect("generated bootstrap")
        .fresh_estate = false;
    let mut retained_missing_platform = IcpEnsurePlatform::new(
        retained_missing_desired,
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    assert!(matches!(
        retained_missing_platform.observe_root_management(&empty_fresh_state, &BTreeSet::new(),),
        Err(IcpEnsurePlatformError::RootManagement(_))
    ));

    let mut targeted_fresh_platform = IcpEnsurePlatform::new(
        fresh.desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    assert!(matches!(
        targeted_fresh_platform
            .observe_root_management(&empty_fresh_state, &BTreeSet::from(["root-0".to_string()]),),
        Err(IcpEnsurePlatformError::RootManagement(_))
    ));

    write_icp("stopped");
    let mut allocated_fresh_state = empty_fresh_state;
    allocated_fresh_state
        .pending_principals
        .insert("root-0".to_string(), fleet_root.clone());
    let mut allocated_fresh_platform = IcpEnsurePlatform::new(
        fresh.desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    assert!(
        allocated_fresh_platform
            .observe_root_management(&allocated_fresh_state, &BTreeSet::new())
            .expect("observe the exact allocated fresh Root")
            .is_some(),
        "once allocation retains a Principal, ordinary Root management applies"
    );
    assert!(matches!(
        initialize_fresh_estate_seed(&FreshEstateSeedRequest {
            cycles_ledger: &mainnet_cycles_ledger(),
            management_creation_fee_cycles: 1,
            seed: &fresh_seed_path,
            source: &source_path,
        }),
        Err(FleetGenerateError::FreshSeedConflict(_))
    ));

    let source_digest = "42".repeat(32);
    let mut no_apply_desired = desired.clone();
    no_apply_desired.fleet = "retained-multi-component-no-apply".to_string();
    let mut no_apply_platform =
        RetainedEnsurePlatform::new(&no_apply_desired, &observed, &pool_one)
            .with_terminal_observation_protocol();
    let no_apply = workflow::plan(
        &root,
        &no_apply_desired,
        &source_digest,
        &no_apply_desired.fleet,
        1_800_000_000_000_000_000,
        &mut no_apply_platform,
    )
    .expect("plan public generated estate with the complete typed protocol");
    assert_eq!(
        no_apply.plan.plan_sha256,
        crate::fleet_ensure::policy::expected_plan_sha256(&no_apply.plan)
    );
    assert_eq!(no_apply.plan.plan_sha256.len(), 64);
    let provision_index = no_apply
        .plan
        .protocol_actions
        .iter()
        .position(|action| {
            matches!(
                action,
                EnsureAction::FleetProtocol { action, .. }
                    if matches!(action.as_ref(), CurrentFleetProtocolAction::ProvisionComponents { .. })
            )
        })
        .expect("Component provisioning action");
    assert!(
        no_apply.plan.protocol_actions[..provision_index]
            .iter()
            .any(|action| matches!(action, EnsureAction::FleetProtocol { .. })),
        "a non-Component typed protocol action precedes Component provisioning"
    );
    assert_eq!(
        no_apply_platform.mutations, 0,
        "public generation and planning remain effect-free"
    );

    let mut recovery_desired = desired.clone();
    recovery_desired.fleet = "retained-multi-component-recovery".to_string();
    let artifacts = crate::fleet_ensure::ops::resolve_desired_artifacts(&root, &recovery_desired)
        .expect("resolve current infrastructure artifacts");
    let mut recovery_platform =
        RetainedEnsurePlatform::new(&recovery_desired, &observed, &pool_one)
            .with_post_effect_root_owned_protocol();
    for configured in &recovery_desired.canisters {
        let live = recovery_platform
            .live
            .get_mut(configured.principal.as_deref().expect("retained Principal"))
            .expect("retained live canister");
        if matches!(
            configured.kind,
            DesiredCanisterKind::Coordinator
                | DesiredCanisterKind::Root
                | DesiredCanisterKind::Store
        ) {
            live.module_sha256 = artifacts
                .wasm_sha256_by_canister
                .get(&configured.name)
                .cloned();
            live.reinstall_required = true;
            if matches!(
                configured.kind,
                DesiredCanisterKind::Coordinator | DesiredCanisterKind::Store
            ) {
                live.status = CanisterRuntimeStatus::Stopped;
            }
        }
    }
    let recovery = workflow::plan(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        1_800_000_000_000_000_050,
        &mut recovery_platform,
    )
    .expect("plan exact same-module infrastructure recovery");
    let ordered = workflow::ordered_actions(&recovery.plan);
    let store_index = ordered
        .iter()
        .position(|action| action.name() == "store-0")
        .expect("Store reinstall");
    let root_index = ordered
        .iter()
        .position(|action| action.name() == "root-0")
        .expect("Root reinstall");
    assert!(store_index < root_index);
    assert_eq!(ordered.len(), 5);
    assert_eq!(
        ordered
            .iter()
            .filter(|action| matches!(
                action,
                EnsureAction::Install {
                    mode: crate::fleet_ensure::model::InstallMode::Reinstall,
                    ..
                }
            ))
            .count(),
        3
    );
    assert_eq!(
        ordered
            .iter()
            .filter(|action| matches!(action, EnsureAction::Start { .. }))
            .count(),
        2
    );
    assert_eq!(recovery.plan.conservation.maximum_new_funding_cycles, 0);
    assert_eq!(recovery.plan.conservation.maximum_operator_debit_cycles, 0);
    let recovery_error = workflow::apply(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        &recovery.plan.plan_sha256,
        &mut recovery_platform,
    )
    .expect_err("post-effect protocol work requires a successor review");
    assert!(matches!(
        recovery_error,
        workflow::EnsureWorkflowError::ConvergenceDrift
    ));
    assert_eq!(recovery_platform.mutations, 5);
    let recovery_paths = EnsurePaths::under(
        &root,
        &recovery_desired.environment,
        &recovery_desired.fleet,
    );
    let recovery_journal = crate::fleet_ensure::ops::read_journal(&recovery_paths)
        .expect("read recovery journal")
        .expect("retained recovery journal");
    assert_eq!(
        recovery_journal.completion,
        crate::fleet_ensure::model::FleetEnsureCompletion::ReplanRequired
    );
    let retained_recovery_files = [
        fs::read(&recovery_paths.state).expect("retain post-effect state bytes"),
        fs::read(&recovery_paths.plan).expect("retain reviewed plan bytes"),
        fs::read(&recovery_paths.journal).expect("retain applied journal bytes"),
    ];
    assert!(matches!(
        crate::fleet_ensure::read_current_fleet_inventory(
            &root,
            &recovery_desired.environment,
            &recovery_desired.fleet,
        ),
        Err(crate::fleet_ensure::CurrentFleetInventoryError::NotConverged { .. })
    ));
    let retained_recovery_state = read_state(&recovery_paths, &recovery_desired.fleet)
        .expect("read retained post-effect recovery state");
    for configured in recovery_desired.canisters.iter().filter(|configured| {
        matches!(
            configured.kind,
            DesiredCanisterKind::Root | DesiredCanisterKind::Store | DesiredCanisterKind::Pool
        )
    }) {
        assert_eq!(
            retained_recovery_state
                .principals
                .get(&configured.name)
                .map(String::as_str),
            configured.principal.as_deref()
        );
        let retained = retained_recovery_state
            .topology
            .get(&configured.name)
            .expect("retained Root-owned topology");
        assert_eq!(retained.kind, configured.kind);
        assert_eq!(retained.parent, configured.parent);
    }
    let mut resumed_recovery_platform = recovery_platform.fresh_process();
    let successor_recovery = workflow::plan(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        1_800_000_000_000_000_075,
        &mut resumed_recovery_platform,
    )
    .expect("fresh host process replans from retained exact topology");
    assert!(
        successor_recovery
            .plan
            .canisters
            .iter()
            .all(|canister| canister.actions.is_empty()),
        "the successor must not repeat reinstall or Start effects"
    );
    assert!(matches!(
        successor_recovery.plan.protocol_actions.as_slice(),
        [EnsureAction::FleetProtocol { .. }]
    ));
    let resumed = workflow::apply(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        &successor_recovery.plan.plan_sha256,
        &mut resumed_recovery_platform,
    )
    .expect("successor recovery converges through the remaining typed action");
    assert!(resumed.terminal);
    assert_eq!(resumed_recovery_platform.mutations, 1);
    let replay_plan = workflow::plan(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        1_800_000_000_000_000_076,
        &mut resumed_recovery_platform,
    )
    .expect("plan terminal recovery replay");
    assert!(workflow::ordered_actions(&replay_plan.plan).is_empty());
    let replay = workflow::apply(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        &replay_plan.plan.plan_sha256,
        &mut resumed_recovery_platform,
    )
    .expect("terminal recovery replay is effect-free");
    assert!(replay.terminal);
    assert_eq!(replay.effects_applied, 0);
    assert_eq!(resumed_recovery_platform.mutations, 1);

    fs::write(&recovery_paths.state, &retained_recovery_files[0])
        .expect("restore untouched post-effect state");
    fs::write(&recovery_paths.plan, &retained_recovery_files[1])
        .expect("restore untouched reviewed plan");
    fs::write(&recovery_paths.journal, &retained_recovery_files[2])
        .expect("restore untouched applied journal");
    let mut overwritten_successor = crate::fleet_ensure::ops::read_plan(&recovery_paths)
        .expect("read retained reviewed plan")
        .expect("retained reviewed plan");
    for canister in &mut overwritten_successor.canisters {
        canister
            .actions
            .retain(|action| matches!(action, EnsureAction::Install { .. }));
    }
    overwritten_successor.protocol_actions = terminal_observation_protocol_actions(
        &recovery_desired,
        &overwritten_successor.operation_id,
    )
    .into_iter()
    .take(1)
    .collect();
    overwritten_successor.planned_at_time += 1;
    overwritten_successor.plan_sha256 =
        crate::fleet_ensure::policy::expected_plan_sha256(&overwritten_successor);
    assert_ne!(
        overwritten_successor.plan_sha256, recovery_journal.plan_sha256,
        "the rejected successor may already have replaced plan.json"
    );
    crate::fleet_ensure::ops::write_plan(&recovery_paths, &overwritten_successor)
        .expect("retain rejected successor plan without changing the applied journal");
    let mut pending_reset_pool = retained_pool.clone();
    for asset in pending_reset_pool
        .entries
        .iter_mut()
        .filter(|asset| asset.origin == CanisterPoolAssetOrigin::Imported)
    {
        asset.cycles = Cycles::new(0);
        asset.status = CanisterPoolAssetStatus::PendingReset;
    }
    pending_reset_pool.workload = 0;
    pending_reset_pool.ready = 0;
    pending_reset_pool.pending_reset = 2;
    let versionless_icp = write_versionless_root_owned_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: artifacts
                .wasm_sha256_by_canister
                .get("coordinator")
                .expect("Coordinator artifact"),
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &pending_reset_pool,
            public_cycle_balance: None,
            root_module_hash: artifacts
                .wasm_sha256_by_canister
                .get("root-0")
                .expect("Root artifact"),
            root_runtime_status: "running",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: artifacts
                .wasm_sha256_by_canister
                .get("store-0")
                .expect("Store artifact"),
        },
    );
    fs::write(root.join("root-status-count"), b"1\n")
        .expect("select Root pool status after retained authority");
    let mut versionless_platform = VersionlessPlanningPlatform::new(
        IcpEnsurePlatform::new(
            recovery_desired.clone(),
            versionless_icp
                .to_str()
                .expect("version-less fake ICP path"),
            &root,
        ),
        recovery_desired.clone(),
    );
    let versionless_replan = workflow::plan(
        &root,
        &recovery_desired,
        &source_digest,
        &recovery_desired.fleet,
        1_800_000_000_000_000_077,
        &mut versionless_platform,
    )
    .expect("version-less fresh process retains journal-proved reinstalls");
    let repeated_installs = workflow::ordered_actions(&versionless_replan.plan)
        .into_iter()
        .filter_map(|action| match action {
            EnsureAction::Install { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect::<BTreeSet<_>>();
    assert!(
        repeated_installs.is_disjoint(&BTreeSet::from(["coordinator", "root-0", "store-0"])),
        "version-less replan repeated proved infrastructure installs: {repeated_installs:?}"
    );
    assert_eq!(
        versionless_replan
            .plan
            .conservation
            .maximum_new_funding_cycles,
        0
    );
    assert_eq!(
        versionless_replan
            .plan
            .conservation
            .maximum_operator_debit_cycles,
        0
    );
    assert_eq!(
        crate::fleet_ensure::ops::read_journal(&recovery_paths)
            .expect("read version-less replan journal")
            .expect("retained version-less replan journal")
            .completion,
        crate::fleet_ensure::model::FleetEnsureCompletion::ReplanRequired
    );
    assert!(matches!(
        versionless_replan.plan.protocol_actions.as_slice(),
        [EnsureAction::FleetProtocol { .. }]
    ));

    let mut production_recovery_desired = recovery_desired.clone();
    production_recovery_desired.fleet = "retained-multi-component-live-recovery".to_string();
    let coordinator_hash = artifacts
        .wasm_sha256_by_canister
        .get("coordinator")
        .expect("Coordinator artifact");
    let root_hash = artifacts
        .wasm_sha256_by_canister
        .get("root-0")
        .expect("Root artifact");
    let store_hash = artifacts
        .wasm_sha256_by_canister
        .get("store-0")
        .expect("Store artifact");
    let predecessor_root_hash = sha256_hex(b"retained predecessor Root protocol");
    let predecessor_store_hash = sha256_hex(b"retained predecessor Store protocol");
    assert_ne!(&predecessor_root_hash, root_hash);
    assert_ne!(&predecessor_store_hash, store_hash);
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &predecessor_root_hash,
            root_runtime_status: "running",
            root_status_error: Some(canic_core::diagnostics::codes::STATE_CONFLICT),
            store: &store,
            store_has_root_controller: true,
            store_module_hash: &predecessor_store_hash,
        },
    );
    let mut state = retained_ensure_state(&production_recovery_desired, &observed, &artifacts);
    state
        .topology
        .get_mut("root-0")
        .expect("retained Root topology")
        .module_hash = None;
    state
        .topology
        .get_mut("store-0")
        .expect("retained Store topology")
        .module_hash = None;
    assert_eq!(state.topology["root-0"].module_hash, None);
    assert_eq!(state.topology["store-0"].module_hash, None);
    write_state(
        &EnsurePaths::under(
            &root,
            &production_recovery_desired.environment,
            &production_recovery_desired.fleet,
        ),
        &state,
    )
    .expect("retain exact current Fleet evidence");
    let mut production_platform = IcpEnsurePlatform::new(
        production_recovery_desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let production_recovery = workflow::plan(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        1_800_000_000_000_000_100,
        &mut production_platform,
    )
    .expect("plan conflicted Root recovery from retained exact balances");
    let production_actions = workflow::ordered_actions(&production_recovery.plan);
    assert_eq!(
        production_actions
            .iter()
            .filter(|action| matches!(
                action,
                EnsureAction::Install {
                    mode: crate::fleet_ensure::model::InstallMode::Reinstall,
                    ..
                }
            ))
            .count(),
        3,
    );
    assert!(production_recovery.plan.protocol_actions.is_empty());
    assert!(matches!(
        production_actions.as_slice(),
        [
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Coordinator),
                ..
            },
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Store { .. }),
                ..
            },
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Root { .. }),
                ..
            }
        ]
    ));
    assert_eq!(
        production_recovery
            .plan
            .conservation
            .maximum_new_funding_cycles,
        0
    );
    assert_eq!(
        production_recovery
            .plan
            .conservation
            .maximum_operator_debit_cycles,
        0
    );
    let pool_names = production_recovery_desired
        .canisters
        .iter()
        .filter(|canister| canister.kind == DesiredCanisterKind::Pool)
        .map(|canister| canister.name.as_str())
        .collect::<BTreeSet<_>>();
    let retained_assets = production_recovery
        .plan
        .canisters
        .iter()
        .filter(|canister| pool_names.contains(canister.name.as_str()))
        .map(|canister| canister.observed_cycles)
        .collect::<BTreeSet<_>>();
    assert_eq!(
        retained_assets,
        BTreeSet::from([4_800_000_000_000, 5_000_000_000_000])
    );

    let production_paths = EnsurePaths::under(
        &root,
        &production_recovery_desired.environment,
        &production_recovery_desired.fleet,
    );
    let mut retained_rejected_plan = production_recovery.plan.clone();
    let retained_store_control = retained_controller_preparation_action(
        &root,
        &production_recovery_desired,
        &state,
        &retained_rejected_plan.operation_id,
    );
    let EnsureAction::FleetProtocol {
        action: retained_store_control_request,
        ..
    } = &retained_store_control
    else {
        unreachable!("retained Store controller action is typed protocol");
    };
    let CurrentFleetProtocolAction::AdoptStore { request } =
        retained_store_control_request.as_ref()
    else {
        unreachable!("retained Store controller action is adoption");
    };
    assert!(
        crate::fleet_ensure::ops::current_protocol::retained_store_control_request_is_exact(
            &root,
            &production_recovery_desired,
            &retained_rejected_plan.operation_id,
            &state,
            "root-0",
            request,
        )
        .expect("validate retained Store controller request")
    );
    let mut wrong_operation_request = request.clone();
    wrong_operation_request.operation_id[0] ^= 1;
    assert!(
        !crate::fleet_ensure::ops::current_protocol::retained_store_control_request_is_exact(
            &root,
            &production_recovery_desired,
            &retained_rejected_plan.operation_id,
            &state,
            "root-0",
            &wrong_operation_request,
        )
        .expect("reject wrong retained operation")
    );
    let mut wrong_store_request = request.clone();
    wrong_store_request.authority.wasm_store = Principal::anonymous();
    assert!(
        !crate::fleet_ensure::ops::current_protocol::retained_store_control_request_is_exact(
            &root,
            &production_recovery_desired,
            &retained_rejected_plan.operation_id,
            &state,
            "root-0",
            &wrong_store_request,
        )
        .expect("reject wrong retained Store")
    );
    assert!(
        !crate::fleet_ensure::ops::current_protocol::retained_store_control_request_is_exact(
            &root,
            &production_recovery_desired,
            &retained_rejected_plan.operation_id,
            &state,
            "missing-root",
            request,
        )
        .expect("reject wrong retained Root")
    );
    retained_rejected_plan
        .protocol_actions
        .push(retained_store_control.clone());
    retained_rejected_plan.plan_sha256 =
        crate::fleet_ensure::policy::expected_plan_sha256(&retained_rejected_plan);
    let retained_action_hashes = workflow::ordered_actions(&retained_rejected_plan)
        .into_iter()
        .map(action_sha256)
        .collect::<Vec<_>>();
    let coordinator_install = workflow::ordered_actions(&retained_rejected_plan)
        .into_iter()
        .next()
        .expect("retained Coordinator reinstall");
    assert!(matches!(
        coordinator_install,
        EnsureAction::Install {
            canic_init: Some(DesiredCanisterInit::Coordinator),
            ..
        }
    ));
    assert_eq!(
        workflow::ordered_actions(&retained_rejected_plan)
            .get(1)
            .copied(),
        Some(&retained_store_control)
    );
    write_plan(&production_paths, &retained_rejected_plan)
        .expect("write retained rejected plan bytes");
    write_journal(
        &production_paths,
        &FleetEnsureJournalRecord {
            completion: FleetEnsureCompletion::InProgress,
            effects: vec![
                EffectRecord {
                    action_sha256: action_sha256(coordinator_install),
                    created_principal: None,
                    destination_post_cycles: None,
                    destination_pre_cycles: None,
                    post_cycles: Some(270_000_000_000_000),
                    pre_cycles: Some(270_000_000_000_000),
                    pre_canister_version: Some(0),
                    progress_identity: Some("install:coordinator:version:1".to_string()),
                    receipt: None,
                    state: EffectState::Applied,
                },
                EffectRecord {
                    action_sha256: action_sha256(&retained_store_control),
                    created_principal: None,
                    destination_post_cycles: None,
                    destination_pre_cycles: None,
                    post_cycles: None,
                    pre_cycles: Some(30_000_000_000_000),
                    pre_canister_version: Some(1),
                    progress_identity: None,
                    receipt: None,
                    state: EffectState::Intent,
                },
            ],
            fleet: retained_rejected_plan.fleet.clone(),
            initial_controlled_cycles: retained_rejected_plan
                .conservation
                .observed_controlled_cycles,
            initial_operator_cycles: 500_000_000_000_000,
            operation_id: retained_rejected_plan.operation_id.clone(),
            plan_sha256: retained_rejected_plan.plan_sha256.clone(),
            schema_version: crate::fleet_ensure::model::FLEET_ENSURE_SCHEMA_VERSION,
            stalled_observations: 1,
        },
    )
    .expect("write retained rejected journal bytes");
    fs::write(root.join("root-status-count"), b"1\n").expect("select retained typed E132 status");
    let replan_error = workflow::apply(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        &retained_rejected_plan.plan_sha256,
        &mut production_platform,
    )
    .expect_err("predecessor Store adoption closes only at replan boundary");
    assert!(
        matches!(
            &replan_error,
            workflow::EnsureWorkflowError::ReplanRequiredAfterRejectedPrerequisite { .. }
        ),
        "unexpected retained rejection result: {replan_error:?}"
    );
    let rejected_journal = read_journal(&production_paths)
        .expect("read rejected journal")
        .expect("retained rejected journal");
    assert_eq!(
        rejected_journal.completion,
        FleetEnsureCompletion::ReplanRequired
    );
    assert_eq!(
        rejected_journal
            .effects
            .iter()
            .map(|effect| effect.action_sha256.clone())
            .collect::<Vec<_>>(),
        retained_action_hashes[..2]
    );
    assert_eq!(rejected_journal.effects[0].state, EffectState::Applied);
    assert_eq!(rejected_journal.effects[1].state, EffectState::Intent);
    assert!(rejected_journal.effects[1].receipt.is_none());
    let rejected_state = read_state(&production_paths, &production_recovery_desired.fleet)
        .expect("read exact rejected state");
    assert_eq!(
        rejected_state.completed_reinstalls,
        BTreeMap::from([("coordinator".to_string(), 0)])
    );
    assert!(!rejected_state.completed_reinstalls.contains_key("root-0"));
    assert!(!rejected_state.completed_reinstalls.contains_key("store-0"));

    let retained_replan_files = [
        fs::read(&production_paths.state).expect("read retained replan state"),
        fs::read(&production_paths.plan).expect("read retained replan plan"),
        fs::read(&production_paths.journal).expect("read retained replan journal"),
    ];
    let alternate_source_digest = "fe".repeat(32);
    let alternate_error = workflow::plan(
        &root,
        &production_recovery_desired,
        &alternate_source_digest,
        &production_recovery_desired.fleet,
        1_800_000_000_000_000_100,
        &mut production_platform,
    )
    .expect_err("alternate desired input cannot clear completed reinstall evidence");
    assert!(matches!(
        alternate_error,
        workflow::EnsureWorkflowError::RetainedReinstallDesiredConflict {
            actual,
            expected,
        } if actual == alternate_source_digest && expected == source_digest
    ));
    assert_eq!(
        [
            fs::read(&production_paths.state).expect("reread retained replan state"),
            fs::read(&production_paths.plan).expect("reread retained replan plan"),
            fs::read(&production_paths.journal).expect("reread retained replan journal"),
        ],
        retained_replan_files,
        "rejected read-only planning must leave every retained authority byte unchanged"
    );
    assert_eq!(
        read_state(&production_paths, &production_recovery_desired.fleet)
            .expect("reread exact rejected state"),
        rejected_state,
    );

    fs::write(root.join("root-status-count"), b"1\n")
        .expect("retain typed predecessor Root status for fresh planning");
    let fresh_replan = workflow::plan(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        1_800_000_000_000_000_101,
        &mut production_platform,
    )
    .expect("fresh plan preserves only the proved Coordinator reinstall");
    let fresh_actions = workflow::ordered_actions(&fresh_replan.plan);
    assert!(fresh_replan.plan.protocol_actions.is_empty());
    assert!(fresh_actions.iter().all(|action| {
        !matches!(
            action,
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Coordinator),
                ..
            }
        )
    }));
    assert!(matches!(
        fresh_actions.as_slice(),
        [
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Store { .. }),
                ..
            },
            EnsureAction::Install {
                canic_init: Some(DesiredCanisterInit::Root { .. }),
                ..
            }
        ]
    ));
    assert_eq!(fresh_replan.plan.conservation.maximum_new_funding_cycles, 0);
    assert_eq!(
        fresh_replan.plan.conservation.maximum_operator_debit_cycles,
        0
    );

    let mut exact_replan_platform =
        RetainedEnsurePlatform::new(&production_recovery_desired, &observed, &pool_one)
            .with_successor_store_adoption(&root);
    for configured in &production_recovery_desired.canisters {
        let principal = configured
            .principal
            .as_deref()
            .expect("retained exact Principal");
        let live = exact_replan_platform
            .live
            .get_mut(principal)
            .expect("retained exact live canister");
        match configured.kind {
            DesiredCanisterKind::Coordinator => {
                live.module_sha256 = Some(coordinator_hash.clone());
            }
            DesiredCanisterKind::Root => {
                live.module_sha256 = Some(predecessor_root_hash.clone());
                live.reinstall_required = true;
            }
            DesiredCanisterKind::Store => {
                live.controllers = vec![fleet_root.clone(), operator.clone()];
                live.controllers.sort();
                live.module_sha256 = Some(predecessor_store_hash.clone());
                live.reinstall_required = true;
            }
            DesiredCanisterKind::Auxiliary
            | DesiredCanisterKind::Pool
            | DesiredCanisterKind::Component => {}
        }
    }
    let initial_exact_cycles = exact_replan_platform.total_cycles();
    let exact_replan_error = workflow::apply(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        &fresh_replan.plan.plan_sha256,
        &mut exact_replan_platform,
    )
    .expect_err("successor Store adoption requires one newly reviewed plan");
    assert!(matches!(
        exact_replan_error,
        workflow::EnsureWorkflowError::ConvergenceDrift
    ));
    assert_eq!(exact_replan_platform.mutations, 2);
    assert_eq!(exact_replan_platform.total_cycles(), initial_exact_cycles);
    let exact_reinstall_journal = read_journal(&production_paths)
        .expect("read exact reinstall journal")
        .expect("exact reinstall journal");
    assert_eq!(
        exact_reinstall_journal.completion,
        FleetEnsureCompletion::ReplanRequired
    );
    assert_eq!(exact_reinstall_journal.effects.len(), 2);
    assert!(
        exact_reinstall_journal
            .effects
            .iter()
            .all(|effect| effect.state == EffectState::Applied)
    );

    let mut successor_platform = exact_replan_platform.fresh_process();
    let successor_plan = workflow::plan(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        1_800_000_000_000_000_102,
        &mut successor_platform,
    )
    .expect("plan successor-only Store adoption after exact reinstalls");
    assert!(
        successor_plan
            .plan
            .canisters
            .iter()
            .all(|canister| canister.actions.is_empty())
    );
    assert!(matches!(
        successor_plan.plan.protocol_actions.as_slice(),
        [EnsureAction::FleetProtocol { action, name, principal, .. }]
            if matches!(
                action.as_ref(),
                CurrentFleetProtocolAction::AdoptStore { .. }
            ) && name == "root-store-adoption:root-0"
                && principal == &fleet_root
    ));
    assert_eq!(
        successor_plan.plan.conservation.maximum_new_funding_cycles,
        0
    );
    assert_eq!(
        successor_plan
            .plan
            .conservation
            .maximum_operator_debit_cycles,
        0
    );
    let successor_applied = workflow::apply(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        &successor_plan.plan.plan_sha256,
        &mut successor_platform,
    )
    .expect("successor Root accepts exact Store authority");
    assert!(successor_applied.terminal);
    assert_eq!(successor_platform.mutations, 1);
    assert_eq!(successor_platform.total_cycles(), initial_exact_cycles);
    let exact_replay_plan = workflow::plan(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        1_800_000_000_000_000_103,
        &mut successor_platform,
    )
    .expect("plan exact terminal replay");
    assert!(workflow::ordered_actions(&exact_replay_plan.plan).is_empty());
    let exact_replay = workflow::apply(
        &root,
        &production_recovery_desired,
        &source_digest,
        &production_recovery_desired.fleet,
        &exact_replay_plan.plan.plan_sha256,
        &mut successor_platform,
    )
    .expect("exact terminal replay is effect-free");
    assert!(exact_replay.terminal);
    assert_eq!(exact_replay.effects_applied, 0);
    assert_eq!(successor_platform.mutations, 1);
    assert_eq!(successor_platform.total_cycles(), initial_exact_cycles);

    write_state(&production_paths, &state).expect("restore pre-replan retained state");
    write_plan(&production_paths, &retained_rejected_plan)
        .expect("restore pre-replan retained plan");
    let mut wrong_controller_journal = rejected_journal;
    wrong_controller_journal.completion = FleetEnsureCompletion::InProgress;
    wrong_controller_journal.effects[1].post_cycles = None;
    wrong_controller_journal.effects[1].progress_identity = None;
    wrong_controller_journal.stalled_observations = 1;
    write_journal(&production_paths, &wrong_controller_journal)
        .expect("restore pre-replan retained journal");
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &predecessor_root_hash,
            root_runtime_status: "running",
            root_status_error: Some(canic_core::diagnostics::codes::STATE_CONFLICT),
            store: &store,
            store_has_root_controller: false,
            store_module_hash: &predecessor_store_hash,
        },
    );
    fs::write(root.join("root-status-count"), b"1\n")
        .expect("select wrong-controller typed E132 status");
    let mut wrong_controller_platform = IcpEnsurePlatform::new(
        production_recovery_desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    assert!(matches!(
        workflow::apply(
            &root,
            &production_recovery_desired,
            &source_digest,
            &production_recovery_desired.fleet,
            &retained_rejected_plan.plan_sha256,
            &mut wrong_controller_platform,
        ),
        Err(workflow::EnsureWorkflowError::Platform(
            IcpEnsurePlatformError::CurrentProtocol(_)
        ))
    ));
    let wrong_controller_retained = read_journal(&production_paths)
        .expect("read wrong-controller journal")
        .expect("wrong-controller journal retained");
    assert_eq!(
        wrong_controller_retained.completion,
        FleetEnsureCompletion::InProgress
    );
    assert_eq!(
        wrong_controller_retained.effects[0].state,
        EffectState::Applied
    );
    assert_eq!(
        wrong_controller_retained.effects[1].state,
        EffectState::Intent
    );
    assert!(wrong_controller_retained.effects[1].receipt.is_none());

    let successor_release =
        plan_release_build_for_profile(&root, crate::build_profile::CanisterBuildProfile::Fast)
            .expect("plan distinct requested successor release");
    let successor_release_build_id = successor_release.record.release_build_id;
    assert_ne!(successor_release_build_id, release_build_id);
    persist_test_release_authority(&root, &config, successor_release_build_id);
    let successor_manifest =
        crate::release_set::load_persisted_canic_infrastructure_artifact_manifest(
            &root,
            successor_release_build_id,
        )
        .expect("load requested successor infrastructure manifest");
    let requested_successor_root_hash = successor_manifest
        .manifest
        .entries
        .iter()
        .find(|entry| entry.role == CanicInfrastructureRole::FleetSubnetRoot)
        .expect("requested successor Root artifact")
        .wasm_sha256_hex
        .clone();

    let mut stopped_desired = recovery_desired.clone();
    stopped_desired.fleet = "retained-stopped-root".to_string();
    let stopped_artifacts =
        crate::fleet_ensure::ops::resolve_desired_artifacts(&root, &stopped_desired)
            .expect("resolve retained desired artifacts");
    let retained_desired_root_hash = stopped_artifacts
        .wasm_sha256_by_canister
        .get("root-0")
        .expect("retained desired Root artifact hash");
    let stopped_root_hash = sha256_hex(b"retained predecessor Root");
    assert_ne!(&stopped_root_hash, retained_desired_root_hash);
    assert_ne!(&stopped_root_hash, &requested_successor_root_hash);
    assert_ne!(retained_desired_root_hash, &requested_successor_root_hash);
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &stopped_root_hash,
            root_runtime_status: "stopped",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    let root_status_counter = root.join("root-status-count");
    if root_status_counter.exists() {
        fs::remove_file(&root_status_counter).expect("reset Root query counter");
    }
    let configured_root = stopped_desired
        .canisters
        .iter()
        .find(|canister| canister.kind == DesiredCanisterKind::Root)
        .expect("configured retained Root");
    let stopped_request = FleetGenerateRequest {
        app_config: &app_config,
        environment: &stopped_desired.environment,
        fleet: &stopped_desired.fleet,
        icp_executable: icp.to_str().expect("fake ICP path"),
        release_build_id: successor_release_build_id,
        root: &root,
        seed: &seed_path,
        source: &source_path,
    };
    let Err(stopped_error) = generate_desired_fleet(&stopped_request) else {
        panic!("stopped predecessor Root requires one retained Start prerequisite");
    };
    assert!(matches!(
        stopped_error,
        FleetGenerateError::StoppedRootStartRequired(details)
            if details.module_sha256 == stopped_root_hash
                && details.successor_module_sha256 == requested_successor_root_hash
    ));
    let stopped_paths =
        EnsurePaths::under(&root, &stopped_desired.environment, &stopped_desired.fleet);
    let stopped_authority = read_root_start_authority(&stopped_paths)
        .expect("read retained Root-start authority")
        .expect("generator retained Root-start authority");
    assert_eq!(
        stopped_authority.release_build_id,
        successor_release_build_id
    );
    assert_eq!(
        stopped_authority.successor_module_sha256,
        requested_successor_root_hash
    );
    crate::fleet_ensure::ops::verify_root_start_release_authority(&root, &stopped_authority)
        .expect("sealed authority resolves its exact finalized successor");
    let mut wrong_release_authority = stopped_authority.clone();
    wrong_release_authority.release_build_id = release_build_id;
    wrong_release_authority.seal();
    assert!(matches!(
        crate::fleet_ensure::ops::verify_root_start_release_authority(
            &root,
            &wrong_release_authority,
        ),
        Err(crate::fleet_ensure::ops::EnsureStateError::InvalidRootStartReleaseAuthority { .. })
    ));
    let mut wrong_successor_authority = stopped_authority.clone();
    wrong_successor_authority.successor_module_sha256 = "00".repeat(32);
    wrong_successor_authority.seal();
    assert!(matches!(
        crate::fleet_ensure::ops::verify_root_start_release_authority(
            &root,
            &wrong_successor_authority,
        ),
        Err(crate::fleet_ensure::ops::EnsureStateError::InvalidRootStartReleaseAuthority { .. })
    ));
    let successor_root_entry = successor_manifest
        .manifest
        .entries
        .iter()
        .find(|entry| entry.role == CanicInfrastructureRole::FleetSubnetRoot)
        .expect("requested successor Root entry");
    let successor_root_path = root.join(&successor_root_entry.wasm_relative_path);
    let successor_root_bytes = fs::read(&successor_root_path).expect("read successor Root bytes");
    fs::write(&successor_root_path, b"changed successor Root").expect("tamper successor Root");
    assert!(matches!(
        crate::fleet_ensure::ops::verify_root_start_release_authority(&root, &stopped_authority,),
        Err(crate::fleet_ensure::ops::EnsureStateError::InvalidRootStartReleaseAuthority { .. })
    ));
    fs::write(&successor_root_path, successor_root_bytes).expect("restore successor Root bytes");
    let retained_authority_bytes = fs::read(&stopped_paths.root_start_authority)
        .expect("read exact retained Root-start authority bytes");
    let mut tampered_authority = stopped_authority.clone();
    tampered_authority.successor_module_sha256 = "00".repeat(32);
    fs::write(
        &stopped_paths.root_start_authority,
        serde_json::to_vec_pretty(&tampered_authority).expect("encode tampered authority"),
    )
    .expect("write tampered authority fixture");
    assert!(matches!(
        read_root_start_authority(&stopped_paths),
        Err(crate::fleet_ensure::ops::EnsureStateError::InvalidRootStartAuthority { .. })
    ));
    fs::write(
        &stopped_paths.root_start_authority,
        &retained_authority_bytes,
    )
    .expect("restore retained Root-start authority bytes");
    let later_release =
        plan_release_build_for_profile(&root, crate::build_profile::CanisterBuildProfile::Debug)
            .expect("plan later requested release");
    let later_release_build_id = later_release.record.release_build_id;
    assert_ne!(later_release_build_id, successor_release_build_id);
    persist_test_release_authority(&root, &config, later_release_build_id);
    let later_manifest = crate::release_set::load_persisted_canic_infrastructure_artifact_manifest(
        &root,
        later_release_build_id,
    )
    .expect("load later requested infrastructure manifest");
    let later_root_hash = later_manifest
        .manifest
        .entries
        .iter()
        .find(|entry| entry.role == CanicInfrastructureRole::FleetSubnetRoot)
        .expect("later requested Root artifact")
        .wasm_sha256_hex
        .clone();
    assert_ne!(later_root_hash, requested_successor_root_hash);
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &stopped_root_hash,
            root_runtime_status: "running",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    let later_request = FleetGenerateRequest {
        app_config: &app_config,
        environment: &stopped_desired.environment,
        fleet: &stopped_desired.fleet,
        icp_executable: icp.to_str().expect("fake ICP path"),
        release_build_id: later_release_build_id,
        root: &root,
        seed: &seed_path,
        source: &source_path,
    };
    let Err(later_error) = generate_desired_fleet(&later_request) else {
        panic!("a later successor cannot retarget the sealed predecessor authority");
    };
    let later_message = later_error.to_string();
    assert!(
        matches!(
        &later_error,
        FleetGenerateError::SealedSuccessorConvergenceRequired(details)
            if details.fleet == stopped_desired.fleet
                && details.sealed_release_build_id == successor_release_build_id.to_string()
                && details.sealed_successor_module_sha256 == requested_successor_root_hash
                && details.requested_release_build_id == later_release_build_id.to_string()
                && details.requested_successor_module_sha256 == later_root_hash
        ),
        "unexpected later-successor result: {later_error:?}"
    );
    assert!(later_message.contains("canic fleet ensure retained-stopped-root"));
    assert!(later_message.contains("terminally converge the retained desired successor"));
    assert_eq!(
        fs::read(&stopped_paths.root_start_authority)
            .expect("read unchanged sealed Root-start authority"),
        retained_authority_bytes
    );
    assert!(
        !root_status_counter.exists(),
        "later generation must reject before a protected predecessor query"
    );
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &stopped_root_hash,
            root_runtime_status: "stopped",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    let root_management = RootManagementObservation {
        operator_cycles: 500_000_000_000_000,
        roots: BTreeMap::from([(
            configured_root.name.clone(),
            RootManagementCanisterObservation {
                live: LiveCanister {
                    canister_version: Some(7),
                    controllers: configured_root.controllers.clone(),
                    cycles: 30_000_000_000_000,
                    module_sha256: Some(stopped_root_hash.clone()),
                    principal: fleet_root.clone(),
                    reinstall_required: false,
                    root_owned_lifecycle: None,
                    status: CanisterRuntimeStatus::Stopped,
                },
                name: configured_root.name.clone(),
                subnet: configured_root.subnet.clone(),
            },
        )]),
    };
    assert!(matches!(
        crate::fleet_ensure::policy::compile_root_start_prerequisite_plan(
            crate::fleet_ensure::policy::RootStartPlanInput {
                authority: None,
                created_at_time: 1_800_000_000_000_000_150,
                desired: &stopped_desired,
                desired_sha256: &source_digest,
                observation: &root_management,
                requested_fleet: &stopped_desired.fleet,
            },
        ),
        Err(
            crate::fleet_ensure::policy::EnsurePolicyError::RootManagementAuthorityMismatch {
                field: "retained module authority",
                ..
            }
        )
    ));
    let mut wrong_authority = stopped_authority.clone();
    wrong_authority.fleet = "other-fleet".to_string();
    wrong_authority.seal();
    assert!(matches!(
        crate::fleet_ensure::policy::compile_root_start_prerequisite_plan(
            crate::fleet_ensure::policy::RootStartPlanInput {
                authority: Some(&wrong_authority),
                created_at_time: 1_800_000_000_000_000_150,
                desired: &stopped_desired,
                desired_sha256: &source_digest,
                observation: &root_management,
                requested_fleet: &stopped_desired.fleet,
            },
        ),
        Err(
            crate::fleet_ensure::policy::EnsurePolicyError::RootManagementAuthorityMismatch {
                field: "retained module authority",
                ..
            }
        )
    ));
    let mut wrong_fleet_identity = stopped_authority.clone();
    wrong_fleet_identity.fleet_id = "ff".repeat(32).parse().expect("wrong Fleet ID");
    wrong_fleet_identity.seal();
    assert!(matches!(
        crate::fleet_ensure::policy::compile_root_start_prerequisite_plan(
            crate::fleet_ensure::policy::RootStartPlanInput {
                authority: Some(&wrong_fleet_identity),
                created_at_time: 1_800_000_000_000_000_150,
                desired: &stopped_desired,
                desired_sha256: &source_digest,
                observation: &root_management,
                requested_fleet: &stopped_desired.fleet,
            },
        ),
        Err(
            crate::fleet_ensure::policy::EnsurePolicyError::RootManagementAuthorityMismatch {
                field: "retained module authority",
                ..
            }
        )
    ));
    crate::fleet_ensure::policy::compile_root_start_prerequisite_plan(
        crate::fleet_ensure::policy::RootStartPlanInput {
            authority: Some(&stopped_authority),
            created_at_time: 1_800_000_000_000_000_150,
            desired: &stopped_desired,
            desired_sha256: &source_digest,
            observation: &root_management,
            requested_fleet: &stopped_desired.fleet,
        },
    )
    .expect("exact Root management authority")
    .expect("stopped Root prerequisite");
    for (field, drift) in [
        ("Principal", "principal"),
        ("Subnet", "subnet"),
        ("controllers", "controller"),
        ("module SHA-256", "module"),
        ("runtime", "runtime"),
    ] {
        let mut drifted = root_management.clone();
        let observed = drifted
            .roots
            .get_mut(&configured_root.name)
            .expect("drifted Root observation");
        match drift {
            "principal" => observed.live.principal = principal_text(98),
            "subnet" => observed.subnet = principal_text(97),
            "controller" => observed.live.controllers = vec![principal_text(96)],
            "module" => observed.live.module_sha256 = Some("00".repeat(32)),
            "runtime" => observed.live.status = CanisterRuntimeStatus::Stopping,
            _ => unreachable!(),
        }
        let error = crate::fleet_ensure::policy::compile_root_start_prerequisite_plan(
            crate::fleet_ensure::policy::RootStartPlanInput {
                authority: Some(&stopped_authority),
                created_at_time: 1_800_000_000_000_000_150,
                desired: &stopped_desired,
                desired_sha256: &source_digest,
                observation: &drifted,
                requested_fleet: &stopped_desired.fleet,
            },
        )
        .expect_err("drifted Root authority must fail before planning");
        assert!(
            matches!(
                (&error, drift),
                (
                    crate::fleet_ensure::policy::EnsurePolicyError::RootManagementAuthorityMismatch { .. },
                    "principal" | "subnet" | "controller" | "module"
                ) | (
                    crate::fleet_ensure::policy::EnsurePolicyError::RootStopping { .. },
                    "runtime"
                )
            ),
            "unexpected {field} drift error: {error:?}"
        );
    }
    let retained_release_manifest_path = root
        .join(".canic/release-builds")
        .join(release_build_id.to_string())
        .join("current-release-set-manifest.json");
    let retained_release_manifest_bytes = fs::read(&retained_release_manifest_path)
        .expect("read retained desired release manifest bytes");
    fs::write(
        &retained_release_manifest_path,
        b"{\"schema_version\":1,\"historical\":true}",
    )
    .expect("replace retained desired release manifest with unsupported historical bytes");
    let retained_root_artifact_path = root.join(
        configured_root
            .wasm
            .as_deref()
            .expect("retained desired Root Wasm path"),
    );
    let retained_root_artifact_bytes =
        fs::read(&retained_root_artifact_path).expect("read retained desired Root artifact");
    fs::remove_file(&retained_root_artifact_path)
        .expect("remove disposable retained desired Root artifact");
    write_state(
        &stopped_paths,
        &FleetEnsureStateRecord {
            active_registry: None,
            completed_reinstall_action_sha256: BTreeMap::new(),
            completed_reinstall_operation_id: None,
            completed_reinstalls: BTreeMap::new(),
            fleet: stopped_desired.fleet.clone(),
            pending_principals: BTreeMap::new(),
            principals: BTreeMap::new(),
            retained_cycles_by_principal: observed
                .iter()
                .map(|(principal, canister)| (principal.clone(), canister.cycles))
                .collect(),
            schema_version: crate::fleet_ensure::model::FLEET_ENSURE_SCHEMA_VERSION,
            topology: BTreeMap::new(),
        },
    )
    .expect("retain real schema-1 state without synthesized topology");
    let mut stopped_platform = IcpEnsurePlatform::new(
        stopped_desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let stopped_plan = workflow::plan(
        &root,
        &stopped_desired,
        &source_digest,
        &stopped_desired.fleet,
        1_800_000_000_000_000_150,
        &mut stopped_platform,
    )
    .expect("plan exact stopped Root before protected role observation");
    let stopped_actions = workflow::ordered_actions(&stopped_plan.plan);
    assert!(matches!(
        stopped_actions.as_slice(),
        [EnsureAction::Start { name, principal }]
            if name == "root-0" && principal == &fleet_root
    ));
    assert!(
        !root_status_counter.exists(),
        "planning must not query a stopped Root role endpoint"
    );
    assert_eq!(stopped_plan.plan.conservation.maximum_new_funding_cycles, 0);
    assert_eq!(
        stopped_plan.plan.conservation.maximum_operator_debit_cycles,
        0
    );
    assert_eq!(
        stopped_plan.plan.scope,
        crate::fleet_ensure::model::FleetEnsurePlanScope::RootStartPrerequisite
    );
    assert_eq!(
        stopped_plan.plan.root_start_authority.as_deref(),
        Some(&stopped_authority)
    );
    let reviewed_plan_sha256 = stopped_plan.plan.plan_sha256.clone();
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &"00".repeat(32),
            root_runtime_status: "stopped",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    assert!(
        workflow::apply(
            &root,
            &stopped_desired,
            &source_digest,
            &stopped_desired.fleet,
            &reviewed_plan_sha256,
            &mut stopped_platform,
        )
        .is_err()
    );
    assert!(
        !root.join("root-start-count").exists(),
        "pre-effect predecessor drift must reject before Start"
    );
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &stopped_root_hash,
            root_runtime_status: "stopped",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    let applied = workflow::apply(
        &root,
        &stopped_desired,
        &source_digest,
        &stopped_desired.fleet,
        &reviewed_plan_sha256,
        &mut stopped_platform,
    )
    .expect("apply only the reviewed same-ID Root Start");
    assert!(applied.terminal);
    assert_eq!(applied.effects_applied, 1);
    assert_eq!(
        applied
            .actual_conservation
            .expect("Root-start conservation")
            .operator_debit_cycles,
        0
    );
    assert_eq!(
        fs::read_to_string(root.join("root-start-count")).expect("Root start count"),
        "1\n"
    );
    assert!(
        !root_status_counter.exists(),
        "applying the prerequisite must not query a protected Root endpoint"
    );
    let replay = workflow::apply(
        &root,
        &stopped_desired,
        &source_digest,
        &stopped_desired.fleet,
        &reviewed_plan_sha256,
        &mut stopped_platform,
    )
    .expect("terminal Root-start replay is effect-free");
    assert!(replay.terminal);
    assert_eq!(replay.effects_applied, 1);
    assert_eq!(
        fs::read_to_string(root.join("root-start-count")).expect("replayed Root start count"),
        "1\n"
    );
    let retained_after_start = read_state(&stopped_paths, &stopped_desired.fleet)
        .expect("read state after Root-start prerequisite");
    assert!(retained_after_start.principals.is_empty());
    assert!(retained_after_start.topology.is_empty());

    fs::remove_file(&stopped_paths.root_start_authority)
        .expect("remove disposable bridge authority");
    fs::write(
        root.join("predecessor-pool-status"),
        b"exact predecessor shape\n",
    )
    .expect("select predecessor response without authority");
    assert!(matches!(
        generate_desired_fleet(&stopped_request),
        Err(FleetGenerateError::CanisterUnavailable { .. })
    ));
    fs::write(
        &stopped_paths.root_start_authority,
        &retained_authority_bytes,
    )
    .expect("restore exact bridge authority");
    fs::remove_file(&root_status_counter).expect("reset Root status fixture");

    let mut wrong_bridge_successor = stopped_authority;
    wrong_bridge_successor.successor_module_sha256 = "00".repeat(32);
    wrong_bridge_successor.seal();
    fs::write(
        &stopped_paths.root_start_authority,
        serde_json::to_vec_pretty(&wrong_bridge_successor).expect("encode wrong bridge authority"),
    )
    .expect("write wrong bridge authority");
    assert!(matches!(
        generate_desired_fleet(&stopped_request),
        Err(FleetGenerateError::Authority(_))
    ));
    fs::write(
        &stopped_paths.root_start_authority,
        &retained_authority_bytes,
    )
    .expect("restore exact bridge authority");

    let unrelated_running_module = "11".repeat(32);
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &unrelated_running_module,
            root_runtime_status: "running",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    if root_status_counter.exists() {
        fs::remove_file(&root_status_counter).expect("reset exact bridge status fixture");
    }
    fs::write(
        root.join("predecessor-pool-status"),
        b"exact predecessor shape\n",
    )
    .expect("select predecessor response for unrelated module");
    assert!(matches!(
        generate_desired_fleet(&stopped_request),
        Err(FleetGenerateError::CanisterUnavailable { .. })
    ));
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &retained_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: &stopped_root_hash,
            root_runtime_status: "running",
            root_status_error: None,
            store: &store,
            store_has_root_controller: true,
            store_module_hash: store_hash,
        },
    );
    if root_status_counter.exists() {
        fs::remove_file(&root_status_counter).expect("reset successful bridge status fixture");
    }
    fs::write(root.join("root-started"), b"running\n")
        .expect("restore terminal Root-start observation");
    fs::write(
        root.join("predecessor-pool-status"),
        b"exact predecessor shape\n",
    )
    .expect("select exact predecessor Root pool response");
    let regenerated = generate_desired_fleet(&stopped_request)
        .expect("bridge exact predecessor status after reviewed Root Start");
    assert_eq!(
        regenerated
            .desired
            .bootstrap
            .as_ref()
            .expect("regenerated bootstrap")
            .release_build_id,
        successor_release_build_id
    );
    assert_eq!(
        fs::read(&preserved_output).expect("read unchanged retained desired authority"),
        b"retained desired authority\n"
    );
    fs::write(
        &retained_release_manifest_path,
        retained_release_manifest_bytes,
    )
    .expect("restore retained desired release manifest for later independent cases");
    fs::write(&retained_root_artifact_path, retained_root_artifact_bytes)
        .expect("restore retained desired Root artifact for later independent cases");
    assert_eq!(regenerated.observed_canisters, 5);
    assert_eq!(regenerated.observed_controlled_cycles, 319_899_950_000_000);
    assert!(root_status_counter.exists());

    let successor_desired_sha256 = sha256_hex(
        &serde_json::to_vec(&regenerated.desired).expect("encode regenerated desired Fleet"),
    );
    let mut successor_platform = IcpEnsurePlatform::new(
        regenerated.desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let successor_plan = workflow::plan(
        &root,
        &regenerated.desired,
        &successor_desired_sha256,
        &regenerated.desired.fleet,
        1_800_000_000_000_000_175,
        &mut successor_platform,
    )
    .expect("review ordinary successor plan through predecessor status bridge");
    let successor_actions = workflow::ordered_actions(&successor_plan.plan);
    assert!(successor_actions.iter().any(|action| {
        matches!(
            action,
            EnsureAction::Install {
                mode: crate::fleet_ensure::model::InstallMode::Reinstall,
                name,
                wasm_sha256,
                ..
            } if name == "root-0" && wasm_sha256 == &requested_successor_root_hash
        )
    }));
    assert!(successor_actions.iter().all(|action| {
        !matches!(
            action,
            EnsureAction::Create { .. }
                | EnsureAction::Delete { .. }
                | EnsureAction::Fund { .. }
                | EnsureAction::Transfer { .. }
        )
    }));
    assert_eq!(
        successor_plan
            .plan
            .conservation
            .maximum_operator_debit_cycles,
        0
    );
    assert_eq!(
        successor_plan.plan.conservation.maximum_new_funding_cycles,
        0
    );
    assert_eq!(
        successor_plan
            .plan
            .conservation
            .maximum_unavoidable_fee_cycles,
        0
    );
    assert_eq!(
        successor_plan.plan.conservation.scheduled_transfer_cycles,
        0
    );

    fs::write(&root_status_counter, b"1\n").expect("prime later pool-only fake query");

    let mut pending_pool = retained_pool;
    let pending = pending_pool
        .entries
        .iter_mut()
        .find(|asset| asset.canister_id.to_text() == pool_two)
        .expect("idle retained pool asset");
    pending.status = CanisterPoolAssetStatus::PendingReset;
    pending.cycles = Cycles::new(0);
    let mut pending_desired = recovery_desired.clone();
    pending_desired.fleet = "retained-multi-component-pending-reset".to_string();
    write_fake_icp(
        &root,
        FakeIcpFixture {
            authority: &retained_authority,
            coordinator: &coordinator,
            coordinator_module_hash: coordinator_hash,
            fleet_root: &fleet_root,
            operator: &operator,
            pool: &pending_pool,
            public_cycle_balance: Some((&pool_one, 4_800_000_000_000)),
            root_module_hash: root_hash,
            root_runtime_status: "running",
            root_status_error: None,
            store: &store,
            store_has_root_controller: false,
            store_module_hash: store_hash,
        },
    );
    write_state(
        &EnsurePaths::under(&root, &pending_desired.environment, &pending_desired.fleet),
        &retained_ensure_state(&pending_desired, &observed, &artifacts),
    )
    .expect("retain exact pre-reset pool balances");
    let mut pending_platform = IcpEnsurePlatform::new(
        pending_desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let pending_plan = workflow::plan(
        &root,
        &pending_desired,
        &source_digest,
        &pending_desired.fleet,
        1_800_000_000_000_000_200,
        &mut pending_platform,
    )
    .expect("plan pending-reset pool from retained exact balance");
    let retained_pending = pending_plan
        .plan
        .canisters
        .iter()
        .find(|canister| canister.principal.as_deref() == Some(pool_two.as_str()))
        .expect("pending retained asset plan");
    assert_eq!(retained_pending.observed_cycles, 5_000_000_000_000);
    assert!(retained_pending.actions.is_empty());
    assert_eq!(pending_plan.plan.conservation.maximum_new_funding_cycles, 0);

    let mut drifted_desired = pending_desired.clone();
    drifted_desired.fleet = "retained-controller-drift".to_string();
    drifted_desired
        .canisters
        .iter_mut()
        .find(|canister| canister.kind == DesiredCanisterKind::Root)
        .expect("desired Root")
        .controllers = vec![principal_text(99)];
    write_state(
        &EnsurePaths::under(&root, &drifted_desired.environment, &drifted_desired.fleet),
        &retained_ensure_state(&drifted_desired, &observed, &artifacts),
    )
    .expect("retain drift-negative evidence");
    let mut drifted_platform = IcpEnsurePlatform::new(
        drifted_desired.clone(),
        icp.to_str().expect("fake ICP path"),
        &root,
    );
    let error = workflow::plan(
        &root,
        &drifted_desired,
        &source_digest,
        &drifted_desired.fleet,
        1_800_000_000_000_000_300,
        &mut drifted_platform,
    )
    .expect_err("Root controller drift must reject retained balance evidence");
    assert!(
        matches!(
            &error,
            workflow::EnsureWorkflowError::Platform(IcpEnsurePlatformError::CurrentProtocol(_))
        ),
        "unexpected controller-drift error: {error:?}"
    );

    let mut platform = RetainedEnsurePlatform::new(&desired, &observed, &pool_one);
    let planned = workflow::plan(
        &root,
        &desired,
        &source_digest,
        &desired.fleet,
        1_800_000_000_000_000_000,
        &mut platform,
    )
    .expect("plan retained estate");
    let applied = workflow::apply(
        &root,
        &desired,
        &source_digest,
        &desired.fleet,
        &planned.plan.plan_sha256,
        &mut platform,
    )
    .expect("apply retained estate");
    assert!(applied.terminal);
    assert!(planned.plan.canisters.iter().all(|canister| {
        canister
            .actions
            .iter()
            .all(|action| !matches!(action, EnsureAction::Create { .. }))
    }));
    assert!(planned.plan.canisters.iter().all(|canister| {
        canister
            .actions
            .iter()
            .all(|action| !matches!(action, EnsureAction::Fund { .. }))
    }));
    assert_eq!(
        platform.mutations, 3,
        "only retained infrastructure reinstalls"
    );
    assert_eq!(platform.total_cycles(), 319_900_000_000_000);

    let second = workflow::plan(
        &root,
        &desired,
        &source_digest,
        &desired.fleet,
        1_800_000_000_000_000_100,
        &mut platform,
    )
    .expect("plan converged retained estate");
    assert!(
        second
            .plan
            .canisters
            .iter()
            .all(|canister| canister.actions.is_empty())
    );
    let replay = workflow::apply(
        &root,
        &desired,
        &source_digest,
        &desired.fleet,
        &second.plan.plan_sha256,
        &mut platform,
    )
    .expect("effect-free replay");
    assert!(replay.terminal);
    assert_eq!(replay.effects_applied, 0);
    assert_eq!(platform.mutations, 3);
    let current =
        crate::fleet_ensure::resolve_current_fleet(&root, &desired.environment, &desired.fleet)
            .expect("resolve terminal retained Fleet");
    let workload = current
        .registry
        .entries
        .iter()
        .find(|entry| entry.pid == pool_one)
        .expect("pool identity becomes terminal workload");
    assert_eq!(workload.role.as_deref(), Some("app"));
    assert!(workload.module_hash.is_some());
    fs::remove_dir_all(root).expect("remove retained journey root");
}

struct RetainedEnsurePlatform {
    desired: DesiredFleet,
    ledger_fee_cycles: u128,
    live: BTreeMap<String, LiveCanister>,
    mutations: u32,
    post_effect_protocol: bool,
    post_effect_protocol_applied: bool,
    successor_store_adoption_root: Option<PathBuf>,
    terminal_observation_protocol: bool,
}

struct VersionlessPlanningPlatform {
    desired: DesiredFleet,
    inner: IcpEnsurePlatform,
}

impl VersionlessPlanningPlatform {
    fn new(inner: IcpEnsurePlatform, desired: DesiredFleet) -> Self {
        Self { desired, inner }
    }
}

impl EnsurePlatform for VersionlessPlanningPlatform {
    type Error = io::Error;

    fn bind_reviewed_desired(&mut self, desired: &DesiredFleet) -> Result<(), Self::Error> {
        self.desired = desired.clone();
        self.inner
            .bind_reviewed_desired(desired)
            .map_err(io::Error::other)
    }

    fn observe_root_management(
        &mut self,
        state: &FleetEnsureStateRecord,
        reviewed_targets: &BTreeSet<String>,
    ) -> Result<Option<RootManagementObservation>, Self::Error> {
        self.inner
            .observe_root_management(state, reviewed_targets)
            .map_err(io::Error::other)
    }

    fn observe(
        &mut self,
        operation_id: &str,
        state: &FleetEnsureStateRecord,
    ) -> Result<FleetObservation, Self::Error> {
        self.inner
            .observe(operation_id, state)
            .map_err(io::Error::other)
    }

    fn protocol_actions(
        &mut self,
        operation_id: &str,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Vec<EnsureAction>, Self::Error> {
        Ok(
            terminal_observation_protocol_actions(&self.desired, operation_id)
                .into_iter()
                .take(1)
                .collect(),
        )
    }

    fn observe_effect(
        &mut self,
        _operation_id: &str,
        _action: &EnsureAction,
        _record: &EffectRecord,
        _state: &FleetEnsureStateRecord,
    ) -> Result<EffectObservation, Self::Error> {
        Err(io::Error::other("planning adapter cannot observe effects"))
    }

    fn action_cycles(
        &mut self,
        _action: &EnsureAction,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Option<u128>, Self::Error> {
        Err(io::Error::other("planning adapter cannot observe effects"))
    }

    fn action_destination_cycles(
        &mut self,
        _action: &EnsureAction,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Option<u128>, Self::Error> {
        Err(io::Error::other("planning adapter cannot observe effects"))
    }

    fn apply(
        &mut self,
        _operation_id: &str,
        _action: &EnsureAction,
        _record: &EffectRecord,
        _state: &FleetEnsureStateRecord,
    ) -> Result<EffectOutcome, Self::Error> {
        Err(io::Error::other("planning adapter cannot apply effects"))
    }
}

impl RetainedEnsurePlatform {
    fn new(
        desired: &DesiredFleet,
        observed: &BTreeMap<String, ObservedCanister>,
        workload: &str,
    ) -> Self {
        let live = desired
            .canisters
            .iter()
            .map(|canister| {
                let principal = canister.principal.clone().expect("retained Principal");
                let observed = observed.get(&principal).expect("retained observation");
                let root_owned_lifecycle = (canister.kind == DesiredCanisterKind::Pool).then_some(
                    if principal == workload {
                        RootOwnedCanisterLifecycle::Workload
                    } else {
                        RootOwnedCanisterLifecycle::Idle
                    },
                );
                let status = if canister.kind == DesiredCanisterKind::Pool {
                    if principal == workload {
                        CanisterRuntimeStatus::Running
                    } else {
                        CanisterRuntimeStatus::Stopped
                    }
                } else {
                    CanisterRuntimeStatus::Running
                };
                (
                    principal.clone(),
                    LiveCanister {
                        canister_version: Some(1),
                        controllers: canister.controllers.clone(),
                        cycles: observed.cycles,
                        module_sha256: canister.wasm.as_ref().map(|_| "00".repeat(32)),
                        principal,
                        reinstall_required: false,
                        root_owned_lifecycle,
                        status,
                    },
                )
            })
            .collect();
        Self {
            desired: desired.clone(),
            ledger_fee_cycles: desired
                .ledger_fee_cycles
                .parse::<Cycles>()
                .map(|cycles| cycles.to_u128())
                .expect("ledger fee"),
            live,
            mutations: 0,
            post_effect_protocol: false,
            post_effect_protocol_applied: false,
            successor_store_adoption_root: None,
            terminal_observation_protocol: false,
        }
    }

    fn fresh_process(&self) -> Self {
        Self {
            desired: self.desired.clone(),
            ledger_fee_cycles: self.ledger_fee_cycles,
            live: self.live.clone(),
            mutations: 0,
            post_effect_protocol: self.post_effect_protocol,
            post_effect_protocol_applied: self.post_effect_protocol_applied,
            successor_store_adoption_root: self.successor_store_adoption_root.clone(),
            terminal_observation_protocol: self.terminal_observation_protocol,
        }
    }

    fn with_post_effect_root_owned_protocol(mut self) -> Self {
        self.post_effect_protocol = true;
        self
    }

    fn with_successor_store_adoption(mut self, root: &Path) -> Self {
        self.post_effect_protocol = true;
        self.successor_store_adoption_root = Some(root.to_path_buf());
        self
    }

    fn with_terminal_observation_protocol(mut self) -> Self {
        self.terminal_observation_protocol = true;
        self
    }

    fn total_cycles(&self) -> u128 {
        self.live.values().map(|canister| canister.cycles).sum()
    }

    fn infrastructure_ready(&self) -> bool {
        self.desired
            .canisters
            .iter()
            .filter(|configured| {
                matches!(
                    configured.kind,
                    DesiredCanisterKind::Coordinator
                        | DesiredCanisterKind::Root
                        | DesiredCanisterKind::Store
                )
            })
            .all(|configured| {
                configured
                    .principal
                    .as_ref()
                    .and_then(|principal| self.live.get(principal))
                    .is_some_and(|live| {
                        !live.reinstall_required && live.status == CanisterRuntimeStatus::Running
                    })
            })
    }

    fn require_exact_root_owned_topology(
        &self,
        state: &FleetEnsureStateRecord,
    ) -> Result<(), io::Error> {
        for configured in self.desired.canisters.iter().filter(|configured| {
            matches!(
                configured.kind,
                DesiredCanisterKind::Store | DesiredCanisterKind::Pool
            )
        }) {
            let principal = configured
                .principal
                .as_ref()
                .expect("retained Root-owned Principal");
            let parent = configured
                .parent
                .as_ref()
                .expect("retained Root-owned parent");
            let parent_principal = self
                .desired
                .canisters
                .iter()
                .find(|candidate| candidate.name == *parent)
                .and_then(|candidate| candidate.principal.as_ref())
                .expect("retained Root Principal");
            let exact = state.principals.get(&configured.name) == Some(principal)
                && state.principals.get(parent) == Some(parent_principal)
                && state
                    .topology
                    .get(&configured.name)
                    .is_some_and(|topology| {
                        topology.kind == configured.kind && topology.parent.as_ref() == Some(parent)
                    });
            if !exact {
                return Err(io::Error::other(format!(
                    "{} has no exact retained topology authority",
                    configured.name
                )));
            }
        }
        Ok(())
    }
}

impl EnsurePlatform for RetainedEnsurePlatform {
    type Error = io::Error;

    fn bind_reviewed_desired(&mut self, desired: &DesiredFleet) -> Result<(), Self::Error> {
        self.desired = desired.clone();
        Ok(())
    }

    fn observe(
        &mut self,
        _operation_id: &str,
        state: &FleetEnsureStateRecord,
    ) -> Result<FleetObservation, Self::Error> {
        if self.post_effect_protocol
            && !self.post_effect_protocol_applied
            && self.infrastructure_ready()
        {
            self.require_exact_root_owned_topology(state)?;
        }
        Ok(FleetObservation {
            additional_controlled_cycles: BTreeMap::new(),
            canisters: self
                .desired
                .canisters
                .iter()
                .map(|canister| {
                    (
                        canister.name.clone(),
                        canister
                            .principal
                            .as_ref()
                            .and_then(|principal| self.live.get(principal).cloned()),
                    )
                })
                .collect(),
            ledger_fee_cycles: self.ledger_fee_cycles,
            operator_cycles: 1_000_000_000_000_000,
            protocol_ready: BTreeMap::new(),
        })
    }

    fn protocol_actions(
        &mut self,
        operation_id: &str,
        state: &FleetEnsureStateRecord,
    ) -> Result<Vec<EnsureAction>, Self::Error> {
        if self.terminal_observation_protocol {
            return Ok(terminal_observation_protocol_actions(
                &self.desired,
                operation_id,
            ));
        }
        if self.post_effect_protocol
            && self.infrastructure_ready()
            && !self.post_effect_protocol_applied
        {
            if let Some(root) = &self.successor_store_adoption_root {
                return Ok(vec![successor_store_adoption_action(
                    root,
                    &self.desired,
                    state,
                    operation_id,
                )]);
            }
            return Ok(
                terminal_observation_protocol_actions(&self.desired, operation_id)
                    .into_iter()
                    .take(1)
                    .collect(),
            );
        }
        Ok(Vec::new())
    }

    fn observe_effect(
        &mut self,
        _operation_id: &str,
        action: &EnsureAction,
        _record: &EffectRecord,
        _state: &FleetEnsureStateRecord,
    ) -> Result<EffectObservation, Self::Error> {
        let applied = match action {
            EnsureAction::Install {
                principal,
                wasm_sha256,
                ..
            } => self.live.get(principal).is_some_and(|canister| {
                !canister.reinstall_required
                    && canister.module_sha256.as_deref() == Some(wasm_sha256)
            }),
            EnsureAction::Start { principal, .. } => self
                .live
                .get(principal)
                .is_some_and(|canister| canister.status == CanisterRuntimeStatus::Running),
            EnsureAction::FleetProtocol { .. } => self.post_effect_protocol_applied,
            _ => return Err(io::Error::other("unexpected retained journey effect")),
        };
        Ok(EffectObservation {
            applied,
            post_cycles: None,
            progress_identity: format!("retained:{}:{applied}", action.name()),
            retry: EffectRetry::None,
        })
    }

    fn terminal_inventory(
        &mut self,
        _operation_id: &str,
        _state: &FleetEnsureStateRecord,
    ) -> Result<crate::fleet_ensure::ops::TerminalFleetInventory, Self::Error> {
        let workload = self
            .live
            .values()
            .find(|canister| {
                canister.root_owned_lifecycle == Some(RootOwnedCanisterLifecycle::Workload)
            })
            .expect("retained workload");
        let configured = self
            .desired
            .canisters
            .iter()
            .find(|canister| canister.principal.as_deref() == Some(&workload.principal))
            .expect("configured workload identity");
        let parent = configured
            .parent
            .as_ref()
            .and_then(|name| {
                self.desired
                    .canisters
                    .iter()
                    .find(|canister| canister.name == *name)
            })
            .and_then(|canister| canister.principal.clone())
            .expect("workload Root");
        Ok(crate::fleet_ensure::ops::TerminalFleetInventory {
            active_registry: None,
            controlled_cycles_by_principal: BTreeMap::from([(
                workload.principal.clone(),
                workload.cycles,
            )]),
            entries: vec![crate::registry::RegistryEntry {
                module_hash: Some("71".repeat(32)),
                parent_pid: Some(parent),
                pid: workload.principal.clone(),
                protocol_binding: Some(crate::protocol_binding::RegistryProtocolBinding {
                    release_identity: "current".to_string(),
                    role: CanisterRole::from("app"),
                    capabilities: BTreeSet::new(),
                    candid_sha256: [72; 32],
                    protocol_profile_digest: ProtocolProfileDigest::from_bytes([73; 32]),
                }),
                role: Some("app".to_string()),
            }],
        })
    }

    fn action_cycles(
        &mut self,
        action: &EnsureAction,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Option<u128>, Self::Error> {
        let (EnsureAction::Install { principal, .. } | EnsureAction::Start { principal, .. }) =
            action
        else {
            return Ok(None);
        };
        Ok(self.live.get(principal).map(|canister| canister.cycles))
    }

    fn action_canister_version(
        &mut self,
        action: &EnsureAction,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Option<u64>, Self::Error> {
        let EnsureAction::Install { principal, .. } = action else {
            return Ok(None);
        };
        Ok(self
            .live
            .get(principal)
            .and_then(|canister| canister.canister_version))
    }

    fn action_destination_cycles(
        &mut self,
        _action: &EnsureAction,
        _state: &FleetEnsureStateRecord,
    ) -> Result<Option<u128>, Self::Error> {
        Ok(None)
    }

    fn apply(
        &mut self,
        _operation_id: &str,
        action: &EnsureAction,
        _record: &EffectRecord,
        _state: &FleetEnsureStateRecord,
    ) -> Result<EffectOutcome, Self::Error> {
        let (post_cycles, receipt) = match action {
            EnsureAction::Install {
                principal,
                wasm_sha256,
                ..
            } => {
                let canister = self
                    .live
                    .get_mut(principal)
                    .ok_or_else(|| io::Error::other("missing retained canister"))?;
                canister.module_sha256 = Some(wasm_sha256.clone());
                canister.reinstall_required = false;
                canister.canister_version = canister.canister_version.map(|version| version + 1);
                (Some(canister.cycles), format!("installed:{principal}"))
            }
            EnsureAction::Start { principal, .. } => {
                let canister = self
                    .live
                    .get_mut(principal)
                    .ok_or_else(|| io::Error::other("missing retained canister"))?;
                canister.status = CanisterRuntimeStatus::Running;
                (Some(canister.cycles), format!("started:{principal}"))
            }
            EnsureAction::FleetProtocol { name, .. } => {
                self.post_effect_protocol_applied = true;
                (None, format!("protocol:{name}"))
            }
            _ => return Err(io::Error::other("unexpected retained journey effect")),
        };
        self.mutations += 1;
        Ok(EffectOutcome {
            created_principal: None,
            post_cycles,
            receipt: Some(receipt),
        })
    }
}

fn terminal_observation_protocol_actions(
    desired: &DesiredFleet,
    operation_id: &str,
) -> Vec<EnsureAction> {
    let bootstrap = desired.bootstrap.as_ref().expect("generated bootstrap");
    let protocol = desired.protocol.as_ref().expect("generated protocol");
    let coordinator = desired
        .canisters
        .iter()
        .find(|canister| canister.kind == DesiredCanisterKind::Coordinator)
        .and_then(|canister| canister.principal.clone())
        .expect("generated Coordinator Principal");
    let store = desired
        .canisters
        .iter()
        .find(|canister| canister.kind == DesiredCanisterKind::Store)
        .and_then(|canister| canister.principal.clone())
        .expect("generated Store Principal");
    let operation_id = canic_core::cdk::utils::hash::decode_hex(operation_id)
        .ok()
        .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
        .expect("Fleet ensure operation ID");
    let fleet = FleetBinding {
        fleet: FleetKey {
            canonical_network_id: bootstrap.canonical_network_id,
            fleet_id: bootstrap.fleet_id,
        },
        app: bootstrap.app.clone(),
    };
    let registry_authority = FleetRegistryAuthority {
        binding: FleetCoordinatorBinding {
            fleet: fleet.clone(),
            coordinator_subnet: bootstrap.coordinator_subnet,
            coordinator: coordinator.parse().expect("Coordinator Principal"),
        },
        epoch: 1,
    };
    vec![
        EnsureAction::FleetProtocol {
            action: Box::new(CurrentFleetProtocolAction::PrepareStoreChunkSet {
                request: TemplateChunkSetPrepareInput {
                    template_id: TemplateId::from("root"),
                    version: TemplateVersion::from("current"),
                    payload_hash: vec![1; 32],
                    payload_size_bytes: 1,
                    chunk_hashes: vec![vec![2; 32]],
                },
            }),
            candid: protocol.store_candid.clone(),
            candid_sha256: "11".repeat(32),
            maximum_execution_burn_cycles: 1,
            name: "store-chunk-preparation".to_string(),
            principal: store,
        },
        EnsureAction::FleetProtocol {
            action: Box::new(CurrentFleetProtocolAction::ProvisionComponents {
                request: FleetComponentProvisioningPrepareRequest {
                    operation_id,
                    plan: FleetComponentProvisioningPlan {
                        fleet,
                        fleet_registry: FleetRegistryVersion {
                            authority: registry_authority,
                            revision: 1,
                            content_hash: [3; 32],
                        },
                        configuration_digest: ComponentDeploymentConfigurationDigest::from_bytes(
                            [4; 32],
                        ),
                        operation: FleetComponentProvisioningOperation::FreshInstall,
                        directory_confirmation_roots: Vec::new(),
                        batches: Vec::new(),
                    },
                },
                plan_hash: [5; 32],
            }),
            candid: protocol.coordinator_candid.clone(),
            candid_sha256: "12".repeat(32),
            maximum_execution_burn_cycles: 1,
            name: "fleet-component-provisioning".to_string(),
            principal: coordinator,
        },
    ]
}

fn retained_controller_preparation_action(
    root: &Path,
    desired: &DesiredFleet,
    state: &FleetEnsureStateRecord,
    operation_id: &str,
) -> EnsureAction {
    let protocol = desired.protocol.as_ref().expect("generated protocol");
    let configured_root = desired
        .canisters
        .iter()
        .find(|canister| canister.kind == DesiredCanisterKind::Root)
        .expect("retained Root");
    let request = crate::fleet_ensure::ops::current_protocol::expected_retained_store_control_request_for_test(
        root,
        desired,
        operation_id,
        state,
        &configured_root.name,
    )
    .expect("compile retained Store controller request")
    .expect("retained Store controller request");
    let subject_text = configured_root
        .principal
        .clone()
        .expect("retained Root Principal");
    let candid_bytes = fs::read(root.join(&protocol.root_candid)).expect("read Root Candid");
    EnsureAction::FleetProtocol {
        action: Box::new(CurrentFleetProtocolAction::AdoptStore { request }),
        candid: protocol.root_candid.clone(),
        candid_sha256: sha256_hex(&candid_bytes),
        maximum_execution_burn_cycles: desired
            .maximum_update_burn_cycles
            .parse::<Cycles>()
            .expect("maximum update burn")
            .to_u128(),
        name: format!("root-store-control:{}", configured_root.name),
        principal: subject_text,
    }
}

fn successor_store_adoption_action(
    root: &Path,
    desired: &DesiredFleet,
    state: &FleetEnsureStateRecord,
    operation_id: &str,
) -> EnsureAction {
    let mut action = retained_controller_preparation_action(root, desired, state, operation_id);
    let EnsureAction::FleetProtocol { name, .. } = &mut action else {
        unreachable!("Store adoption helper always returns one typed protocol action");
    };
    *name = "root-store-adoption:root-0".to_string();
    action
}

fn retained_ensure_state(
    desired: &DesiredFleet,
    observed: &BTreeMap<String, ObservedCanister>,
    artifacts: &crate::fleet_ensure::model::DesiredFleetArtifacts,
) -> FleetEnsureStateRecord {
    FleetEnsureStateRecord {
        active_registry: None,
        completed_reinstall_action_sha256: BTreeMap::new(),
        completed_reinstall_operation_id: None,
        completed_reinstalls: BTreeMap::new(),
        fleet: desired.fleet.clone(),
        pending_principals: BTreeMap::new(),
        principals: desired
            .canisters
            .iter()
            .filter_map(|canister| {
                canister
                    .principal
                    .clone()
                    .map(|principal| (canister.name.clone(), principal))
            })
            .collect(),
        retained_cycles_by_principal: observed
            .iter()
            .map(|(principal, canister)| (principal.clone(), canister.cycles))
            .collect(),
        schema_version: crate::fleet_ensure::model::FLEET_ENSURE_SCHEMA_VERSION,
        topology: desired
            .canisters
            .iter()
            .map(|canister| {
                (
                    canister.name.clone(),
                    crate::fleet_ensure::model::FleetEnsureTopologyRecord {
                        kind: canister.kind,
                        module_hash: artifacts
                            .wasm_sha256_by_canister
                            .get(&canister.name)
                            .cloned(),
                        parent: canister.parent.clone(),
                        protocol_binding: canister.protocol_binding.clone(),
                        role: canister
                            .protocol_binding
                            .as_ref()
                            .map(|binding| binding.role.to_string()),
                    },
                )
            })
            .collect(),
    }
}

fn multi_component_config() -> &'static str {
    r#"
[app]
name = "demo"

[roles.root]
kind = "root"
package = "root"

[roles.app]
kind = "canister"
package = "app"
fleet_admission = true

[component_specs.app]
component_role = "app"
maximum_instances = 1
initial_cycles = "5T"

[component_groups.app.components.app]
component_spec = "app"

[component_group_deployments.app]
component_group = "app"
initial_placements = 1
maximum_placements = 1
placement.maximum_per_root = 1
placement.minimum_distinct_roots = 1
"#
}

fn multi_component_source(
    operator: &str,
    coordinator_subnet: &str,
    placement: &str,
) -> FleetSource {
    FleetSource {
        schema_version: 1,
        funding_profile: FleetFundingProfile::PreviewMultiSubnet,
        operator: operator.to_string(),
        admission: AdmissionSource {
            principals: vec![operator.to_string()],
        },
        coordinator: CoordinatorSource {
            subnet: ExplicitSubnetSource {
                kind: "explicit".to_string(),
                subnet: coordinator_subnet.to_string(),
                acknowledge_fiduciary_cost: false,
            },
            creation_funding: CyclesCreationSource {
                kind: "cycles".to_string(),
                cycles: Cycles::new(270_000_000_000_000),
            },
            root_funding: CoordinatorFundingSource {
                minimum_reserve_cycles: Cycles::new(210_000_000_000_000),
                window_secs: 7_776_000,
                maximum_cycles: Cycles::new(30_000_000_000_000),
                maximum_automatic_grants: 2,
                maximum_automatic_cycles: Cycles::new(60_000_000_000_000),
            },
        },
        fleet_subnet_roots: vec![RootSource {
            placement_subnet: placement.to_string(),
            acknowledge_fiduciary_cost: false,
            component_group_placements: BTreeMap::from([(
                "app".parse().expect("deployment"),
                vec![0],
            )]),
            component_admissions: BTreeMap::from([("app".parse().expect("Component Spec"), 1)]),
            canister_pool: PoolSource {
                minimum_size: 2,
                maximum_size: 2,
                canister_cycles: Cycles::new(5_000_000_000_000),
                imports: Vec::new(),
            },
            root_funding: RootFundingSource {
                request_threshold: Cycles::new(10_000_000_000_000),
                target_balance: Cycles::new(30_000_000_000_000),
                cooldown_secs: 2_592_000,
                window_secs: 7_776_000,
                maximum_cycles: Cycles::new(30_000_000_000_000),
                maximum_automatic_grants: 2,
                maximum_automatic_cycles: Cycles::new(60_000_000_000_000),
            },
            limits: LimitsSource {
                maximum_component_instances: 1,
                maximum_registry_bytes: 16_777_216,
                maximum_wasm_store_bytes: 40_000_000,
                maximum_group_placements: 1,
                cycles_funding: CyclesFundingSource {
                    window_secs: 3_600,
                    maximum_cycles: Cycles::new(15_000_000_000_000),
                },
            },
            root_creation_funding: CyclesCreationSource {
                kind: "cycles".to_string(),
                cycles: Cycles::new(30_000_000_000_000),
            },
            wasm_store_creation_funding: CyclesCreationSource {
                kind: "cycles".to_string(),
                cycles: Cycles::new(10_000_000_000_000),
            },
        }],
    }
}

fn multi_component_source_toml(
    operator: &str,
    coordinator_subnet: &str,
    placement: &str,
) -> String {
    format!(
        r#"
schema_version = 1
funding_profile = "preview_multi_subnet"
operator = "{operator}"

[admission]
principals = ["{operator}"]

[coordinator.subnet]
kind = "explicit"
subnet = "{coordinator_subnet}"
acknowledge_fiduciary_cost = false

[coordinator.creation_funding]
kind = "cycles"
cycles = "270T"

[coordinator.root_funding]
minimum_reserve_cycles = "210T"
window_secs = 7776000
maximum_cycles = "30T"
maximum_automatic_grants = 2
maximum_automatic_cycles = "60T"

[[fleet_subnet_roots]]
placement_subnet = "{placement}"
acknowledge_fiduciary_cost = false
component_admissions = {{ app = 1 }}

[fleet_subnet_roots.component_group_placements]
app = [0]

[fleet_subnet_roots.canister_pool]
minimum_size = 2
maximum_size = 2
canister_cycles = "5T"

[fleet_subnet_roots.root_funding]
request_threshold = "10T"
target_balance = "30T"
cooldown_secs = 2592000
window_secs = 7776000
maximum_cycles = "30T"
maximum_automatic_grants = 2
maximum_automatic_cycles = "60T"

[fleet_subnet_roots.limits]
maximum_component_instances = 1
maximum_registry_bytes = 16777216
maximum_wasm_store_bytes = 40000000
maximum_group_placements = 1

[fleet_subnet_roots.limits.cycles_funding]
window_secs = 3600
maximum_cycles = "15T"

[fleet_subnet_roots.root_creation_funding]
kind = "cycles"
cycles = "30T"

[fleet_subnet_roots.wasm_store_creation_funding]
kind = "cycles"
cycles = "10T"
"#
    )
}

fn retained_estate_seed_toml(
    fleet_id: canic_core::ids::FleetId,
    coordinator: &str,
    placement: &str,
    root: &str,
    store: &str,
    pools: [&str; 2],
) -> String {
    format!(
        r#"
schema_version = 1
fleet_id = "{fleet_id}"
coordinator = "{coordinator}"
cycles_ledger = "{}"

[[roots]]
placement_subnet = "{placement}"
root = "{root}"
store = "{store}"
pool_imports = ["{}", "{}"]
"#,
        mainnet_cycles_ledger(),
        pools[0],
        pools[1],
    )
}

fn enroll_test_network(root: &Path) -> canic_core::ids::CanonicalNetworkId {
    let mut root_key = vec![
        0x30, 0x81, 0x82, 0x30, 0x1d, 0x06, 0x0d, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c,
        0x05, 0x03, 0x01, 0x02, 0x01, 0x06, 0x0c, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xdc, 0x7c,
        0x05, 0x03, 0x02, 0x01, 0x03, 0x61, 0x00,
    ];
    root_key.extend_from_slice(&[9; 96]);
    let path = root.join("root-key.der");
    fs::write(&path, &root_key).expect("write local root key");
    enroll_network(NetworkEnrollmentOptions {
        workspace_root: root,
        environment: "local",
        root_key: &path,
        fingerprint: &sha256_hex(&root_key),
    })
    .expect("enroll local network")
    .canonical_network_id
}

fn persist_test_release_authority(
    root: &Path,
    config: &AppConfigSnapshot,
    release_build_id: ReleaseBuildId,
) {
    let directory = root
        .join(".canic/release-builds")
        .join(release_build_id.to_string());
    fs::create_dir_all(&directory).expect("create release authority directory");
    let artifacts = infrastructure_artifacts(root, release_build_id);
    let infrastructure = CanicInfrastructureArtifactManifest {
        release_build_id,
        entries: artifacts,
    };
    fs::write(
        directory.join("infrastructure-artifact-manifest.json"),
        infrastructure
            .canonical_bytes()
            .expect("canonical infrastructure manifest"),
    )
    .expect("write infrastructure manifest");

    let role = CanisterRole::from("app");
    let wasm = [b"\0asm\x01\0\0\0".as_slice(), &[74]].concat();
    let wasm_gz = gzip(&wasm);
    let application = ApplicationArtifactUnion::compile(
        config.component_topology(),
        release_build_id,
        &[ApplicationArtifactBuildTarget {
            role: role.clone(),
            package: "app".to_string(),
            wasm_relative_path: "artifacts/app.wasm".to_string(),
            wasm_gz_relative_path: "artifacts/app.wasm.gz".to_string(),
        }],
        &[ApplicationArtifactBuildOutput {
            role,
            package: "app".to_string(),
            release_build_id,
            wasm_relative_path: "artifacts/app.wasm".to_string(),
            wasm,
            wasm_gz_relative_path: "artifacts/app.wasm.gz".to_string(),
            wasm_gz,
            candid_sha256: [75; 32],
            protocol_profile_digest: ProtocolProfileDigest::from_bytes([76; 32]),
        }],
    )
    .expect("compile application union");
    fs::write(
        directory.join("application-artifact-union.json"),
        application
            .canonical_bytes(config.component_topology())
            .expect("canonical application union"),
    )
    .expect("write application union");

    let current = CurrentReleaseSetManifest {
        application_artifact_union_sha256: application
            .digest(config.component_topology())
            .expect("application union digest"),
        build_network: canic_core::ids::BuildNetwork::Local,
        infrastructure_artifact_manifest_sha256: infrastructure
            .digest()
            .expect("infrastructure manifest digest"),
        release_build_id,
        schema_version: CurrentReleaseSetManifest::SCHEMA_VERSION,
    };
    let current_path = directory.join("current-release-set-manifest.json");
    fs::write(
        &current_path,
        current.canonical_bytes().expect("current release manifest"),
    )
    .expect("write current release manifest");
    finalize_release_build_from_manifest(root, release_build_id, &current_path)
        .expect("finalize test release authority");
}

fn gzip(bytes: &[u8]) -> Vec<u8> {
    let mut encoder = GzBuilder::new()
        .mtime(0)
        .write(Vec::new(), Compression::best());
    encoder.write_all(bytes).expect("write gzip");
    encoder.finish().expect("finish gzip")
}

fn copy_test_tree(source: &Path, destination: &Path) -> io::Result<()> {
    fs::create_dir_all(destination)?;
    for entry in fs::read_dir(source)? {
        let entry = entry?;
        let destination = destination.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_test_tree(&entry.path(), &destination)?;
        } else {
            fs::copy(entry.path(), destination)?;
        }
    }
    Ok(())
}

#[expect(
    clippy::too_many_arguments,
    reason = "the retained observation fixture binds every independent Fleet authority identity"
)]
fn retained_root_authority(
    canonical_network_id: canic_core::ids::CanonicalNetworkId,
    app: canic_core::ids::AppId,
    fleet_id: canic_core::ids::FleetId,
    source: &FleetSource,
    planned: &crate::component_topology::PlannedFleetSubnetRootTopology,
    operator: &str,
    coordinator: &str,
    coordinator_subnet: &str,
    root: &str,
    store: &str,
    release_build_id: ReleaseBuildId,
) -> FleetSubnetRootAuthority {
    let coordinator = parse_principal("Coordinator", coordinator).expect("Coordinator");
    let root = parse_principal("Root", root).expect("Root");
    let store = parse_principal("Store", store).expect("Store");
    let placement_subnet = planned.placement_subnet;
    let registry = FleetRegistryAuthority {
        binding: FleetCoordinatorBinding {
            fleet: FleetBinding {
                fleet: FleetKey {
                    canonical_network_id,
                    fleet_id,
                },
                app,
            },
            coordinator_subnet: parse_subnet("Coordinator", coordinator_subnet)
                .expect("Coordinator Subnet"),
            coordinator,
        },
        epoch: 1,
    };
    let root_source = source.fleet_subnet_roots.first().expect("Root source");
    let mut retained_limits = root_limits(root_source);
    retained_limits.canister_pool.canister_cycles = Cycles::new(2_000_000_000_000);
    let binding = FleetSubnetRootBinding {
        authority: registry.clone(),
        placement_subnet,
        fleet_subnet_root: root,
        component_admissions: planned.component_admissions.clone(),
        component_topology_digest: planned.component_topology_digest,
        limits: retained_limits,
        funding: root_funding(source.funding_profile, &root_source.root_funding),
    };
    FleetSubnetRootAuthority {
        binding,
        initial_release_set: FleetSubnetRootReleaseSet {
            release_build_id,
            manifest_digest: ReleaseSetDigest::from_bytes([78; 32]),
        },
        expected_module_hash: [79; 32],
        wasm_store_authority: FleetSubnetWasmStoreAuthority {
            authority: registry,
            placement_subnet,
            fleet_subnet_root: root,
            wasm_store: store,
            installation_controller: parse_principal("operator", operator).expect("operator"),
            release_build_id,
            wasm_module_hash: [80; 32],
        },
    }
}

fn retained_pool_response(
    config: FleetSubnetCanisterPoolConfig,
    store: &str,
    workload: &str,
    idle: &str,
) -> CanisterPoolResponse {
    let claim = canic_core::dto::pool::CanisterPoolClaim {
        component: canic_core::ids::ComponentInstanceId::from_generated_bytes([81; 32]),
        operation_id: [82; 32],
    };
    CanisterPoolResponse {
        config,
        tracked: 3,
        store: 1,
        store_deletion_pending: 0,
        pooled: 1,
        workload: 1,
        surplus: 0,
        ready: 1,
        pending_reset: 0,
        claimed: 0,
        recycling: 0,
        recovering_ledger: 0,
        handing_off: 0,
        failed: 0,
        completed_handoffs: 0,
        pending_creation: None,
        pending_handoff: None,
        entries: vec![
            CanisterPoolAsset {
                canister_id: parse_principal("Store", store).expect("Store"),
                cycles: Cycles::new(10_000_000_000_000),
                origin: CanisterPoolAssetOrigin::InfrastructureStore,
                status: CanisterPoolAssetStatus::Store,
                added_at_ns: 1,
                updated_at_ns: 1,
            },
            CanisterPoolAsset {
                canister_id: parse_principal("workload", workload).expect("workload"),
                cycles: Cycles::new(4_900_000_000_000),
                origin: CanisterPoolAssetOrigin::Imported,
                status: CanisterPoolAssetStatus::Workload { claim },
                added_at_ns: 2,
                updated_at_ns: 3,
            },
            CanisterPoolAsset {
                canister_id: parse_principal("idle pool", idle).expect("idle pool"),
                cycles: Cycles::new(5_000_000_000_000),
                origin: CanisterPoolAssetOrigin::Imported,
                status: CanisterPoolAssetStatus::Ready,
                added_at_ns: 4,
                updated_at_ns: 5,
            },
        ],
        next_start_after: None,
    }
}

struct FakeIcpFixture<'a> {
    authority: &'a FleetSubnetRootAuthority,
    coordinator: &'a str,
    coordinator_module_hash: &'a str,
    fleet_root: &'a str,
    operator: &'a str,
    pool: &'a CanisterPoolResponse,
    public_cycle_balance: Option<(&'a str, u128)>,
    root_module_hash: &'a str,
    root_runtime_status: &'a str,
    root_status_error: Option<canic_core::diagnostics::RegisteredDiagnosticCode>,
    store: &'a str,
    store_has_root_controller: bool,
    store_module_hash: &'a str,
}

#[cfg(unix)]
fn write_fake_icp(root: &Path, fixture: FakeIcpFixture<'_>) -> PathBuf {
    write_fake_icp_with_status_projection(root, fixture, Some(1), false)
}

#[cfg(unix)]
fn write_versionless_root_owned_fake_icp(root: &Path, fixture: FakeIcpFixture<'_>) -> PathBuf {
    write_fake_icp_with_status_projection(root, fixture, None, true)
}

#[cfg(unix)]
#[expect(
    clippy::too_many_lines,
    reason = "one process-backed fixture keeps every accepted fake ICP command visible"
)]
fn write_fake_icp_with_status_projection(
    root: &Path,
    fixture: FakeIcpFixture<'_>,
    status_canister_version: Option<u64>,
    store_status_unavailable: bool,
) -> PathBuf {
    let FakeIcpFixture {
        authority,
        coordinator,
        coordinator_module_hash,
        fleet_root,
        operator,
        pool,
        public_cycle_balance,
        root_module_hash,
        root_runtime_status,
        root_status_error,
        store,
        store_has_root_controller,
        store_module_hash,
    } = fixture;
    let executable = root.join("fake-icp");
    let counter = root.join("root-status-count");
    let predecessor_pool_status = root.join("predecessor-pool-status");
    let root_started = root.join("root-started");
    let root_start_count = root.join("root-start-count");
    let store_status_count = root.join("store-status-count");
    if root_started.exists() {
        fs::remove_file(&root_started).expect("reset fake Root runtime state");
    }
    if root_start_count.exists() {
        fs::remove_file(&root_start_count).expect("reset fake Root start count");
    }
    if predecessor_pool_status.exists() {
        fs::remove_file(&predecessor_pool_status).expect("reset predecessor pool response");
    }
    if store_status_count.exists() {
        fs::remove_file(&store_status_count).expect("reset Store status counter");
    }
    let coordinator_status = canister_status_json(
        coordinator,
        operator,
        coordinator_module_hash.to_string(),
        270_000_000_000_000,
        "running",
        None,
        status_canister_version,
    );
    let root_status = canister_status_json(
        fleet_root,
        operator,
        root_module_hash.to_string(),
        30_000_000_000_000,
        root_runtime_status,
        None,
        status_canister_version,
    );
    let running_root_status = canister_status_json(
        fleet_root,
        operator,
        root_module_hash.to_string(),
        29_999_950_000_000,
        "running",
        None,
        status_canister_version,
    );
    let store_status = canister_status_json(
        store,
        operator,
        store_module_hash.to_string(),
        10_000_000_000_000,
        "running",
        store_has_root_controller.then_some(fleet_root),
        status_canister_version,
    );
    let store_status_command = if store_status_unavailable {
        format!(
            r#"if [ ! -f "{}" ]; then
      printf '%s\n' '1' > "{}"
      printf '%s\n' 'Store status unavailable' >&2
      exit 1
    fi
    printf '%s\n' '{store_status}'
    exit 0"#,
            store_status_count.display(),
            store_status_count.display(),
        )
    } else {
        format!("printf '%s\\n' '{store_status}'\n    exit 0")
    };
    let authority_response = candid_response_json(&Ok::<_, canic_core::dto::error::Error>(
        RootEstateStatusResponse::FleetAuthority(Box::new(authority.clone())),
    ));
    let pool_response = root_status_error.map_or_else(
        || {
            candid_response_json(&Ok::<_, canic_core::dto::error::Error>(
                RootEstateStatusResponse::Pool(Box::new(pool.clone())),
            ))
        },
        |code| {
            candid_response_json(&Err::<RootEstateStatusResponse, _>(
                canic_core::dto::error::Error::from_registered(code),
            ))
        },
    );
    let predecessor_pool_response = serde_json::json!({
        "response_bytes": hex_bytes(
            crate::fleet_ensure::ops::predecessor_root_status::encode_pool_response_fixture(pool)
        )
    })
    .to_string();
    let ledger_response = candid_response_json(&Nat::from(100_000_000_u64));
    let public_cycle_case = public_cycle_balance.map_or_else(String::new, |(canister, cycles)| {
        let response = candid_response_json(&Ok::<_, canic_core::dto::error::Error>(
            FixtureManagedStatusResponse::CycleBalance(
                canic_core::dto::role::CycleBalanceStatusResponse { cycles },
            ),
        ));
        format!(
            r#"if [ "$1" = "canister" ] && [ "$2" = "call" ] && [ "$3" = "{canister}" ] && [ "$4" = "canic_status" ]; then
  printf '%s\n' '{response}'
  exit 0
fi
"#
        )
    });
    let script = format!(
        r#"#!/bin/sh
if [ "$1" = "--version" ]; then
  printf '%s\n' 'icp 1.3.0'
  exit 0
fi
while [ "$1" = "--project-root-override" ] || [ "$1" = "--identity-password-file" ]; do
  shift 2
done
if [ "$1" = "identity" ] && [ "$2" = "principal" ]; then
  printf '%s\n' '{operator}'
  exit 0
fi
if [ "$1" = "cycles" ] && [ "$2" = "balance" ]; then
  printf '%s\n' '{{"balance":"500000000000000 cycles"}}'
  exit 0
fi
if [ "$1" = "canister" ] && [ "$2" = "status" ]; then
  if [ "$3" = "{coordinator}" ]; then
    printf '%s\n' '{coordinator_status}'
    exit 0
  fi
  if [ "$3" = "{fleet_root}" ]; then
    if [ -f "{root_started}" ]; then
      printf '%s\n' '{running_root_status}'
    else
      printf '%s\n' '{root_status}'
    fi
    exit 0
  fi
  if [ "$3" = "{store}" ]; then
    {store_status_command}
  fi
fi
if [ "$1" = "canister" ] && [ "$2" = "start" ] && [ "$3" = "{fleet_root}" ]; then
  count=0
  if [ -f "{root_start_count}" ]; then
    count=$(sed -n '1p' "{root_start_count}")
  fi
  count=$((count + 1))
  printf '%s\n' "$count" > "{root_start_count}"
  printf '%s\n' 'running' > "{root_started}"
  exit 0
fi
if [ "$1" = "canister" ] && [ "$2" = "call" ]; then
  {public_cycle_case}
  if [ "$4" = "icrc1_fee" ]; then
    printf '%s\n' '{ledger_response}'
    exit 0
  fi
  if [ "$3" = "{fleet_root}" ] && [ "$4" = "canic_status" ]; then
    count=0
    if [ -f "{counter}" ]; then
      count=$(sed -n '1p' "{counter}")
    fi
    if [ "$count" = "0" ]; then
      printf '%s\n' '1' > "{counter}"
      printf '%s\n' '{authority_response}'
    elif [ -f "{predecessor_pool_status}" ]; then
      printf '%s\n' '{predecessor_pool_response}'
    else
      printf '%s\n' '{pool_response}'
    fi
    exit 0
  fi
fi
printf '%s\n' 'unsupported fake ICP command' >&2
exit 42
"#,
        counter = counter.display(),
        predecessor_pool_status = predecessor_pool_status.display(),
        root_start_count = root_start_count.display(),
        root_started = root_started.display(),
    );
    fs::write(&executable, script).expect("write fake ICP executable");
    fs::set_permissions(&executable, fs::Permissions::from_mode(0o755))
        .expect("make fake ICP executable runnable");
    executable
}

#[derive(candid::CandidType)]
enum FixtureManagedStatusResponse {
    CycleBalance(canic_core::dto::role::CycleBalanceStatusResponse),
}

#[cfg(not(unix))]
fn write_fake_icp(_root: &Path, _fixture: FakeIcpFixture<'_>) -> PathBuf {
    panic!("public generator fixture requires a Unix fake ICP executable")
}

#[cfg(not(unix))]
fn write_versionless_root_owned_fake_icp(_root: &Path, _fixture: FakeIcpFixture<'_>) -> PathBuf {
    panic!("public generator fixture requires a Unix fake ICP executable")
}

fn canister_status_json(
    canister: &str,
    controller: &str,
    module_hash: String,
    cycles: u128,
    status: &str,
    second_controller: Option<&str>,
    canister_version: Option<u64>,
) -> String {
    let mut controllers = vec![controller];
    controllers.extend(second_controller);
    let mut status = serde_json::json!({
        "id": canister,
        "name": null,
        "status": status,
        "settings": { "controllers": controllers },
        "module_hash": module_hash,
        "memory_size": null,
        "cycles": cycles.to_string(),
        "reserved_cycles": null,
        "idle_cycles_burned_per_day": null
    });
    if let Some(canister_version) = canister_version {
        status["version"] = serde_json::json!(canister_version);
    }
    status.to_string()
}

fn candid_response_json<T: candid::CandidType>(value: &T) -> String {
    let bytes = candid::encode_one(value).expect("encode fake ICP response");
    serde_json::json!({ "response_bytes": hex_bytes(bytes) }).to_string()
}

fn infrastructure_artifacts(
    root: &Path,
    release_build_id: ReleaseBuildId,
) -> Vec<CanicInfrastructureArtifactEntry> {
    [
        CanicInfrastructureRole::FleetCoordinator,
        CanicInfrastructureRole::FleetSubnetRoot,
        CanicInfrastructureRole::PoolLedgerRecovery,
        CanicInfrastructureRole::WasmStore,
    ]
    .into_iter()
    .enumerate()
    .map(|(index, role)| {
        let marker = u8::try_from(index).expect("three infrastructure artifacts");
        let artifact_name = role.protocol_role_name();
        let release_identity = release_build_id.to_string();
        let path = format!("artifacts/{release_build_id}/{artifact_name}/{artifact_name}.wasm");
        let bytes = [
            b"\0asm\x01\0\0\0".as_slice(),
            &[marker],
            release_identity.as_bytes(),
        ]
        .concat();
        let absolute = root.join(&path);
        fs::create_dir_all(absolute.parent().expect("artifact parent"))
            .expect("create artifact parent");
        fs::write(&absolute, &bytes).expect("write artifact");
        fs::write(absolute.with_extension("did"), b"service : {};").expect("write Candid");
        CanicInfrastructureArtifactEntry {
            role,
            package: role.as_str().to_string(),
            protocol_release_identity: "current".to_string(),
            protocol_role: CanisterRole::owned(role.protocol_role_name().to_string()),
            protocol_capabilities: BTreeSet::<RoleCapabilityKey>::new(),
            release_build_id,
            wasm_relative_path: path,
            wasm_size_bytes: bytes.len() as u64,
            wasm_sha256_hex: canic_core::cdk::utils::hash::sha256_hex(&bytes),
            wasm_gz_relative_path: format!(
                "artifacts/{release_build_id}/{}.wasm.gz",
                role.as_str()
            ),
            wasm_gz_size_bytes: 1,
            wasm_gz_sha256_hex: "00".repeat(32),
            candid_sha256: Sha256::digest(b"service : {};").into(),
            protocol_profile_digest: ProtocolProfileDigest::from_bytes([marker; 32]),
        }
    })
    .collect()
}

#[test]
fn candid_sidecar_uses_the_manifest_bound_wasm_basename() {
    let root = temp_dir("canic-generate-candid-sidecar");
    let release_build_id = "91".repeat(32).parse().expect("release build ID");
    let artifacts = infrastructure_artifacts(&root, release_build_id);
    let root_artifact = artifacts
        .iter()
        .find(|entry| entry.role == CanicInfrastructureRole::FleetSubnetRoot)
        .expect("Root artifact");

    assert_eq!(
        root_artifact.wasm_relative_path,
        format!("artifacts/{release_build_id}/root/root.wasm")
    );
    assert_eq!(
        candid_sidecar(&root, root_artifact).expect("resolve Root sidecar"),
        format!("artifacts/{release_build_id}/root/root.did")
    );

    let sidecar = root
        .join(&root_artifact.wasm_relative_path)
        .with_extension("did");
    fs::rename(&sidecar, sidecar.with_file_name("renamed.did")).expect("rename sidecar");
    assert!(matches!(
        candid_sidecar(&root, root_artifact),
        Err(FleetGenerateError::Candid(reason)) if reason.contains("is missing")
    ));
    fs::write(&sidecar, b"service : { changed : () -> (); };").expect("write changed sidecar");
    assert!(matches!(
        candid_sidecar(&root, root_artifact),
        Err(FleetGenerateError::Candid(reason)) if reason.contains("digest differs")
    ));

    fs::remove_dir_all(root).expect("remove fixture root");
}

#[cfg(unix)]
#[test]
fn candid_sidecar_rejects_a_symbolic_link() {
    let root = temp_dir("canic-generate-candid-sidecar-link");
    let release_build_id = "92".repeat(32).parse().expect("release build ID");
    let artifacts = infrastructure_artifacts(&root, release_build_id);
    let root_artifact = artifacts
        .iter()
        .find(|entry| entry.role == CanicInfrastructureRole::FleetSubnetRoot)
        .expect("Root artifact");
    let sidecar = root
        .join(&root_artifact.wasm_relative_path)
        .with_extension("did");
    let target = sidecar.with_file_name("target.did");
    fs::rename(&sidecar, &target).expect("move real sidecar");
    symlink(&target, &sidecar).expect("link sidecar");

    assert!(matches!(
        candid_sidecar(&root, root_artifact),
        Err(FleetGenerateError::Candid(reason)) if reason.contains("not a regular no-follow file")
    ));

    fs::remove_dir_all(root).expect("remove fixture root");
}

fn principal_text(byte: u8) -> String {
    Principal::from_slice(&[byte; 29]).to_text()
}

fn divergent_principal_order_pair() -> (Principal, Principal) {
    for left_byte in 0_u8..=u8::MAX {
        let left = Principal::from_slice(&[left_byte]);
        for right_byte in left_byte.saturating_add(1)..=u8::MAX {
            let right = Principal::from_slice(&[right_byte]);
            if left.cmp(&right) != left.to_text().cmp(&right.to_text()) {
                return (left, right);
            }
        }
    }
    panic!("Principal fixture set did not contain divergent text and binary ordering")
}