ignition-core 1.6.2

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! Typed error taxonomy — THE exit-code contract for `ign`.
//!
//! The mapping error-class → exit code is LOCKED (Phase-1 API freeze). The
//! table exists in exactly two places: [`CoreError::exit_code`] here and the
//! README — kept in sync by the `exit_code_mapping_enumerated` unit test and
//! the golden-file tests in `crates/ignition-cli/tests/`.
//!
//! | exit | class          | slugs
//! |------|----------------|-----------------------------------------------
//! | 1    | internal       | `internal`
//! | 2    | usage          | `confirmation_required`, `invalid_import_file`, `invalid_input`, `gateway_client_error` (09-01), `deploy_tree_invalid`, `embedded_secret` (21-03), `destructive_change_refused` (23-02) (clap renders its own usage errors — never hook clap)
//! | 3    | config         | `profile_not_found`, `no_active_profile`, `secret_unavailable`, `config_invalid`, `poll_interval_too_small` (08-01), `module_not_registered` (16-01)
//! | 4    | network        | `network_error`, `module_feed_unreachable` (15-01), `transport_failed` (22-01)
//! | 5    | auth           | `auth_rejected`
//! | 6    | target_state   | `gateway_too_old`, `gateway_not_commissioned`, `gateway_restarting`, `not_found`, `project_exists`, `resource_binary`, `trial_not_expired` (04-03), `provider_not_found` (05-04), `routes_not_deployed`, `webdev_unlicensed`, `route_version_mismatch`, `webdev_route_error` (05-03), `tag_collision` (05-05), `alarm_journal_missing` (05-06), `import_denied` (05-07), `session_not_prunable` (06-07), `eam_not_controller` (07-02), `eam_task_type_refused` (07-02), `eam_task_in_flight` (07-06), `script_exec_not_configured` (07-03), `lint_tool_absent` (07-04), `provider_root_unsupported` (07-06), `bundle_not_available` (09-07), `module_release_not_found`, `module_digest_mismatch`, `module_feed_unusable` (15-01), `module_digest_changed` (15-02), `module_uninstall_denied` (19-01), `scan_lock_held` (20-02), `resource_signature_rejected` (20-02), `resource_exists` (20-REVIEW WR-01), `mode_exists` (20-REVIEW WR-01), `deploy_ledger_invalid` (22-03), `plan_stale`, `deploy_blocked`, `deploy_preflight_failed`, `deploy_journal_present`, `deploy_live_changed`, `deploy_run_invalid`, `rollback_failed` (23-02), `project_git_managed` (25-07), `deploy_unreadable` (quick-261029-ms3)
//! | 7    | rig            | `rig_error` (reserved — first used in Phase 4)
//!
//! Slugs are public contract: never respell them. Exit codes are public
//! contract: never renumber them (the enumerated test guards both).

use serde::Serialize;

/// The `ign tui` TTY-refusal reason (06-07). The InvalidInput hint is
/// content-addressed off this exact string: the frozen taxonomy keeps
/// ONE usage-input variant (no hint field, no new variant), but the
/// TTY refusal's fix is terminal-related, not `--file`/stdin —
/// [`CoreError::hint`] special-cases this one reason while every other
/// raise site keeps the resource-put default. Construct via
/// [`CoreError::tui_tty_refusal`] so the reason/hint pair cannot drift.
pub const TUI_TTY_REFUSAL_REASON: &str = "ign tui requires a terminal (stdout is not a TTY)";

/// The `ign top` (itop) TTY-refusal reason — the SAME usage class and
/// slug as [`TUI_TTY_REFUSAL_REASON`] at one command over (the monitor
/// is its own full-screen surface, so its refusal names ITS command —
/// the RoutesNotDeployed rule: a hint must never name a command that
/// does not fix it). [`CoreError::hint`] content-addresses this
/// constant exactly like its tui sibling.
pub const TOP_TTY_REFUSAL_REASON: &str = "ign top requires a terminal (stdout is not a TTY)";

/// The TAGS-12 loss-gate refusal reason prefix (11-07 gap closure). The
/// InvalidInput hint is content-addressed off this literal: the loss
/// gate's reason is DYNAMIC prose (the CLI's `render_loss_prose` header
/// `loss report ({label}): …` plus per-fact lines), so unlike
/// [`TUI_TTY_REFUSAL_REASON`] the sentinel cannot be the whole reason —
/// it is the stable header prefix instead. Same slug (`invalid_input`),
/// same exit 2 (frozen taxonomy; only the hint differs) — the 06-07
/// TTY-refusal pattern at one removal. The contract_tags loss-gate
/// pins are the drift guard: if the prose header ever changes, the
/// hint silently regresses to the generic default and those pins fail.
pub const LOSS_GATE_REFUSAL_REASON_PREFIX: &str = "loss report (";

/// The TESTING bundle's route prefix (QUICK-p0g). The
/// [`CoreError::RoutesNotDeployed`] hint is content-addressed off it
/// — same third instance of the 06-07 pattern: the frozen taxonomy
/// keeps ONE absent-routes variant and one slug
/// (`routes_not_deployed`, exit 6), but the testing bundle installs
/// through a DIFFERENT command (`ign webdev deploy --with-testing` /
/// `ign adopt --project NAME --testing`), so the generic
/// `ign webdev deploy` hint would name a command that does not fix
/// it. Raise sites pass `route: "testing/run"`.
pub const TESTING_ROUTE_PREFIX: &str = "testing/";

/// The api-call catch-all's body cap (09-01): a gateway 4xx body rides
/// [`CoreError::GatewayClientError`] VERBATIM up to this many bytes; a
/// larger body is truncated at [`truncate_api_body`] with the explicit
/// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`]. 4 KiB is the plan-locked
/// cap — an unbounded passthrough would let a pathological gateway
/// page flood the agent's envelope.
pub const GATEWAY_CLIENT_BODY_CAP_BYTES: usize = 4096;

/// The truncation marker [`truncate_api_body`] appends when the api-call
/// body exceeds [`GATEWAY_CLIENT_BODY_CAP_BYTES`]. ASCII-pinned (no
/// multi-byte characters) so golden-file consumers never see an encoding
/// surprise at the cut.
pub const GATEWAY_CLIENT_BODY_TRUNCATION_MARKER: &str = "... [truncated]";

/// The ONE construction site for a capped api-call body: returns `body`
/// verbatim when it fits [`GATEWAY_CLIENT_BODY_CAP_BYTES`], otherwise its
/// first cap bytes (on a UTF-8 char boundary) plus
/// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`]. The variant always carries
/// its final form — construction cannot forget the cap.
pub fn truncate_api_body(body: &str) -> String {
    if body.len() <= GATEWAY_CLIENT_BODY_CAP_BYTES {
        return body.to_string();
    }
    let mut end = GATEWAY_CLIENT_BODY_CAP_BYTES;
    while !body.is_char_boundary(end) {
        end -= 1;
    }
    let mut truncated = body[..end].to_string();
    truncated.push_str(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER);
    truncated
}

/// Every failure `ign` can report. One variant per contract class; `code()`,
/// `exit_code()`, `hint()` are total functions over it.
#[derive(Debug, thiserror::Error)]
pub enum CoreError {
    /// Unexpected runtime failure — the catch-all; report as a bug. Exit 1.
    #[error("internal error: {0}")]
    Internal(String),

    /// Destructive operation invoked without `--yes`. Exit 2 (same class as
    /// usage: it names a flag the caller must add; clap renders its own
    /// usage errors with its exit 2 — never hook clap).
    #[error("{operation} is destructive; rerun with --yes to confirm")]
    ConfirmationRequired { operation: String },

    /// JVM profiling invoked without `--i-accept-the-risk`. Exit 2
    /// (usage class — it names a flag the caller must add, like
    /// [`Self::ConfirmationRequired`]) but DELIBERATELY NOT satisfiable
    /// by the global `--yes`/`IGNITION_YES`: active JVM instrumentation
    /// is a stronger opt-in than the destructive-verb guard — the
    /// caller must acknowledge THIS specific production risk, not
    /// confirm generically.
    #[error(
        "{operation} actively instruments the gateway JVM; rerun with --i-accept-the-risk to acknowledge the production risk"
    )]
    ProfilingRiskNotAccepted { operation: String },

    /// An import byte source the caller must fix (wrong file, too big,
    /// unreadable). Exit 2 — usage class: it names what the CALLER must
    /// change, like [`Self::ConfirmationRequired`] (03-02).
    #[error("invalid import file: {reason}")]
    InvalidImportFile { reason: String },

    /// The gateway ANSWERED the import POST with HTTP 200 but the
    /// body says `{"success": false, "problem": "…"}` — the
    /// denial-rides-200 class the WebDev family handles (05-01)
    /// applied to the project-import family (05-07, UAT Gap 1):
    /// without this check the import caller reports ok while nothing
    /// landed. Exit 6 — target state: the gateway refused the
    /// import (the problem text names why, verbatim).
    #[error("gateway rejected the project import for {project:?}: {problem}")]
    ImportDenied {
        /// The project the import was headed for.
        project: String,
        /// The gateway's own `problem` text (verbatim when present).
        problem: String,
        /// URL of the import request, when known.
        endpoint: Option<String>,
    },

    /// A command input the caller must fix (unreadable `--file`, failed
    /// stdin read). Exit 2 — usage class, the generic sibling of
    /// [`Self::InvalidImportFile`] (03-03: `resource put`'s byte
    /// source).
    #[error("invalid input: {reason}")]
    InvalidInput { reason: String },

    /// Named profile absent from config. Exit 3.
    #[error("profile {name:?} not found (known profiles: {known:?})")]
    ProfileNotFound { name: String, known: Vec<String> },

    /// No `--profile`, no `IGNITION_PROFILE`, no active profile in config.
    /// Exit 3. Constructible from the CLI once config resolution lands
    /// (01-03); the taxonomy is complete on day one.
    #[error("no active profile configured")]
    NoActiveProfile,

    /// No credential resolvable for the profile (env, token_env, keyring all
    /// missed or failed). Exit 3.
    #[error("secret unavailable for profile {profile:?}")]
    SecretUnavailable { profile: String },

    /// The adopt bootstrap's login rung needs `IGNITION_PASSWORD` and it
    /// was absent/empty (ADOPT-05 review round: the generic
    /// [`Self::SecretUnavailable`] hint names the TOKEN paths, which is
    /// exactly wrong for the PASSWORD gate — same exit class, own slug,
    /// never a new exit code; the PollIntervalTooSmall precedent).
    #[error("login password unavailable for profile {profile:?}")]
    PasswordUnavailable { profile: String },

    /// Config file unreadable or wrong shape. Exit 3.
    #[error("invalid configuration: {reason}")]
    ConfigInvalid { reason: String },

    /// A profile's `poll_interval_secs` is below the 1-second floor
    /// (08-01, TUIX-05 clamp): sub-second gateway polling is refused at
    /// load time — the TUI's background refresh cadence may not hammer
    /// the gateway. Exit 3 — the CONFIG class (the Phase-7 additive-slug
    /// precedent, e.g. `eam_not_controller`: same exit class, own slug,
    /// never a new exit code — the 1–7 taxonomy is frozen).
    #[error("profile {profile:?}: poll_interval_secs must be >= 1 (sub-second polling refused)")]
    PollIntervalTooSmall {
        /// The profile carrying the refused value.
        profile: String,
    },

    /// Gateway unreachable / timeout / TLS failure. Exit 4.
    ///
    /// `source: None` marks a POLL deadline expiry (02-04 `poll.rs`):
    /// same class, same slug (`network_error`), no new variant — the
    /// transport-error `source` a real failure carries is simply
    /// absent, and `url` describes what was being waited on instead
    /// (the poll's subject). The deadline's last observation rides
    /// `observation` (09-07): when it is `Some` the gateway ANSWERED
    /// with a concrete state, and the message leads with "no terminal
    /// state" — it NEVER claims unreachability for an observed
    /// answer; `None` keeps the plain unreachability wording.
    #[error(
        "{lead} at {url}{source_note}{observation_note}",
        lead = if observation.is_some() {
            "no terminal state"
        } else {
            "gateway unreachable"
        },
        source_note = source.as_ref().map(|source| format!(": {source}")).unwrap_or_default(),
        observation_note = observation
            .as_deref()
            .map(|obs| format!("; last observation: {obs}"))
            .unwrap_or_default()
    )]
    Network {
        url: String,
        #[source]
        source: Option<reqwest::Error>,
        /// The poll deadline's last concrete observation (e.g. the
        /// gateway's reported state) — `None` for transport failures
        /// and observation-less deadlines. `Some` ⇒ the gateway
        /// answered; the Display never says "unreachable" then.
        observation: Option<String>,
    },

    /// Gateway reachable but rejected credentials (401/403). Exit 5.
    #[error("gateway rejected credentials (HTTP {status})")]
    Auth {
        status: u16,
        /// URL/path of the request that was rejected, when known.
        endpoint: Option<String>,
    },

    /// Gateway reachable but the command is invalid for its current state —
    /// version below minimum, uncommissioned, mid-restart, or a missing
    /// resource. Exit 6.
    #[error("gateway version {found} is below minimum {minimum}")]
    GatewayTooOld {
        found: String,
        minimum: String,
        /// URL/path of the request that answered, when known.
        endpoint: Option<String>,
    },

    /// Gateway reachable but uncommissioned — every `/data` route 302s to
    /// `/welcome` (verified on a fresh 8.3.6 container; 02-RESEARCH
    /// §Error-Body Sniffing). Exit 6.
    #[error("gateway at {} is not commissioned", endpoint.as_deref().unwrap_or("unknown address"))]
    GatewayNotCommissioned {
        /// URL that was redirected to the commissioning wizard.
        endpoint: Option<String>,
    },

    /// Gateway restarting — webserver answers (503) but services are down
    /// (verified restart lifecycle: webserver never drops the connection).
    /// Exit 6.
    #[error("gateway is restarting (webserver up, services down)")]
    GatewayRestarting {
        /// URL that answered 503.
        endpoint: Option<String>,
    },

    /// Named resource absent (404) — terminating a nonexistent session id,
    /// an unknown path, or a pre-8.3 gateway's JSON
    /// `{"message": "No route match for path: …"}`. Exit 6.
    #[error("resource not found on the gateway")]
    NotFound {
        /// URL that answered 404.
        endpoint: Option<String>,
    },

    /// A project of this name already exists and the import's collision
    /// policy is abort — the CLI-side pre-check refused BEFORE any
    /// upload (the server's own answer remains the backstop). Exit 6 —
    /// target state: the command is invalid for the gateway's current
    /// state (03-02, the GatewayTooOld action-built-variant precedent:
    /// constructed by the actions layer, not classify).
    #[error("project {name} already exists on the gateway")]
    ProjectExists {
        /// The colliding project name.
        name: String,
        /// URL of the pre-check request, when known.
        endpoint: Option<String>,
    },

    /// A binary (data.bin-class) resource met the surgical JSON/text
    /// loop — REFUSED rather than corrupted through it. Exit 6 —
    /// target state: the command is invalid for that resource's
    /// nature; the export/import family owns binary resources
    /// (Pitfall 7).
    #[error("resource {path:?} has binary content — not editable via the resource loop")]
    ResourceBinary {
        /// The resource path that was refused.
        path: String,
        /// URL of the request involved, when known.
        endpoint: Option<String>,
    },

    /// The gateway refuses trial resets while the trial is still
    /// active — live-discovered on 8.3.3 during 04-03's spike: the
    /// reset POST answers 403 on a NON-expired trial (verified from
    /// the browser page itself with the exact UI headers), and 200 +
    /// the flip on an expired one. The action layer's expiry pre-check
    /// turns that misleading auth-shaped 403 into the honest
    /// target-state refusal. Exit 6 (the ProjectExists precedent:
    /// action-constructed, not classify).
    #[error(
        "trial is not expired ({remaining_s}s left) — the gateway only honors resets once the trial expires"
    )]
    TrialNotExpired {
        /// Seconds left on the active trial.
        remaining_s: i64,
        /// URL of the rig's trial endpoint, when known.
        endpoint: Option<String>,
    },

    /// The WebDev route family a command depends on is not deployed —
    /// the presence probe answered 405, the live-proven 8.3 absent
    /// marker (missing routes AND missing projects both answer 405,
    /// NOT 404; 05-RESEARCH Pitfall 1). Exit 6 — target state: the
    /// command is invalid until `ign webdev deploy` installs the
    /// routes (the TrialNotExpired precedent: action-constructed, not
    /// classify).
    #[error(
        "webdev routes are not deployed (probe of {route:?} in project {project:?} answered 405)"
    )]
    RoutesNotDeployed {
        /// The deploy project the probe targeted.
        project: String,
        /// The route folder the probe named.
        route: String,
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// The WebDev module answered 402 — installed but unlicensed (a
    /// trial-expired gateway; live-verified cross-version on 8.3.6,
    /// 05-RESEARCH §Servlet). Exit 6 — no `/system/webdev` route can
    /// answer until the gateway is licensed.
    #[error(
        "the WebDev module is unlicensed on this gateway (HTTP 402 — trial-expired rigs cannot serve /system/webdev routes)"
    )]
    WebdevUnlicensed {
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// A deployed route's handshake version differs from the embedded
    /// bundle's — the CLI refuses rather than auto-upgrading either
    /// side (roadmap-locked: actionable error, no auto-upgrade
    /// magic). Exit 6.
    #[error("route {route:?} version mismatch: deployed {deployed}, this CLI expects {expected}")]
    RouteVersionMismatch {
        /// The route folder that answered.
        route: String,
        /// The route's deployed `routeVersion`.
        deployed: String,
        /// The embedded bundle's version
        /// ([`crate::webdev::ROUTE_BUNDLE_VERSION`]).
        expected: String,
        /// Path of the probe request, when known.
        endpoint: Option<String>,
    },

    /// A tag provider of this name does not exist — the
    /// find→signature→delete chain's find half missed (05-04,
    /// TAGS-01). Exit 6 — target state: the named thing is absent
    /// (the ProjectExists precedent family: action-constructed, not
    /// classify — the honest, family-specific refusal over a bare
    /// 404).
    #[error("tag provider {name:?} not found on the gateway")]
    ProviderNotFound {
        /// The provider name that missed.
        name: String,
        /// URL of the find request, when known.
        endpoint: Option<String>,
    },

    /// A WebDev route answered HTTP 200 with a body denial
    /// (`{ok:false, error{code,message}}`) whose machine code this CLI
    /// does not specifically map — code + message ride verbatim so
    /// agents can branch on the stable route contract (05-01). Exit 6
    /// — target state: the deployed route refused the action.
    #[error("webdev route denied the call ({code}): {message}")]
    WebdevRouteError {
        /// The route's machine error code (stable contract).
        code: String,
        /// The route's human message.
        message: String,
        /// Path of the request, when known.
        endpoint: Option<String>,
    },

    /// A tag import under abort policy found EXISTING tags at the
    /// target provider (05-05, TAGS-09) — the browse pre-check
    /// refuses BEFORE any route write (the LOCKED Phase-3 collision
    /// matrix mapped onto configure's 'a'/'o'). Exit 6 — target
    /// state: the named tags exist; overwrite is the explicit,
    /// guarded opt-in.
    #[error(
        "tag collision importing into provider {provider:?}: {} already exist(s)",
        names.join(", ")
    )]
    TagCollision {
        /// The target provider the import was headed for.
        provider: String,
        /// The colliding top-level tag names the pre-check found.
        names: Vec<String>,
        /// URL of the pre-check browse request, when known.
        endpoint: Option<String>,
    },

    /// The gateway has no alarm-journal profile configured — alarm
    /// history has nowhere to read from. The alarms route's
    /// structured `no_alarm_journal` denial maps here (the
    /// denial_to_error seam, 05-06 TAGS-07): DEFAULT rigs hit this
    /// ALWAYS, because the journal is a config-resource chain —
    /// database connection + `ignition/alarm-journal` profile + the
    /// `general-alarm-settings` singleton pointing at it. Exit 6 —
    /// target state: the command is invalid for the gateway's
    /// current state until that chain is provisioned (the honest,
    /// actionable refusal over a bare route error).
    #[error(
        "no alarm journal profile is configured on this gateway — alarm history has nothing to read"
    )]
    AlarmJournalMissing {
        /// URL of the alarms route request, when known.
        endpoint: Option<String>,
    },

    /// Pruning a LIVE Designer session entry — the gateway's prune
    /// route answers 409 (empty body, wire-verified on 8.3.3,
    /// 06-UAT test 6): prune removes STALE entries only, so the
    /// command is invalid while the Designer is still open. Exit 6 —
    /// target state (additive slug in the frozen taxonomy's
    /// established growth pattern; classify()'s ROUTE-SCOPED 409 arm
    /// constructs this — the first classify-constructed refusal added
    /// since the 02-01 set).
    #[error("designer session {id} is live — the gateway refused the prune")]
    SessionNotPrunable {
        /// The Designer session id that was refused.
        id: String,
        /// URL of the refused DELETE, when known.
        endpoint: Option<String>,
    },

    /// Docker/compose rig failure. Exit 7. Reserved — first used in Phase 4;
    /// trivially constructible so the taxonomy enumerates completely today.
    #[error("rig error: {0}")]
    Rig(String),

    /// The gateway's EAM module is not configured as a controller —
    /// every `/data/eam/api/v1/*` runtime endpoint answers 403 with
    /// "This operation can only be performed when EAM is configured
    /// as a controller" on a stock gateway (live-proven 8.3.3,
    /// 07-RESEARCH): a STATE refusal, not auth — the token is fine,
    /// the module's role is not. Message-classified at the classify
    /// seam, path-scoped to `/data/eam/` so generic 403s elsewhere
    /// cannot shift (the trial_not_expired pattern, classify
    /// edition). Exit 6 — target state.
    #[error(
        "EAM is not configured as a controller on this gateway — every EAM runtime \
         operation refuses until the module's installMode is flipped"
    )]
    EamNotController {
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// A provider-ROOT tag path (`[default]` alone, or a bare first
    /// segment that resolves to a provider) met the tagConfig route
    /// — `system.tag.getConfiguration`/`exportTags` need an RPC
    /// context WebDev threads don't carry (live-proven 8.3.3
    /// b2026012009, both gateways; 07-UAT test 12). The route
    /// refuses honestly (pre-call bracket detection + RpcContext
    /// translation for the bare form) instead of surfacing the
    /// IllegalStateException as a generic route error; subtree
    /// paths (`[default]folder`) are the supported form. Exit 6 —
    /// target state: a platform limitation, not a bug.
    #[error(
        "provider-root tag paths are not supported by the deployed route (the gateway needs an \
         RPC context WebDev threads don't carry) — target a subtree like [provider]folder"
    )]
    ProviderRootUnsupported {
        /// URL of the tagConfig route request, when known.
        endpoint: Option<String>,
    },

    /// An `eam task new` whose type is in the REFUSED set —
    /// `eam_restoreBackup`, `eam_installModules`, `eam_remoteUpgrade`
    /// are fleet-destructive (they push backups/modules/upgrades to
    /// every AGENT target), and the CLI refuses them outright over
    /// guard-everything: honest refusal with the v2 scope pointer
    /// (the planner-locked create ladder's top rung). Exit 6 —
    /// target state (additive slug alongside Task 2's).
    #[error(
        "EAM task type {task_type} is fleet-destructive — refused (restore/install/upgrade \
         are EXT-03 (v2) scope; run them from the EAM console)"
    )]
    EamTaskTypeRefused {
        /// The refused `profile.type` token.
        task_type: String,
    },

    /// An `eam task force` whose slot a leftover run occupies — the
    /// force route answers 409 with the gateway's own Jetty page
    /// ("Task 'X (forced)' already exists! It must be completed or
    /// deleted before another task of this type can be force
    /// executed."; live-captured 8.3.3, 07-UAT test 7). Exit 6 —
    /// target state (the `session_not_prunable` precedent,
    /// force-route edition): the gateway's state refused the command,
    /// not a bug; classify()'s path-scoped 409 arm constructs this.
    #[error("EAM task {task} has a run in flight — the gateway refused the force: {detail}")]
    EamTaskInFlight {
        /// The forced task's name (the force URL's last segment).
        task: String,
        /// The gateway's Jetty page message verbatim when sniffed;
        /// the '(forced)' fallback text otherwise.
        detail: String,
        /// URL of the refused force POST, when known.
        endpoint: Option<String>,
    },

    /// The scriptExec route is not configured for this profile — no
    /// webdev secret is persisted, which can only mean `ign webdev
    /// deploy --with-script-exec` has never run (deploy persists the
    /// secret 0600 BEFORE upload, so a deployed route without a
    /// stored secret is not a reachable state). `ign script run`'s
    /// opt-in is STRUCTURAL — the deploy flag — so the verb carries
    /// no `--yes` guard and refuses here instead (07-03, SCRPT-01:
    /// the TrialNotExpired precedent — action-constructed, not
    /// classify). Exit 6 — target state.
    #[error(
        "scriptExec is not configured for profile {profile:?} — the secret-gated route deploys \
         only via the explicit opt-in"
    )]
    ScriptExecNotConfigured {
        /// The profile whose secret store is empty.
        profile: String,
    },

    /// `ign lint` found no `ignition-lint` executable on PATH — the
    /// delegation has nothing to delegate to (07-04, INTR-02). The
    /// hint carries the install command + repo. Exit 6 — target
    /// state (additive slug; the environment lacks the tool, the
    /// command is fine).
    #[error("ignition-lint is not installed (no executable found on PATH)")]
    LintToolAbsent,

    /// `ign e2e init` found no `node` executable on PATH — the scaffold
    /// it would write is unusable without one (QUICK-tg4).
    ///
    /// Exit 6, mirroring [`Self::LintToolAbsent`] line for line: this
    /// is the SAME shape — a local external tool a verb delegates to is
    /// absent, with an install hint. It deliberately does NOT join
    /// exit 7, whose sole slug is `rig_error` for docker/compose rig
    /// failures; putting a missing Node there would force a relabel of
    /// a locked exit class.
    #[error("{tool} is not installed (no executable found on PATH)")]
    NodeToolAbsent {
        /// The tool that was looked for (`node`).
        tool: String,
    },

    /// The gateway answered the api call with a 4xx this CLI does not
    /// curate — the caller's request is the problem, and the body is
    /// theirs to read. Exit 2 (usage class; additive slug — the
    /// poll_interval_too_small precedent: same class, own slug, no new
    /// exit code). Constructed ONLY by the api-call-scoped classify arm
    /// (09-01: the `api_call` parameter) — a curated command's 4xx keeps
    /// its existing classification (the catch-all cannot fire without
    /// the parameter). The body is the gateway's answer VERBATIM,
    /// truncated at [`GATEWAY_CLIENT_BODY_CAP_BYTES`] with the explicit
    /// [`GATEWAY_CLIENT_BODY_TRUNCATION_MARKER`] via [`truncate_api_body`]
    /// at construction.
    #[error("gateway rejected the api call (HTTP {status} from {endpoint}): {body}")]
    GatewayClientError {
        /// HTTP status the gateway answered with.
        status: u16,
        /// Full URL of the rejected request.
        endpoint: String,
        /// The response body VERBATIM, truncated at
        /// [`GATEWAY_CLIENT_BODY_CAP_BYTES`] with an explicit marker.
        body: String,
    },

    /// No diagnostics bundle is available — the status poll ANSWERED
    /// with a captured TERMINAL steady state meaning "no current
    /// bundle" (`Invalid`: live-proven on 8.3.6 rig ign-p9-836,
    /// 2026-09-07 UAT / 09-UAT.md Gap 3 — a `Valid` bundle decays to
    /// `Invalid` within ~2 minutes UNPROMPTED and stays `Invalid`;
    /// only a fresh generate changes it, polling cannot). Exit 6 —
    /// target state (the `ImportDenied` precedent: a gateway-answered
    /// refusal riding its own class, action-constructed by `bundle
    /// wait`'s probe, not classify).
    #[error(
        "no diagnostics bundle available (gateway reports state {state:?}) — run \
         `ign diagnostics bundle generate` first; polling cannot change this state"
    )]
    BundleNotAvailable {
        /// The observed steady state (the captured unavailable
        /// vocabulary, e.g. `Invalid`).
        state: String,
    },

    /// Transport failure reaching a third-party module release feed or
    /// its asset CDN — DNS/connect/timeout/TLS (Phase 15, D-06). Exit 4:
    /// same network class as [`Self::Network`], but a SEPARATE slug and
    /// wording — `Network`'s Display hard-codes "gateway unreachable",
    /// which is actively wrong here (`api.github.com` is not a gateway,
    /// and the user's own gateway may be perfectly reachable). This is
    /// the offline signal `fetch_and_verify` returns when the cache is
    /// empty (SC-4's negative half).
    #[error(
        "module release feed at {url} is unreachable{source_note}",
        source_note = source.as_ref().map(|source| format!(": {source}")).unwrap_or_default()
    )]
    ModuleFeedUnreachable {
        /// The feed or CDN URL that could not be reached.
        url: String,
        #[source]
        source: Option<reqwest::Error>,
    },

    /// No release exists for the pinned tag, or the release carries no
    /// asset of the expected name (Phase 15, SC-1's "unknown version"
    /// refusal). Exit 6 — target state: names BOTH the requested version
    /// and the resolved URL, and (for a missing asset) both the expected
    /// asset name and the names actually present, so the caller never
    /// has to guess which lookup failed or falls back to "latest".
    #[error("module {module:?} version {version:?} not found at {url}: {detail}")]
    ModuleReleaseNotFound {
        /// The [`crate::module::ModuleSpec::id`] being fetched.
        module: String,
        /// The requested version string.
        version: String,
        /// The tag-pinned releases URL that was queried.
        url: String,
        /// What specifically was missing (no release for the tag, or no
        /// matching asset — names the asset actually present).
        detail: String,
    },

    /// Downloaded bytes hash to something other than the release's
    /// published digest — SC-2's hard refusal (Phase 15; this variant is
    /// defined in 15-01, the branch is exercised starting 15-02). Exit 6
    /// — target state: the feed answered and served bytes, but what it
    /// served cannot be trusted. The bytes are discarded (never
    /// persisted to the cache) and BOTH digests are named.
    ///
    /// Payload is BOXED: five inline `String`s put `CoreError` at
    /// exactly clippy's 128-byte `result_large_err` threshold, which
    /// fails `-D warnings` in every crate returning `Result<_,
    /// CoreError>` — `ignition-tui` first. Error paths are cold, so one
    /// allocation on construction is the cheap side of that trade.
    #[error("{0}")]
    ModuleDigestMismatch(Box<ModuleDigestMismatchDetails>),

    /// The module release feed ANSWERED but not usably — rate-limited,
    /// unauthenticated 401/403, 5xx, an unparseable body, an asset with
    /// no published digest, or an insecure downgrade of the asset URL
    /// (Phase 15). Exit 6 — target state: distinct from
    /// [`Self::ModuleFeedUnreachable`] (exit 4 — transport never reached
    /// the feed at all); here the feed DID answer, just not with
    /// something `ign` can safely act on.
    #[error("module release feed at {url} is unusable: {detail}")]
    ModuleFeedUnusable {
        /// The feed or asset URL that answered unusably.
        url: String,
        /// What specifically made the answer unusable.
        detail: String,
    },

    /// A pinned version's upstream digest differs from what's already
    /// cached — D-02's default refusal on `FetchPolicy::Refresh` /
    /// `AcceptUpstreamChange` (Phase 15, 15-02): the feed answered
    /// fine, but what it currently publishes for this version no
    /// longer matches what was verified and cached before. Exit 6 —
    /// target state: names BOTH full digests and the path of the
    /// cached artifact, which is left on disk UNTOUCHED (no path in
    /// `module/` deletes, truncates, or overwrites a cache entry).
    /// `FetchPolicy::AcceptUpstreamChange` is the explicit, documented
    /// override.
    ///
    /// Payload is BOXED for the same reason as
    /// [`Self::ModuleDigestMismatch`] — see that variant.
    #[error("{0}")]
    ModuleDigestChanged(Box<ModuleDigestChangedDetails>),

    /// A declared module id has no matching registry entry (Phase 16,
    /// D-13). A well-formed id that simply isn't registered is a CONFIG
    /// problem, not malformed input (exit 2 belongs to
    /// `validate_module_id`/`validate_version`) and not a Docker
    /// failure (exit 7 is [`Self::Rig`]) — every OTHER module
    /// provisioning refusal (missing artifact, non-file artifact,
    /// relative path, underivable service) stays `CoreError::Rig`.
    /// Exit 3, structurally the [`Self::ProfileNotFound`] shape: names
    /// both the bad id and every id that IS registered.
    #[error("module {id:?} is not registered (known modules: {known:?})")]
    ModuleNotRegistered {
        /// The declared id with no matching [`crate::module::ModuleSpec`].
        id: String,
        /// Every currently registered [`crate::module::ModuleSpec::id`].
        known: Vec<String>,
    },

    /// The gateway ANSWERED `DELETE /data/api/v1/modules/uninstall` with
    /// HTTP 200 but the body says `{"success": false, "failedUninstalls":
    /// {"uninstall": […]}}` — the denial-rides-200 class
    /// ([`Self::ImportDenied`]'s precedent) applied to module uninstall
    /// (Phase 19, D-19-03): live-verified that a stock module, a bogus
    /// id, and a still-mounted module ALL answer 200 with
    /// `success:false`. An unparseable body, a missing `success`, or an
    /// absent `failedUninstalls` all map here too — absence of detail
    /// must never degrade into a reported success. Exit 6 — target
    /// state: names both the registry id and the gateway id that was
    /// sent, plus every failed id the gateway reported (or the sent id
    /// itself when the gateway gave no detail).
    #[error(
        "gateway refused to uninstall module {module_id:?} ({gateway_module_id}): {}",
        failed.join(", ")
    )]
    ModuleUninstallDenied {
        /// The registry slug (`git`) the caller named.
        module_id: String,
        /// The gateway's own id ([`crate::module::ModuleSpec::gateway_module_id`])
        /// sent in the request.
        gateway_module_id: String,
        /// `failedUninstalls.uninstall` verbatim, or `[gateway_module_id]`
        /// when the gateway's body carried no usable detail.
        failed: Vec<String>,
        /// URL of the refused DELETE, when known.
        endpoint: Option<String>,
    },

    /// Another actor holds the gateway's scan-lock. Exit 6 — target
    /// state. Constructed by the route-scoped scan-lock arm in
    /// classify.rs (20-03); `kind` is `config` or `projects`. `actor`
    /// is the holder's opaque identity string when the gateway named
    /// it (`api-token:<name>:<ip>`), echoed and never parsed; `None`
    /// when the refusal did not name one.
    #[error(
        "the {kind} scan-lock is held by {}",
        actor.as_deref().unwrap_or("another actor")
    )]
    ScanLockHeld {
        /// The holder's identity string, when the gateway named it.
        actor: Option<String>,
        /// Which scan-lock: `config` or `projects`.
        kind: String,
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// The gateway refused a resource write over its signature. Exit 6 —
    /// target state. Constructed ONLY by the deploy-scoped write helper
    /// in client/deploy_api.rs (20-04), never by classify.rs, so the
    /// v1.1 EAM 500 pin stays exit 1 `internal`. The payload
    /// deliberately carries no signature and no gateway problem text:
    /// 8.3.3 problem messages leak the live signature.
    #[error("gateway refused the write to resource {name:?}: {reason} signature")]
    ResourceSignatureRejected {
        /// The resource name that was being written.
        name: String,
        /// Why the signature was refused.
        reason: SignatureReason,
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// A resource create named a resource that already exists. Exit 6 —
    /// target state. Constructed ONLY by the deploy-scoped create helper
    /// in client/deploy_api.rs from the live 409 JSON `problem` body
    /// (20-LIVE-CAPTURES D10), never by classify.rs. The payload carries
    /// no gateway problem text or stacktrace.
    #[error("resource {name:?} already exists")]
    ResourceExists {
        /// The resource name that was being created.
        name: String,
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// A deployment-mode create named a mode that is already defined.
    /// Exit 6 — target state. Constructed ONLY by the deploy-scoped mode
    /// create in client/deploy_api.rs from the live 409 (D6).
    #[error("deployment mode {name:?} is already defined")]
    ModeExists {
        /// The mode name that was being created.
        name: String,
        /// URL of the refused request, when known.
        endpoint: Option<String>,
    },

    /// A declared gateway tree failed render validation (21-03): one or
    /// more findings, each naming its file and, for YAML syntax and
    /// schema defects, a line and column. Exit 2 — usage class: the
    /// CALLER authored the tree and must fix it. Render is offline, so
    /// there is no endpoint. Boxed to keep `CoreError` under clippy's
    /// `result_large_err` threshold.
    #[error("deploy tree invalid: {0}")]
    DeployTreeInvalid(Box<DeployTreeInvalidDetails>),

    /// A declared tree carries an Embedded or plaintext secret (21-03).
    /// Exit 2 — usage class. The payload holds JSON paths and other
    /// findings only: no field exists that could carry a secret value.
    #[error("refusing to render an embedded or plaintext secret: {0}")]
    EmbeddedSecret(Box<EmbeddedSecretDetails>),

    /// A deploy host transport could not read (or later write) a node's
    /// gateway data directory (22-01): a missing or unreadable directory, a
    /// hostile live tree (symlink, special file, non-UTF-8 name), a size cap
    /// breach or an ssh failure. Exit 4 — network class: the host could not
    /// be reached or read. A failed read is NEVER an empty result, so a plan
    /// cannot mistake an unreadable tree for deletions. `detail` names paths
    /// and causes only, never file content.
    #[error("transport failed ({operation}) on {node}: {detail}")]
    TransportFailed {
        /// What was being done, e.g. `read`.
        operation: String,
        /// The target node label, e.g. `nodes.master`.
        node: String,
        /// What went wrong; names paths and causes, never file content.
        detail: String,
    },

    /// The on-box declared-names ledger exists but cannot be trusted (22-03,
    /// D-07): unreadable, empty, over its size cap, not strict UTF-8 JSON, of
    /// another schema version, naming another gateway or mode, unsorted or
    /// duplicated, or listing a path plan must never delete. Exit 6 -
    /// target_state class: the on-box state is wrong, not the caller's input.
    /// Plan never falls back to an empty delete set. `problem` names fields
    /// and listed paths only, never other file content.
    #[error("declared-names ledger {location} is unusable: {problem}")]
    DeployLedgerInvalid {
        /// The ledger location relative to the node's data directory.
        location: String,
        /// What is wrong; names fields and listed paths, never file content.
        problem: String,
    },

    /// The plan the caller reviewed is no longer the plan (23-02, DAPL-02):
    /// `--plan-sha256` differs from the recomputed `plan_sha256`, or the
    /// on-box pre-image changed under the scan lock. Exit 6 - target_state
    /// class: the gateway moved since the review. Carries hashes only.
    #[error("plan changed since review: expected plan_sha256 {expected}, now {actual} ({detail})")]
    PlanStale {
        /// The `plan_sha256` the caller reviewed.
        expected: String,
        /// The `plan_sha256` of the plan as it is now.
        actual: String,
        /// Where the mismatch was found, e.g. `review hash`; no file content.
        detail: String,
    },

    /// A destructive or drifted plan was applied without its flag (23-02,
    /// DAPL-02). Exit 2 - usage class: the caller must pass
    /// `--allow-destructive` or `--allow-drift <reason>`. Carries unit keys
    /// and counts only.
    #[error("{}", destructive_change_refused_text(.gate, .keys, *.count))]
    DestructiveChangeRefused {
        /// Which gate refused: `destructive` or `drift`.
        gate: String,
        /// The first [`APPLY_LIST_SHOWN`] offending unit keys, byte-sorted.
        keys: Vec<String>,
        /// How many entries the gate refused in all.
        count: usize,
    },

    /// A removal that cannot take effect (23-02, DAPL-01): the unit's `core`
    /// copy shadows the mode collection, so deleting from the mode collection
    /// changes nothing. No flag permits it. Exit 6.
    #[error("{}", deploy_blocked_text(.keys))]
    DeployBlocked {
        /// The `shadows_removal` unit keys, byte-sorted.
        keys: Vec<String>,
    },

    /// An apply would write, check or delete a unit whose live copy the
    /// host's sftp server cannot read (quick-261029-ms3): a host path of 240
    /// characters or more, so the live copy is unknown and must never be
    /// taken as absent. Raised when an unreadable unit is declared or listed
    /// in the declared-names ledger, on the master by the plan's gate, and on
    /// the backup by the `backup_read` preflight (a unit the apply writes or
    /// deletes that the backup cannot read, WR-02). No flag permits it. Exit
    /// 6.
    #[error("{}", deploy_unreadable_text(.node, .keys))]
    DeployUnreadable {
        /// The node whose host cannot read the units: `master` or `backup`.
        node: String,
        /// The unreadable unit keys that are declared or in the ledger,
        /// byte-sorted.
        keys: Vec<String>,
    },

    /// One or more apply preflight checks failed (23-02, DAPL-04). Exit 6.
    /// Nothing was written to the gateway. The payload is BOXED so the large
    /// list stays off every `Result<_, CoreError>`.
    #[error("{}", deploy_preflight_failed_text(.failures))]
    DeployPreflightFailed {
        /// Every failed check, in the order the checks ran.
        failures: Box<[PreflightFailure]>,
    },

    /// An interrupted deploy left its journal on the box (23-02, D-09). Exit
    /// 6. The message, not the hint, carries the recovery command.
    #[error(
        "an interrupted deploy left the journal {location} for run {run_id}; \
         recover it with: ign deploy rollback --run {run_id} --env {env}"
    )]
    DeployJournalPresent {
        /// The interrupted run.
        run_id: String,
        /// The `--env` value the recovery command needs.
        env: String,
        /// The on-box journal location.
        location: String,
    },

    /// Live files changed after the run wrote them, so a rollback would
    /// overwrite someone's edit (23-02, DAPL-07). Exit 6. Carries paths and
    /// counts only.
    #[error("{}", deploy_live_changed_text(.run_id, .paths, *.count))]
    DeployLiveChanged {
        /// The run being rolled back.
        run_id: String,
        /// The first [`APPLY_LIST_SHOWN`] changed paths, byte-sorted.
        paths: Vec<String>,
        /// How many touched paths changed in all.
        count: usize,
    },

    /// A run's record or snapshot cannot be trusted (23-02, D-04). Exit 6.
    /// `problem` names fields and paths only, never file content.
    #[error("deploy run {run_id} is unusable: {problem}")]
    DeployRunInvalid {
        /// The run id asked for.
        run_id: String,
        /// What is wrong.
        problem: String,
    },

    /// A rollback could not restore the pre-apply files (23-02, D-12).
    /// Exit 6. Boxed to keep `CoreError` under clippy's `result_large_err`.
    #[error("{0}")]
    RollbackFailed(Box<RollbackFailure>),

    /// `deploy projects` refused a project the git module still manages
    /// (25-07, DPRJ-04, D-11): the project's `.git` entry exists on the
    /// gateway host. Exit 6 - target_state class: the gateway is not in a
    /// state this deploy may touch. The tool never deletes a `.git`; an
    /// administrator removes it per project. Carries the project name, the
    /// location below the data directory and the kind (`directory`, `file`,
    /// `symlink`, `other`) only.
    #[error(
        "project {project} is still managed by the git module: {location} is present ({kind}); an administrator removes it before this project is deployed"
    )]
    ProjectGitManaged {
        /// The gateway project name.
        project: String,
        /// The `.git` path below the node's data directory.
        location: String,
        /// What the entry is.
        kind: String,
    },

    /// `deploy projects` refused a project whose parent cannot be used
    /// (25-10, DPRJ-02, D-05, K6): the parent named in the repo's
    /// `project.json` is missing on the gateway, closes a cycle, or is not
    /// inheritable. Exit 6 - target_state class: the gateway is not in a
    /// state this deploy may build on. Carries names and the reason word
    /// (`missing`, `cycle`, `not_inheritable`) only. The parent is only read.
    #[error("project {project} cannot be deployed under parent {parent}: {reason}")]
    ProjectParentInvalid {
        /// The gateway project being deployed.
        project: String,
        /// The parent named in the repo's `project.json`.
        parent: String,
        /// `missing`, `cycle` or `not_inheritable`.
        reason: String,
    },

    /// `deploy projects` refused an artifact that is not the one that was
    /// reviewed (25-11, SC-1, D-01, V1): `--artifact-sha256` differs from the
    /// canonical digest of the artifact the checkout builds. Exit 6 -
    /// target_state class: the checkout is not in the state the reviewer saw.
    /// The comparison runs after the local build and before any host or
    /// gateway contact, so nothing was uploaded. Carries the project name and
    /// the two hashes only.
    #[error(
        "artifact hash mismatch for project {project}: expected {expected}, the checkout builds {actual}; nothing was uploaded"
    )]
    ProjectHashMismatch {
        /// The gateway project name.
        project: String,
        /// The `--artifact-sha256` the caller reviewed.
        expected: String,
        /// The canonical digest of the artifact this checkout builds.
        actual: String,
    },
}

/// Items listed inline by the Phase 23 refusal Displays; the rest collapse
/// into `and {m} more`.
pub const APPLY_LIST_SHOWN: usize = 10;

/// One failed apply preflight check (23-02). `detail` carries no value from
/// the gateway, the host or the repo that could be a secret.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreflightFailure {
    /// The check id, e.g. `mode_master` or `run_dir_not_ignored`.
    pub check: String,
    /// What failed, value-free.
    pub detail: String,
}

/// Payload of [`CoreError::RollbackFailed`] (23-02).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RollbackFailure {
    /// The run being restored.
    pub run_id: String,
    /// The `--env` value the retry command needs.
    pub env: String,
    /// The local run directory holding the snapshot, when one was made.
    pub run_dir: Option<String>,
    /// The on-box journal path, left in place for a manual recovery.
    pub journal: String,
    /// Why the restore failed; names paths and causes, never file content.
    pub cause: String,
}

impl RollbackFailure {
    /// The on-box directory holding the run's pre-images
    /// (`snapshots/<run>/`), next to the journal.
    pub fn snapshot_dir(&self) -> String {
        match self.journal.rsplit_once('/') {
            Some((dir, _)) => format!("{dir}/snapshots/{}/", self.run_id),
            None => format!("snapshots/{}/", self.run_id),
        }
    }
}

impl std::fmt::Display for RollbackFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The run directory's `snapshot/` is made only after a restore has
        // succeeded, so it is never offered here: the intact pre-images are
        // the on-box `snapshots/<run>/` directory and, when one was taken, the
        // `.gwbk`.
        write!(
            f,
            "rollback of run {run} failed ({cause}); the gateway files may be half restored. \
             Retry with: ign deploy rollback --run {run} --env {env} (the journal at {journal} \
             and the snapshot are still on the host). If the retry reports a lost or damaged \
             snapshot, restore the files from the .gwbk backup (when this run took one) or from \
             the on-box snapshot {snapshot}, then delete the journal by hand. \
             run directory: {run_dir}",
            run = self.run_id,
            cause = self.cause,
            env = self.env,
            journal = self.journal,
            snapshot = self.snapshot_dir(),
            run_dir = self.run_dir.as_deref().unwrap_or("none was created"),
        )
    }
}

/// `a, b, c and {m} more`: `shown` capped at [`APPLY_LIST_SHOWN`], then the
/// remainder of `total`.
fn listed(shown: &[String], total: usize) -> String {
    let take = shown.len().min(APPLY_LIST_SHOWN);
    let mut out = shown[..take].join(", ");
    if total > take {
        out.push_str(&format!(" and {} more", total - take));
    }
    out
}

fn destructive_change_refused_text(gate: &str, keys: &[String], count: usize) -> String {
    let (flag, verb) = match gate {
        "drift" => ("--allow-drift <reason>", "apply"),
        "downgrade" => ("--allow-downgrade", "deploy projects"),
        "first_deploy" => ("--allow-first-change <reason>", "deploy projects"),
        _ => ("--allow-destructive", "apply"),
    };
    format!(
        "{gate} change refused for {count} entr{}: {}; {verb} needs {flag}",
        if count == 1 { "y" } else { "ies" },
        listed(keys, count)
    )
}

fn deploy_blocked_text(keys: &[String]) -> String {
    format!(
        "deploy blocked: {} unit(s) are removed from the declared tree but a core copy \
         shadows them, so deleting them from the mode collection cannot take effect: {}",
        keys.len(),
        listed(keys, keys.len())
    )
}

fn deploy_unreadable_text(node: &str, keys: &[String]) -> String {
    format!(
        "deploy refused: {} unit(s) the deploy would write or delete have a live path the \
         {node} host's sftp server cannot read, so their live copy is unknown: {}; nothing was \
         written",
        keys.len(),
        listed(keys, keys.len())
    )
}

fn deploy_preflight_failed_text(failures: &[PreflightFailure]) -> String {
    let mut out = format!("deploy preflight failed ({} check(s)):", failures.len());
    for failure in failures {
        out.push_str(&format!("\n  {}: {}", failure.check, failure.detail));
    }
    out
}

fn deploy_live_changed_text(run_id: &str, paths: &[String], count: usize) -> String {
    format!(
        "live files changed since run {run_id} wrote them ({count}): {}; restoring the \
         snapshot would overwrite them",
        listed(paths, count)
    )
}

/// Findings shown inline by the deploy error Displays; the rest collapse
/// into `and {m} more`.
pub const DEPLOY_FINDINGS_SHOWN: usize = 20;

/// One defect in a declared deploy tree (21-03).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeployFinding {
    /// Collection-relative file the finding is about.
    pub file: String,
    /// 1-based line, when the defect has a source position.
    pub line: Option<usize>,
    /// 1-based column, when the defect has a source position.
    pub column: Option<usize>,
    /// What is wrong. Never contains a value read from the tree.
    pub message: String,
}

impl std::fmt::Display for DeployFinding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (self.line, self.column) {
            (Some(line), Some(column)) => {
                write!(f, "{}:{line}:{column}: {}", self.file, self.message)
            }
            _ => write!(f, "{}: {}", self.file, self.message),
        }
    }
}

/// Payload of [`CoreError::DeployTreeInvalid`], boxed to keep
/// `CoreError` under clippy's `result_large_err` threshold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeployTreeInvalidDetails {
    /// Every finding, in discovery order.
    pub findings: Vec<DeployFinding>,
}

impl std::fmt::Display for DeployTreeInvalidDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let [only] = self.findings.as_slice() {
            return write!(f, "{only}");
        }
        write!(f, "{} findings: ", self.findings.len())?;
        write_findings(f, &self.findings, DEPLOY_FINDINGS_SHOWN)
    }
}

/// Write `findings` joined by `; `, at most `shown` of them, then
/// `; and {m} more` when truncated.
fn write_findings(
    f: &mut std::fmt::Formatter<'_>,
    findings: &[DeployFinding],
    shown: usize,
) -> std::fmt::Result {
    for (i, finding) in findings.iter().take(shown).enumerate() {
        if i > 0 {
            f.write_str("; ")?;
        }
        write!(f, "{finding}")?;
    }
    if findings.len() > shown {
        write!(f, "; and {} more", findings.len() - shown)?;
    }
    Ok(())
}

/// Payload of [`CoreError::EmbeddedSecret`], boxed to keep `CoreError`
/// under clippy's `result_large_err` threshold. Carries locations only:
/// there is deliberately no field that can hold a secret value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddedSecretDetails {
    /// Each entry is `<collection-relative file>: <dotted json path>`.
    pub paths: Vec<String>,
    /// Non-secret tree findings discovered in the same render.
    pub other_findings: Vec<DeployFinding>,
}

impl std::fmt::Display for EmbeddedSecretDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "embedded secret at {} path(s): ", self.paths.len())?;
        let shown_paths = self.paths.len().min(DEPLOY_FINDINGS_SHOWN);
        f.write_str(&self.paths[..shown_paths].join("; "))?;
        if self.paths.len() > shown_paths {
            write!(f, "; and {} more", self.paths.len() - shown_paths)?;
        }
        if !self.other_findings.is_empty() {
            write!(
                f,
                "; also {} other tree finding(s): ",
                self.other_findings.len()
            )?;
            // The combined list stays within DEPLOY_FINDINGS_SHOWN entries.
            let room = DEPLOY_FINDINGS_SHOWN.saturating_sub(shown_paths);
            write_findings(f, &self.other_findings, room)?;
        }
        Ok(())
    }
}

/// Why a resource write's signature was refused
/// ([`CoreError::ResourceSignatureRejected`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureReason {
    /// The gateway refused a signature that no longer matches: the
    /// resource changed since it was read.
    Stale,
    /// No usable signature was supplied: either refused before any
    /// request because it was empty, or a gateway refusal that the live
    /// capture shows is distinguishable.
    Missing,
}

impl std::fmt::Display for SignatureReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Stale => "stale",
            Self::Missing => "missing",
        })
    }
}

/// Payload of [`CoreError::ModuleDigestMismatch`], boxed to keep
/// `CoreError` under clippy's `result_large_err` threshold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleDigestMismatchDetails {
    /// The [`crate::module::ModuleSpec::id`] being fetched.
    pub module: String,
    /// The requested version string.
    pub version: String,
    /// The asset URL the mismatched bytes were downloaded from.
    pub url: String,
    /// The release's published sha256 digest.
    pub expected: String,
    /// The sha256 digest of the bytes actually downloaded.
    pub actual: String,
}

/// Payload of [`CoreError::ModuleDigestChanged`], boxed to keep
/// `CoreError` under clippy's `result_large_err` threshold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModuleDigestChangedDetails {
    /// The [`crate::module::ModuleSpec::id`] being fetched.
    pub module: String,
    /// The requested version string.
    pub version: String,
    /// The digest of the artifact already cached for this version.
    pub cached_digest: String,
    /// The digest the feed currently publishes for this version.
    pub upstream_digest: String,
    /// Path of the untouched, still-usable cached artifact.
    pub cached_path: String,
}

impl std::fmt::Display for ModuleDigestMismatchDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "module {:?} version {:?} digest mismatch at {}: expected {}, got {}",
            self.module, self.version, self.url, self.expected, self.actual
        )
    }
}

impl std::fmt::Display for ModuleDigestChangedDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "module {:?} version {:?} digest changed upstream: cached {}, \
             upstream now reports {} (cached artifact kept at {})",
            self.module, self.version, self.cached_digest, self.upstream_digest, self.cached_path
        )
    }
}

impl CoreError {
    /// Stable machine slug — public contract, never respell.
    pub fn code(&self) -> &'static str {
        match self {
            Self::Internal(_) => "internal",
            Self::ConfirmationRequired { .. } => "confirmation_required",
            Self::ProfilingRiskNotAccepted { .. } => "profiling_risk_not_accepted",
            Self::InvalidImportFile { .. } => "invalid_import_file",
            Self::ImportDenied { .. } => "import_denied",
            Self::InvalidInput { .. } => "invalid_input",
            Self::ProfileNotFound { .. } => "profile_not_found",
            Self::NoActiveProfile => "no_active_profile",
            Self::SecretUnavailable { .. } => "secret_unavailable",
            Self::PasswordUnavailable { .. } => "password_unavailable",
            Self::ConfigInvalid { .. } => "config_invalid",
            Self::PollIntervalTooSmall { .. } => "poll_interval_too_small",
            Self::Network { .. } => "network_error",
            Self::Auth { .. } => "auth_rejected",
            Self::GatewayTooOld { .. } => "gateway_too_old",
            Self::GatewayNotCommissioned { .. } => "gateway_not_commissioned",
            Self::GatewayRestarting { .. } => "gateway_restarting",
            Self::NotFound { .. } => "not_found",
            Self::ProjectExists { .. } => "project_exists",
            Self::ResourceBinary { .. } => "resource_binary",
            Self::TrialNotExpired { .. } => "trial_not_expired",
            Self::ProviderNotFound { .. } => "provider_not_found",
            Self::RoutesNotDeployed { .. } => "routes_not_deployed",
            Self::WebdevUnlicensed { .. } => "webdev_unlicensed",
            Self::RouteVersionMismatch { .. } => "route_version_mismatch",
            Self::WebdevRouteError { .. } => "webdev_route_error",
            Self::TagCollision { .. } => "tag_collision",
            Self::AlarmJournalMissing { .. } => "alarm_journal_missing",
            Self::SessionNotPrunable { .. } => "session_not_prunable",
            Self::Rig(_) => "rig_error",
            Self::EamNotController { .. } => "eam_not_controller",
            Self::ProviderRootUnsupported { .. } => "provider_root_unsupported",
            Self::EamTaskTypeRefused { .. } => "eam_task_type_refused",
            Self::EamTaskInFlight { .. } => "eam_task_in_flight",
            Self::ScriptExecNotConfigured { .. } => "script_exec_not_configured",
            Self::LintToolAbsent => "lint_tool_absent",
            Self::NodeToolAbsent { .. } => "node_tool_absent",
            Self::GatewayClientError { .. } => "gateway_client_error",
            Self::BundleNotAvailable { .. } => "bundle_not_available",
            Self::ModuleFeedUnreachable { .. } => "module_feed_unreachable",
            Self::ModuleReleaseNotFound { .. } => "module_release_not_found",
            Self::ModuleDigestMismatch(..) => "module_digest_mismatch",
            Self::ModuleFeedUnusable { .. } => "module_feed_unusable",
            Self::ModuleDigestChanged(..) => "module_digest_changed",
            Self::ModuleNotRegistered { .. } => "module_not_registered",
            Self::ModuleUninstallDenied { .. } => "module_uninstall_denied",
            Self::ScanLockHeld { .. } => "scan_lock_held",
            Self::ResourceSignatureRejected { .. } => "resource_signature_rejected",
            Self::ResourceExists { .. } => "resource_exists",
            Self::ModeExists { .. } => "mode_exists",
            Self::DeployTreeInvalid(..) => "deploy_tree_invalid",
            Self::EmbeddedSecret(..) => "embedded_secret",
            Self::TransportFailed { .. } => "transport_failed",
            Self::DeployLedgerInvalid { .. } => "deploy_ledger_invalid",
            Self::PlanStale { .. } => "plan_stale",
            Self::DestructiveChangeRefused { .. } => "destructive_change_refused",
            Self::DeployBlocked { .. } => "deploy_blocked",
            Self::DeployUnreadable { .. } => "deploy_unreadable",
            Self::DeployPreflightFailed { .. } => "deploy_preflight_failed",
            Self::DeployJournalPresent { .. } => "deploy_journal_present",
            Self::DeployLiveChanged { .. } => "deploy_live_changed",
            Self::DeployRunInvalid { .. } => "deploy_run_invalid",
            Self::RollbackFailed(..) => "rollback_failed",
            Self::ProjectGitManaged { .. } => "project_git_managed",
            Self::ProjectParentInvalid { .. } => "project_parent_invalid",
            Self::ProjectHashMismatch { .. } => "project_hash_mismatch",
        }
    }

    /// The LOCKED exit-code mapping — the only place exit codes are decided.
    pub fn exit_code(&self) -> u8 {
        match self {
            Self::Internal(_) => 1,
            Self::ConfirmationRequired { .. }
            | Self::ProfilingRiskNotAccepted { .. }
            | Self::InvalidImportFile { .. }
            | Self::InvalidInput { .. }
            | Self::GatewayClientError { .. }
            | Self::DeployTreeInvalid(..)
            | Self::EmbeddedSecret(..)
            | Self::DestructiveChangeRefused { .. } => 2,
            Self::ProfileNotFound { .. }
            | Self::NoActiveProfile
            | Self::SecretUnavailable { .. }
            | Self::PasswordUnavailable { .. }
            | Self::ConfigInvalid { .. }
            | Self::PollIntervalTooSmall { .. }
            | Self::ModuleNotRegistered { .. } => 3,
            Self::Network { .. }
            | Self::ModuleFeedUnreachable { .. }
            | Self::TransportFailed { .. } => 4,
            Self::Auth { .. } => 5,
            Self::GatewayTooOld { .. }
            | Self::GatewayNotCommissioned { .. }
            | Self::GatewayRestarting { .. }
            | Self::NotFound { .. }
            | Self::ProjectExists { .. }
            | Self::ResourceBinary { .. }
            | Self::TrialNotExpired { .. }
            | Self::ProviderNotFound { .. }
            | Self::RoutesNotDeployed { .. }
            | Self::WebdevUnlicensed { .. }
            | Self::RouteVersionMismatch { .. }
            | Self::WebdevRouteError { .. }
            | Self::TagCollision { .. }
            | Self::AlarmJournalMissing { .. }
            | Self::SessionNotPrunable { .. }
            | Self::ImportDenied { .. }
            | Self::EamNotController { .. }
            | Self::ProviderRootUnsupported { .. }
            | Self::EamTaskTypeRefused { .. }
            | Self::EamTaskInFlight { .. }
            | Self::ScriptExecNotConfigured { .. }
            | Self::LintToolAbsent
            | Self::NodeToolAbsent { .. }
            | Self::BundleNotAvailable { .. }
            | Self::ModuleReleaseNotFound { .. }
            | Self::ModuleDigestMismatch(..)
            | Self::ModuleFeedUnusable { .. }
            | Self::ModuleDigestChanged(..)
            | Self::ModuleUninstallDenied { .. }
            | Self::ScanLockHeld { .. }
            | Self::ResourceSignatureRejected { .. }
            | Self::ResourceExists { .. }
            | Self::ModeExists { .. }
            | Self::DeployLedgerInvalid { .. }
            | Self::PlanStale { .. }
            | Self::DeployBlocked { .. }
            | Self::DeployUnreadable { .. }
            | Self::DeployPreflightFailed { .. }
            | Self::DeployJournalPresent { .. }
            | Self::DeployLiveChanged { .. }
            | Self::DeployRunInvalid { .. }
            | Self::RollbackFailed(..)
            | Self::ProjectGitManaged { .. }
            | Self::ProjectParentInvalid { .. }
            | Self::ProjectHashMismatch { .. } => 6,
            Self::Rig(_) => 7,
        }
    }

    /// Actionable next step (CORE-05). Every class carries one.
    pub fn hint(&self) -> Option<String> {
        match self {
            Self::Internal(_) => Some(
                "internal errors are bugs; re-run with -vv and report the \
                 diagnostics output"
                    .to_string(),
            ),
            Self::ConfirmationRequired { .. } => Some(
                "this operation is destructive; re-run with --yes or set \
                   IGNITION_YES=1"
                    .to_string(),
            ),
            Self::ProfilingRiskNotAccepted { .. } => Some(
                "JVM profiling ACTIVELY instruments the gateway: stack sampling \
                   adds CPU overhead proportional to thread count x frequency, \
                   and flight recordings buffer in JVM memory and write to \
                   gateway disk. On a PRODUCTION server this belongs inside an \
                   approved change window with a rollback plan — never as a \
                   casual probe. --yes deliberately does NOT satisfy this gate; \
                   re-run with --i-accept-the-risk after confirming that"
                    .to_string(),
            ),
            Self::InvalidImportFile { .. } => Some(
                "import expects a project-export ZIP (PK\\x03\\x04 magic) of at \
                   most 512 MB — pass a file produced by `ign project export` \
                   via --file (or `-` to pipe one on stdin)"
                    .to_string(),
            ),
            Self::ImportDenied { problem, .. } => Some(format!(
                "the gateway refused the import over a 200 answer — the problem \
                   text above is the gateway's own; `ign project export` of the \
                   current state is the honest baseline for hand-editing ({problem})"
            )),
            Self::InvalidInput { reason } => Some(
                if reason == TUI_TTY_REFUSAL_REASON {
                    // The ONE contextual InvalidInput hint (06-07): the
                    // TTY refusal's fix is terminal-related — the
                    // --file/stdin default is meaningless for a pipe.
                    "run `ign tui` in an interactive terminal (the cockpit \
                     needs a TTY on stdout — not a pipe or redirect)"
                } else if reason == TOP_TTY_REFUSAL_REASON {
                    // itop's sibling refusal: same terminal-contextual
                    // fix, naming the MONITOR's command (a hint naming
                    // `ign tui` would not fix an `ign top` run).
                    "run `ign top` in an interactive terminal (the monitor \
                     needs a TTY on stdout — not a pipe or redirect)"
                } else if reason.starts_with(LOSS_GATE_REFUSAL_REASON_PREFIX) {
                    // The loss-gate refusal (11-07): the message above already names
                    // every finding and ends with the actionable guidance — the hint
                    // restates it for envelope readers instead of the file-read
                    // default, which is meaningless here (the file WAS readable).
                    "the loss report above names what this import would drop or \
                     coerce — re-run with --yes to import anyway"
                } else if reason.starts_with("--plan-sha256 ")
                    || reason.starts_with("--allow-drift ")
                    || reason.starts_with("--artifact-sha256 ")
                    || reason.starts_with("--release ")
                    || reason.starts_with("--allow-first-change ")
                    || reason.starts_with("deploy projects needs --artifact-sha256")
                {
                    // The deploy apply and deploy projects gate flags (23-02,
                    // 25-11): the --file/stdin default is meaningless for a
                    // flag value.
                    "correct the flag value named above and rerun; no host or gateway \
                     was contacted"
                } else {
                    "fix the input source — a readable file path via --file, or `-` \
                     to pipe the content on stdin"
                }
                .to_string(),
            ),
            Self::ProfileNotFound { known, .. } => Some(if known.is_empty() {
                "no profiles configured yet; run `ign profile add` to create \
                     one"
                .to_string()
            } else {
                format!(
                    "known profiles: {}; run `ign profile add` to add another",
                    known.join(", ")
                )
            }),
            Self::NoActiveProfile => Some(
                "pass --profile NAME, set IGNITION_PROFILE, or mark a profile \
                 active with `ign profile use`"
                    .to_string(),
            ),
            Self::SecretUnavailable { profile } => Some(format!(
                "set IGNITION_TOKEN (or token_env in the profile), or store a \
                 keyring entry: service 'ignition-cli', user 'profile:{profile}'"
            )),
            Self::PasswordUnavailable { .. } => Some(
                "ign adopt logs in with the gateway admin password — export \
                 IGNITION_PASSWORD (env-only, never a flag)"
                    .to_string(),
            ),
            Self::ConfigInvalid { .. } => Some(
                "verify the config file is valid TOML with [profiles.NAME] \
                 tables; `ign profile add` writes a known-good one"
                    .to_string(),
            ),
            Self::PollIntervalTooSmall { profile } => Some(format!(
                "set poll_interval_secs to 1 or higher in [profiles.{profile}], \
                 or remove the key to use the default cadence"
            )),
            Self::Network {
                url,
                observation,
                ..
            } => Some(match observation {
                Some(observation) => format!(
                    "the gateway answered but no terminal state arrived before the deadline — \
                     the last observation was: {observation}; address that state, not the \
                     connection ({url})"
                ),
                None => format!("check the gateway is reachable at {url} (host, port, VPN, TLS)"),
            }),
            Self::Auth { status, .. } => Some(match status {
                401 => {
                    // 401 = token not recognized — the #1 setup failure is
                    // a key-only header (verified: key-only → 401, full
                    // `name:key` → 200; Basic is dead on 8.3 /data).
                    "token not recognized — the X-Ignition-API-Token header must be the FULL `name:key` string from the gateway UI (Platform→Security→API Keys); Basic auth does not work on 8.3 /data routes — create an API token"
                }
                403 => {
                    // 403 = recognized but under-permitted (verified
                    // semantics; see 02-RESEARCH Auth §4/§5).
                    "token recognized but under-permitted — Ignition token setup is three parts: (1) token holds an adequate security level, (2) gateway read/write permissions include that level, (3) 'Require secure connections' is unchecked for http gateways; run `ign doctor` for a diagnosis"
                }
                _ => "check the credential; Ignition token setup is three parts: security level, write permissions, token assignment",
            }
            .to_string()),
            Self::GatewayTooOld { minimum, .. } => {
                Some(format!("upgrade the gateway to at least {minimum}"))
            }
            Self::GatewayNotCommissioned { .. } => Some(
                "open http://<host>:<port>/welcome in a browser and complete the \
                 commissioning wizard"
                    .to_string(),
            ),
            Self::GatewayRestarting { .. } => Some(
                "wait for readiness with `ign wait restart` or retry in ~1 minute".to_string(),
            ),
            Self::NotFound { .. } => Some(
                "check the id/path; a 404 JSON 'No route match' body can also mean \
                  a pre-8.3 gateway"
                    .to_string(),
            ),
            Self::ProjectExists { .. } => Some(
                "the default collision policy refuses to overwrite; re-run with \
                  --collision-policy overwrite to replace it — overwrite \
                  REPLACES the ENTIRE project (resources absent from the ZIP \
                  are deleted; merge is Designer-only)"
                    .to_string(),
            ),
            Self::ResourceBinary { .. } => Some(
                "resource content is binary — use `ign project export`/`import` \
                  for data.bin-class resources"
                    .to_string(),
            ),
            Self::TrialNotExpired { .. } => Some(
                "wait for the trial to expire (watch `ign rig trial status`), or \
                  run `ign rig reset --yes` for a completely fresh trial volume"
                    .to_string(),
            ),
            Self::RoutesNotDeployed { route, .. } => Some(
                // CONTENT-ADDRESSED off the route (the
                // TUI_TTY_REFUSAL_REASON / loss-gate prose-prefix
                // pattern, same file): the testing bundle is a
                // SEPARATE deploy with its own flag, so the generic
                // `ign webdev deploy` hint would send the caller to a
                // command that does not install it. No new variant,
                // no new slug — the exit tables are untouched.
                if route.starts_with(TESTING_ROUTE_PREFIX) {
                    "run `ign webdev deploy --with-testing` to install the gateway \
                      testing bundle into the project (or bootstrap it in one shot \
                      with `ign adopt --project NAME --testing`), then retry"
                } else {
                    "run `ign webdev deploy` to install the CLI's WebDev routes into \
                      the gateway, then retry"
                }
                .to_string(),
            ),
            Self::WebdevUnlicensed { .. } => Some(
                "license the gateway — the WebDev module answers 402 while \
                  unlicensed (on a rig, `ign rig trial reset --yes` restarts an \
                  expired trial)"
                    .to_string(),
            ),
            Self::RouteVersionMismatch { deployed, expected, .. } => {
                // Direction decides the fix (roadmap criterion): an older
                // deployed route → redeploy from THIS binary; a NEWER
                // deployed route → this CLI is behind (the route bundle
                // travels with the binary). Same slug either way.
                let newer = semver::Version::parse(deployed)
                    .ok()
                    .zip(semver::Version::parse(expected).ok())
                    .is_some_and(|(deployed, expected)| deployed > expected);
                Some(if newer {
                    "the deployed routes are NEWER than this CLI — update ign \
                      (the route bundle travels with the binary)"
                        .to_string()
                } else {
                    "run `ign webdev deploy` to redeploy the route version \
                      this CLI expects"
                        .to_string()
                })
            }
            Self::ProviderNotFound { .. } => Some(
                "check the provider name; `ign tags provider list` shows the \
                  gateway's tag providers"
                    .to_string(),
            ),
            Self::TagCollision { .. } => Some(
                "re-run with --collision-policy overwrite to replace the \
                  existing tags (destructive: requires --yes)"
                    .to_string(),
            ),
            Self::AlarmJournalMissing { .. } => Some(
                "alarm history needs a journal profile — provision a database \
                  connection + alarm-journal profile on the gateway (and point \
                  the general-alarm-settings singleton at it), then retry; see \
                  the README 'Alarm history' section"
                    .to_string(),
            ),
            Self::SessionNotPrunable { .. } => Some(
                "close the Designer first — prune removes stale entries only".to_string(),
            ),
            Self::WebdevRouteError { code, .. } => Some(if code == "secret_required" || code == "secret_mismatch" {
                "the scriptExec route is secret-gated — deploy it with `ign \
                  webdev deploy --with-script-exec` (the secret is generated \
                  and stored in the profile config at 0600); a mismatch means \
                  the route was deployed with a different secret: redeploy or \
                  pass --rotate-secret"
                    .to_string()
            } else {
                "the deployed route refused the action — the code and message \
                  are the route's stable contract; `ign webdev status` \
                  diagnoses the deployment"
                    .to_string()
            }),
            Self::EamNotController { .. } => Some(
                "flip the gateway's EAM role: config-resource PUT on \
                   com.inductiveautomation.eam/module-settings with \
                   installMode \"Controller\" (array body carrying the current \
                   signature) — a manual gateway-role decision this CLI \
                   deliberately does not automate; see the README 'EAM tasks' \
                   section"
                    .to_string(),
            ),
            Self::ProviderRootUnsupported { .. } => Some(
                "target a subtree path like [provider]folder — provider-ROOT \
                   forms ([default] alone, or a bare provider name) need an \
                   RPC context WebDev threads don't carry (8.3.3); subtree \
                   paths are the supported form"
                    .to_string(),
            ),
            Self::EamTaskTypeRefused { .. } => Some(
                "restore/install/upgrade tasks dispatch fleet-wide (every \
                   agent target); run them from the Ignition EAM console — \
                   EXT-03 (v2) will scope them into the CLI"
                    .to_string(),
            ),
            Self::EamTaskInFlight { .. } => Some(
                "complete or delete the leftover '(forced)' run from the EAM \
                   console — no ign verb deletes runs; the slot frees once the \
                   run is resolved"
                    .to_string(),
            ),
            Self::ScriptExecNotConfigured { .. } => Some(
                "run `ign webdev deploy --with-script-exec` to deploy the route and \
                  generate + persist its secret (the deploy flag IS the opt-in — \
                  `ign script run` has no --yes by design)"
                    .to_string(),
            ),
            Self::LintToolAbsent => Some(
                "install the linter: `uv tool install ignition-lint-toolkit` \
                 (or `pip install ignition-lint-toolkit`) — \
                 github.com/TheThoughtagen/ignition-lint; then re-run with \
                 ignition-lint on PATH"
                    .to_string(),
            ),
            // The SAME string `ign e2e doctor`'s node row hands out —
            // a user who hits this refusal and then runs the doctor
            // must not be given two wordings of one instruction.
            Self::NodeToolAbsent { .. } => {
                Some(crate::actions::e2e::NODE_INSTALL_HINT.to_string())
            }
            Self::GatewayClientError { .. } => Some(
                "the gateway rejected this request — the body above is the \
                 gateway's own answer; fix the path/method/body, or use a \
                 curated `ign` command when one exists"
                    .to_string(),
            ),
            Self::BundleNotAvailable { .. } => Some(
                "generate a fresh bundle with `ign diagnostics bundle generate`, \
                 then wait again — the gateway reports no current bundle and \
                 polling cannot produce one"
                    .to_string(),
            ),
            Self::ModuleFeedUnreachable { .. } => Some(
                "check network reachability to the module release feed — an \
                 already-cached version works fully offline, so this only \
                 blocks a first-time fetch of a new version"
                    .to_string(),
            ),
            Self::ModuleReleaseNotFound {
                module, version, ..
            } => Some(format!(
                "check that {module} version {version} exists as a release upstream \
                 (the tag and asset name must match exactly) — this CLI never falls \
                 back to \"latest\""
            )),
            Self::ModuleDigestMismatch(d) => Some(format!(
                "the downloaded bytes for {} version {} do not match \
                 the feed's published digest — do not trust this artifact; nothing \
                 was cached, so re-running the fetch tries again from scratch",
                d.module,
                d.version
            )),
            Self::ModuleFeedUnusable { .. } => Some(
                "the module release feed answered but was not usable — if the \
                 detail names a rate limit, wait and retry; otherwise the feed's \
                 response itself needs investigation"
                    .to_string(),
            ),
            Self::ModuleDigestChanged(d) => Some(format!(
                "upstream re-released this version with different bytes — the cached \
                 artifact at {} is still there and usable offline; re-run with \
                 FetchPolicy::AcceptUpstreamChange to deliberately accept and verify the \
                 new bytes",
                d.cached_path
            )),
            Self::Rig(_) => Some(
                "check Docker is running and inspect the rig containers \
                 (docker ps)"
                    .to_string(),
            ),
            Self::ModuleNotRegistered { known, .. } => Some(if known.is_empty() {
                "no modules are registered in this build of ign".to_string()
            } else {
                format!(
                    "known module ids: {} — check the id passed to --with-module \
                     or declared under [rigs.NAME.modules.*]",
                    known.join(", ")
                )
            }),
            Self::ModuleUninstallDenied { .. } => Some(
                "the gateway refuses to uninstall a module whose .modl is still \
                 mounted — remove it from [rigs.NAME.modules], run `ign rig up` \
                 so the mount goes, then retry; a successful uninstall is NOT \
                 undone by re-declaring the module — recovery today means \
                 `ign rig reset --yes`, which destroys the rig's data volume"
                    .to_string(),
            ),
            Self::ScanLockHeld { .. } => Some(
                "the scan-lock is released when the holder's scan runs or its \
                 holdTimeout expires — wait for that, then retry"
                    .to_string(),
            ),
            Self::ResourceSignatureRejected { .. } => Some(
                "re-read the resource for its current signature and retry — \
                 signatures change on every write"
                    .to_string(),
            ),
            Self::ResourceExists { .. } => Some(
                "a resource of that name is already present — read it for its \
                 current signature and update it, or choose another name"
                    .to_string(),
            ),
            Self::ModeExists { .. } => Some(
                "that deployment mode is already defined — list the modes and \
                 skip the create"
                    .to_string(),
            ),
            Self::DeployTreeInvalid(..) => Some(
                "fix each file named above in the declared gateway tree; render \
                 refuses until every finding is resolved"
                    .to_string(),
            ),
            Self::EmbeddedSecret(..) => Some(
                "store the value in the gateway's secret provider and reference it \
                 as {\"type\":\"Referenced\",\"data\":{\"providerName\":\"…\",\
                 \"secretName\":\"…\"}}; never commit an Embedded or plaintext secret"
                    .to_string(),
            ),
            Self::TransportFailed { .. } => Some(
                "check the node's host access in targets/<env>.yaml: for `local`, that \
                 data_dir exists and is readable; for `ssh`, the pinned host key, the \
                 key and reachability. Nothing was read as absent, so no plan was made"
                    .to_string(),
            ),
            Self::DeployLedgerInvalid { .. } => Some(
                "the delete set is never assumed empty, so no plan was made; inspect or \
                 restore the ledger file named above (only an apply writes it) and rerun"
                    .to_string(),
            ),
            Self::PlanStale { detail, .. } if detail.starts_with("live project") => Some(
                "the live project changed after the plan was drawn; run the check again, \
                 review what it reports and rerun the deploy, nothing was imported"
                    .to_string(),
            ),
            Self::PlanStale { .. } => Some(
                "the plan changed after it was reviewed; review the new plan and rerun \
                 with its plan_sha256, nothing was written"
                    .to_string(),
            ),
            Self::DestructiveChangeRefused { gate, .. } => Some(match gate.as_str() {
                "drift" => "live files differ from both the base render and the declared tree; \
                     review the drift, then rerun with --allow-drift and a reason of at most \
                     500 characters"
                    .to_string(),
                "downgrade" => "the gateway last received a newer release of this project; \
                     deploy the newer release, or rerun with --allow-downgrade when the older \
                     release must replace it"
                    .to_string(),
                "first_deploy" => "this is the first deploy of the project by this tool and it \
                     would change what the gateway runs; release what the gateway runs first, \
                     or rerun with --allow-first-change and a reason"
                    .to_string(),
                _ => "review the destructive entries named above, then rerun with \
                     --allow-destructive and the plan_sha256 you reviewed"
                    .to_string(),
            }),
            Self::DeployBlocked { .. } => Some(
                "a core copy still shadows each unit named above, so no flag permits the \
                 removal; keep the unit in the declared tree, or remove the core copy on \
                 the gateway first"
                    .to_string(),
            ),
            Self::DeployUnreadable { .. } => Some(
                "the live path of each unit named above is too long for the host's sftp \
                 server; shorten it on the gateway (rename the folder), or, when the gateway \
                 owns the provider, list the provider in exclude_tag_providers and stop \
                 declaring it; nothing was written"
                    .to_string(),
            ),
            Self::DeployPreflightFailed { .. } => Some(
                "fix each failed check named above and rerun; no gateway file was written"
                    .to_string(),
            ),
            Self::DeployJournalPresent { .. } => Some(
                "an earlier deploy was interrupted and its journal is still on the box; run \
                 the recovery command in the message, then rerun; plan and apply refuse \
                 until the journal is cleared"
                    .to_string(),
            ),
            Self::DeployLiveChanged { .. } => Some(
                "someone changed the files named above after the run wrote them; review \
                 those changes, then rerun the rollback with --discard-live-changes to \
                 restore the snapshot over them"
                    .to_string(),
            ),
            Self::DeployRunInvalid { .. } => Some(
                "the run directory or the on-box record is missing or damaged; restore the \
                 files from the .gwbk backup or the run-directory snapshot instead"
                    .to_string(),
            ),
            Self::RollbackFailed(..) => Some(
                "do not apply again until the files are restored: run the retry command in \
                 the message first, because the journal and the snapshot are usually intact; \
                 only if it reports a lost or damaged snapshot restore from the .gwbk backup \
                 or the on-box snapshot named there, and then delete the journal at the path \
                 in the message by hand"
                    .to_string(),
            ),
            Self::ProjectGitManaged { .. } => Some(
                "follow the README cutover runbook: remove this project's .git on the \
                 gateway (the deploy tool never deletes it), then run the check again"
                    .to_string(),
            ),
            Self::ProjectParentInvalid { reason, .. } => Some(
                match reason.as_str() {
                    "missing" => "deploy the parent project from its own repo first, then run \
                                  the check again",
                    "cycle" => "fix the parent in project.json so the inheritance has no cycle",
                    _ => "the parent is not inheritable; fix the parent in project.json or \
                          make the parent inheritable",
                }
                .to_string(),
            ),
            Self::ProjectHashMismatch { .. } => Some(
                "the checkout is not the reviewed one; rerun the check on this commit and \
                 pass its artifact_sha256"
                    .to_string(),
            ),
        }
    }

    /// URL/path of the request involved, when one was — populated for the
    /// network, auth, and target-state classes (CORE-05).
    pub fn endpoint(&self) -> Option<String> {
        match self {
            Self::Network { url, .. } => Some(url.clone()),
            Self::Auth { endpoint, .. } => endpoint.clone(),
            Self::GatewayTooOld { endpoint, .. }
            | Self::GatewayNotCommissioned { endpoint }
            | Self::GatewayRestarting { endpoint }
            | Self::NotFound { endpoint }
            | Self::ProjectExists { endpoint, .. }
            | Self::ResourceBinary { endpoint, .. }
            | Self::TrialNotExpired { endpoint, .. }
            | Self::ProviderNotFound { endpoint, .. }
            | Self::RoutesNotDeployed { endpoint, .. }
            | Self::WebdevUnlicensed { endpoint }
            | Self::RouteVersionMismatch { endpoint, .. }
            | Self::WebdevRouteError { endpoint, .. }
            | Self::TagCollision { endpoint, .. }
            | Self::AlarmJournalMissing { endpoint }
            | Self::SessionNotPrunable { endpoint, .. }
            | Self::ImportDenied { endpoint, .. }
            | Self::EamNotController { endpoint }
            | Self::ProviderRootUnsupported { endpoint }
            | Self::EamTaskInFlight { endpoint, .. }
            | Self::ModuleUninstallDenied { endpoint, .. }
            | Self::ScanLockHeld { endpoint, .. }
            | Self::ResourceSignatureRejected { endpoint, .. }
            | Self::ResourceExists { endpoint, .. }
            | Self::ModeExists { endpoint, .. } => endpoint.clone(),
            Self::ModuleFeedUnreachable { url, .. }
            | Self::ModuleReleaseNotFound { url, .. }
            | Self::ModuleFeedUnusable { url, .. } => Some(url.clone()),
            // Boxed payload, so it cannot share the or-pattern above.
            Self::ModuleDigestMismatch(d) => Some(d.url.clone()),
            _ => None,
        }
    }

    /// The deploy slugs (21-03), in the order the README row lists them.
    pub const DEPLOY_SLUGS: &'static [&'static str] = &[
        "deploy_tree_invalid",
        "embedded_secret",
        "transport_failed",
        "deploy_ledger_invalid",
        "plan_stale",
        "destructive_change_refused",
        "deploy_blocked",
        "deploy_preflight_failed",
        "deploy_journal_present",
        "deploy_live_changed",
        "deploy_run_invalid",
        "rollback_failed",
        "project_git_managed",
        "project_parent_invalid",
        "project_hash_mismatch",
        "deploy_unreadable",
    ];

    /// A single positioned (or file-only, when `line`/`column` are
    /// `None`) tree finding as a [`Self::DeployTreeInvalid`].
    pub fn deploy_tree_invalid(
        file: impl Into<String>,
        line: Option<usize>,
        column: Option<usize>,
        message: impl Into<String>,
    ) -> Self {
        Self::deploy_findings(vec![DeployFinding {
            file: file.into(),
            line,
            column,
            message: message.into(),
        }])
    }

    /// Several tree findings as one [`Self::DeployTreeInvalid`]. An empty
    /// vector is a programming error: debug builds assert, release builds
    /// still return one generic finding so the error is never empty.
    pub fn deploy_findings(findings: Vec<DeployFinding>) -> Self {
        debug_assert!(!findings.is_empty(), "deploy_findings needs a finding");
        let findings = if findings.is_empty() {
            vec![DeployFinding {
                file: String::new(),
                line: None,
                column: None,
                message: "the declared tree is invalid".to_string(),
            }]
        } else {
            findings
        };
        Self::DeployTreeInvalid(Box::new(DeployTreeInvalidDetails { findings }))
    }

    /// An embedded or plaintext secret at each of `paths` (locations
    /// only, never values), plus any non-secret findings from the same
    /// render.
    pub fn embedded_secret(paths: Vec<String>, other_findings: Vec<DeployFinding>) -> Self {
        Self::EmbeddedSecret(Box::new(EmbeddedSecretDetails {
            paths,
            other_findings,
        }))
    }

    /// The `ign tui` TTY refusal (06-07): InvalidInput carrying the
    /// ONE reason whose hint is terminal-contextual — see
    /// [`TUI_TTY_REFUSAL_REASON`]. Same slug, same exit 2 (frozen
    /// taxonomy; only the hint differs).
    pub fn tui_tty_refusal() -> Self {
        Self::InvalidInput {
            reason: TUI_TTY_REFUSAL_REASON.to_string(),
        }
    }

    /// The `ign top` TTY refusal (itop): the tui refusal's sibling at
    /// one command over — same slug, same exit 2, the hint naming the
    /// monitor's command. See [`TOP_TTY_REFUSAL_REASON`].
    pub fn top_tty_refusal() -> Self {
        Self::InvalidInput {
            reason: TOP_TTY_REFUSAL_REASON.to_string(),
        }
    }

    /// Build the LOCKED failure envelope for this error (field order is part
    /// of the golden contract: `ok`, `profile`, `error` then `code`,
    /// `message`, `endpoint`, `hint`).
    pub fn envelope<'a>(&self, profile: Option<&'a str>) -> ErrorEnvelope<'a> {
        ErrorEnvelope {
            ok: false,
            profile,
            error: ErrorBody {
                code: self.code(),
                message: self.to_string(),
                endpoint: self.endpoint(),
                hint: self.hint(),
            },
        }
    }
}

/// LOCKED failure envelope shape: exactly the top-level fields `ok`,
/// `profile`, `error` — changing the set is a breaking change for agents.
#[derive(Debug, Serialize)]
pub struct ErrorEnvelope<'a> {
    /// Always `false` in this envelope.
    pub ok: bool,
    /// Active profile echoed in every output (CORE-01); `None` until config
    /// resolution lands.
    pub profile: Option<&'a str>,
    /// The typed error body.
    pub error: ErrorBody,
}

/// LOCKED error body: `code` (stable slug), `message` (human-readable),
/// `endpoint` (when a request was involved), `hint` (actionable next step).
#[derive(Debug, Serialize)]
pub struct ErrorBody {
    /// Stable slug from [`CoreError::code`] — never respelled.
    pub code: &'static str,
    /// Human-readable description.
    pub message: String,
    /// URL/path when a request was involved.
    pub endpoint: Option<String>,
    /// Actionable next step.
    pub hint: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::{
        CoreError, DeployFinding, ErrorBody, ErrorEnvelope, GATEWAY_CLIENT_BODY_CAP_BYTES,
        GATEWAY_CLIENT_BODY_TRUNCATION_MARKER, LOSS_GATE_REFUSAL_REASON_PREFIX,
        ModuleDigestChangedDetails, ModuleDigestMismatchDetails, PreflightFailure, RollbackFailure,
        SignatureReason, TESTING_ROUTE_PREFIX, truncate_api_body,
    };

    /// Build a real `reqwest::Error` for the Network variant: a request to
    /// an unroutable loopback port fails at connect time (instant refusal —
    /// `reqwest::Error` has no public constructor).
    fn network_error() -> CoreError {
        // reqwest is built with `rustls-no-provider`, so a raw
        // `reqwest::get` panics unless the process-wide provider is
        // installed. In a full lib-test run some other test happens to
        // install it first; running the error tests ALONE (which the
        // exit-table verify command does) hit the panic. The install is
        // idempotent and documented for exactly this use.
        crate::client::install_crypto_provider();
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime");
        let url = "http://127.0.0.1:1";
        let source = rt
            .block_on(reqwest::get(url))
            .expect_err("request to an unroutable port must fail");
        CoreError::Network {
            url: url.to_string(),
            source: Some(source),
            observation: None,
        }
    }

    /// The [`CoreError::ModuleFeedUnreachable`] twin of [`network_error`]
    /// — a real `reqwest::Error` from an unroutable loopback port, for
    /// the offline-module-feed exit-4 case.
    fn module_feed_unreachable_error() -> CoreError {
        crate::client::install_crypto_provider();
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime");
        let url = "http://127.0.0.1:1";
        let source = rt
            .block_on(reqwest::get(url))
            .expect_err("request to an unroutable port must fail");
        CoreError::ModuleFeedUnreachable {
            url: url.to_string(),
            source: Some(source),
        }
    }

    /// Pitfall-5 guard: the FULL 1–7 taxonomy enumerated on day one so no
    /// later phase can silently renumber it or respell a slug. The slugs are
    /// asserted against literals — that IS the stability contract.
    #[test]
    fn exit_code_mapping_enumerated() {
        let cases: Vec<(CoreError, u8, &'static str)> = vec![
            (CoreError::Internal("boom".into()), 1, "internal"),
            (
                CoreError::ConfirmationRequired {
                    operation: "project download".into(),
                },
                2,
                "confirmation_required",
            ),
            (
                CoreError::ProfilingRiskNotAccepted {
                    operation: "jvm sample".into(),
                },
                2,
                "profiling_risk_not_accepted",
            ),
            (
                CoreError::InvalidImportFile {
                    reason: "missing ZIP magic".into(),
                },
                2,
                "invalid_import_file",
            ),
            (
                CoreError::InvalidInput {
                    reason: "cannot read put.json".into(),
                },
                2,
                "invalid_input",
            ),
            (
                CoreError::ProfileNotFound {
                    name: "nope".into(),
                    known: vec!["dev".into()],
                },
                3,
                "profile_not_found",
            ),
            (CoreError::NoActiveProfile, 3, "no_active_profile"),
            (
                CoreError::SecretUnavailable {
                    profile: "dev".into(),
                },
                3,
                "secret_unavailable",
            ),
            (
                CoreError::PasswordUnavailable {
                    profile: "dev".into(),
                },
                3,
                "password_unavailable",
            ),
            (
                CoreError::ConfigInvalid {
                    reason: "bad toml".into(),
                },
                3,
                "config_invalid",
            ),
            (
                CoreError::PollIntervalTooSmall {
                    profile: "dev".into(),
                },
                3,
                "poll_interval_too_small",
            ),
            (network_error(), 4, "network_error"),
            (
                CoreError::Auth {
                    status: 401,
                    endpoint: None,
                },
                5,
                "auth_rejected",
            ),
            (
                CoreError::GatewayTooOld {
                    found: "8.1.0".into(),
                    minimum: "8.3.1".into(),
                    endpoint: None,
                },
                6,
                "gateway_too_old",
            ),
            (
                CoreError::GatewayNotCommissioned {
                    endpoint: Some("http://gw:8088/data/api/v1/gateway-info".into()),
                },
                6,
                "gateway_not_commissioned",
            ),
            (
                CoreError::GatewayRestarting {
                    endpoint: Some("http://gw:8088/data/api/v1/gateway-info".into()),
                },
                6,
                "gateway_restarting",
            ),
            (
                CoreError::NotFound {
                    endpoint: Some("http://gw:8088/data/api/v1/designer/42".into()),
                },
                6,
                "not_found",
            ),
            (
                CoreError::ProjectExists {
                    name: "PlantFloor".into(),
                    endpoint: None,
                },
                6,
                "project_exists",
            ),
            (
                CoreError::ResourceBinary {
                    path: "com.x/perspective/session-permissions".into(),
                    endpoint: None,
                },
                6,
                "resource_binary",
            ),
            (
                CoreError::TrialNotExpired {
                    remaining_s: 6590,
                    endpoint: Some("http://localhost:9088/data/api/v1/trial".into()),
                },
                6,
                "trial_not_expired",
            ),
            (
                CoreError::ProviderNotFound {
                    name: "nope".into(),
                    endpoint: Some("/data/api/v1/resources/find/ignition/tag-provider/nope".into()),
                },
                6,
                "provider_not_found",
            ),
            (
                CoreError::RoutesNotDeployed {
                    project: "ign-cli".into(),
                    route: "tags".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "routes_not_deployed",
            ),
            (
                CoreError::WebdevUnlicensed {
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "webdev_unlicensed",
            ),
            (
                CoreError::RouteVersionMismatch {
                    route: "tags".into(),
                    deployed: "0.9.0".into(),
                    expected: "1.0.0".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "route_version_mismatch",
            ),
            (
                CoreError::WebdevRouteError {
                    code: "route_error".into(),
                    message: "boom".into(),
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "webdev_route_error",
            ),
            (
                CoreError::TagCollision {
                    provider: "p5import".into(),
                    names: vec!["T1".into(), "P5".into()],
                    endpoint: Some("/system/webdev/ign-cli/cli/tags".into()),
                },
                6,
                "tag_collision",
            ),
            (
                CoreError::AlarmJournalMissing {
                    endpoint: Some("/system/webdev/ign-cli/cli/alarms".into()),
                },
                6,
                "alarm_journal_missing",
            ),
            (
                CoreError::ImportDenied {
                    project: "PlantFloor".into(),
                    problem: "resource already exists: ResourceId{resourcePath=com.example, collectionName=views}".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/projects/import/PlantFloor?overwrite=true".into()),
                },
                6,
                "import_denied",
            ),
            (
                CoreError::SessionNotPrunable {
                    id: "d-live-1".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/designer/d-live-1".into()),
                },
                6,
                "session_not_prunable",
            ),
            (
                CoreError::EamNotController {
                    endpoint: Some("http://gw:8088/data/eam/api/v1/eam-tasks/history".into()),
                },
                6,
                "eam_not_controller",
            ),
            (
                CoreError::ProviderRootUnsupported {
                    endpoint: Some("/system/webdev/ign-cli/cli/tagConfig".into()),
                },
                6,
                "provider_root_unsupported",
            ),
            (
                CoreError::EamTaskTypeRefused {
                    task_type: "eam_remoteUpgrade".into(),
                },
                6,
                "eam_task_type_refused",
            ),
            (
                CoreError::EamTaskInFlight {
                    task: "cli-research-backup".into(),
                    detail: "Task 'cli-research-backup (forced)' already exists! It must be completed or deleted before another task of this type can be force executed.".into(),
                    endpoint: Some(
                        "http://gw:8088/data/eam/api/v1/eam-tasks/force/eam/cli-research-backup"
                            .into(),
                    ),
                },
                6,
                "eam_task_in_flight",
            ),
            (
                CoreError::ScriptExecNotConfigured {
                    profile: "dev".into(),
                },
                6,
                "script_exec_not_configured",
            ),
            (CoreError::LintToolAbsent, 6, "lint_tool_absent"),
            (
                CoreError::NodeToolAbsent {
                    tool: "node".into(),
                },
                6,
                "node_tool_absent",
            ),
            (
                CoreError::BundleNotAvailable {
                    state: "Invalid".into(),
                },
                6,
                "bundle_not_available",
            ),
            (
                CoreError::GatewayClientError {
                    status: 400,
                    endpoint: "http://gw:8088/data/api/v1/nonexistent".into(),
                    body: r#"{"error":{"code":"NOT_FOUND"}}"#.into(),
                },
                2,
                "gateway_client_error",
            ),
            (CoreError::Rig("compose up failed".into()), 7, "rig_error"),
            (
                module_feed_unreachable_error(),
                4,
                "module_feed_unreachable",
            ),
            (
                CoreError::ModuleReleaseNotFound {
                    module: "git".into(),
                    version: "99.99.99".into(),
                    url: "https://api.github.com/repos/WhiskeyHouse/ignition-git-module/releases/tags/v99.99.99".into(),
                    detail: "no release exists for tag \"v99.99.99\"".into(),
                },
                6,
                "module_release_not_found",
            ),
            (
                CoreError::ModuleDigestMismatch(Box::new(ModuleDigestMismatchDetails {
                    module: "git".into(),
                    version: "2.3.4".into(),
                    url: "https://release-assets.githubusercontent.com/Git-2.3.4-signed.modl".into(),
                    expected: "b".repeat(64),
                    actual: "c".repeat(64),
                })),
                6,
                "module_digest_mismatch",
            ),
            (
                CoreError::ModuleFeedUnusable {
                    url: "https://api.github.com/repos/WhiskeyHouse/ignition-git-module/releases/tags/v2.3.4".into(),
                    detail: "rate limit exceeded".into(),
                },
                6,
                "module_feed_unusable",
            ),
            (
                CoreError::ModuleDigestChanged(Box::new(ModuleDigestChangedDetails {
                    module: "git".into(),
                    version: "2.3.4".into(),
                    cached_digest: "a".repeat(64),
                    upstream_digest: "b".repeat(64),
                    cached_path: "/cache/modules/git/2.3.4-aaaa.modl".into(),
                })),
                6,
                "module_digest_changed",
            ),
            (
                CoreError::ModuleNotRegistered {
                    id: "bogus".into(),
                    known: vec!["git".into()],
                },
                3,
                "module_not_registered",
            ),
            (
                CoreError::ModuleUninstallDenied {
                    module_id: "git".into(),
                    gateway_module_id: "com.axone_io.ignition.git".into(),
                    failed: vec!["com.axone_io.ignition.git".into()],
                    endpoint: Some(
                        "http://gw:8088/data/api/v1/modules/uninstall".into(),
                    ),
                },
                6,
                "module_uninstall_denied",
            ),
            (
                CoreError::ScanLockHeld {
                    actor: Some("api-token:cap-a:172.17.0.1".into()),
                    kind: "config".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/scan-lock/config".into()),
                },
                6,
                "scan_lock_held",
            ),
            (
                CoreError::ResourceSignatureRejected {
                    name: "DB_A".into(),
                    reason: SignatureReason::Stale,
                    endpoint: Some(
                        "http://gw:8088/data/api/v1/resources/find/ignition/database-connection/DB_A"
                            .into(),
                    ),
                },
                6,
                "resource_signature_rejected",
            ),
            (
                CoreError::ResourceExists {
                    name: "DB_A".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/resources/ignition/database-connection".into()),
                },
                6,
                "resource_exists",
            ),
            (
                CoreError::ModeExists {
                    name: "production".into(),
                    endpoint: Some("http://gw:8088/data/api/v1/mode".into()),
                },
                6,
                "mode_exists",
            ),
            (
                CoreError::deploy_tree_invalid("manifest.yaml", Some(2), Some(1), "unknown field"),
                2,
                "deploy_tree_invalid",
            ),
            (
                CoreError::embedded_secret(vec!["a.json: settings.password".into()], vec![]),
                2,
                "embedded_secret",
            ),
            (
                CoreError::TransportFailed {
                    operation: "read".into(),
                    node: "nodes.master".into(),
                    detail: "cannot read directory config/resources (NotFound)".into(),
                },
                4,
                "transport_failed",
            ),
            (
                CoreError::DeployLedgerInvalid {
                    location: "ign-deploy/gw/dev/ledger.json".into(),
                    problem: "files is not byte-sorted".into(),
                },
                6,
                "deploy_ledger_invalid",
            ),
            (
                CoreError::PlanStale {
                    expected: "a".repeat(64),
                    actual: "b".repeat(64),
                    detail: "review hash".into(),
                },
                6,
                "plan_stale",
            ),
            (
                CoreError::DestructiveChangeRefused {
                    gate: "destructive".into(),
                    keys: vec!["ignition/a/x".into()],
                    count: 1,
                },
                2,
                "destructive_change_refused",
            ),
            (
                CoreError::DeployBlocked {
                    keys: vec!["ignition/a/x".into()],
                },
                6,
                "deploy_blocked",
            ),
            (
                CoreError::DeployPreflightFailed {
                    failures: vec![PreflightFailure {
                        check: "mode_master".into(),
                        detail: "the gateway is not in the declared mode".into(),
                    }]
                    .into(),
                },
                6,
                "deploy_preflight_failed",
            ),
            (
                CoreError::DeployJournalPresent {
                    run_id: "r1".into(),
                    env: "prod".into(),
                    location: "ign-deploy/gw/m/journal.json".into(),
                },
                6,
                "deploy_journal_present",
            ),
            (
                CoreError::DeployLiveChanged {
                    run_id: "r1".into(),
                    paths: vec!["a/b.json".into()],
                    count: 1,
                },
                6,
                "deploy_live_changed",
            ),
            (
                CoreError::DeployRunInvalid {
                    run_id: "r1".into(),
                    problem: "record.json is missing".into(),
                },
                6,
                "deploy_run_invalid",
            ),
            (
                CoreError::RollbackFailed(Box::new(RollbackFailure {
                    run_id: "r1".into(),
                    env: "dev".into(),
                    run_dir: Some(".ign/deploy/r1".into()),
                    journal: "ign-deploy/gw/m/journal.json".into(),
                    cause: "write_failed".into(),
                })),
                6,
                "rollback_failed",
            ),
            (
                CoreError::ProjectGitManaged {
                    project: "CapApp".into(),
                    location: "projects/CapApp/.git".into(),
                    kind: "directory".into(),
                },
                6,
                "project_git_managed",
            ),
            (
                CoreError::ProjectParentInvalid {
                    project: "CapApp".into(),
                    parent: "WHK-Global".into(),
                    reason: "missing".into(),
                },
                6,
                "project_parent_invalid",
            ),
            (
                CoreError::ProjectHashMismatch {
                    project: "CapApp".into(),
                    expected: "0".repeat(64),
                    actual: "1".repeat(64),
                },
                6,
                "project_hash_mismatch",
            ),
            (
                CoreError::DeployUnreadable {
                    node: "master".into(),
                    keys: vec!["ignition/tag-definition/default/Deep".into()],
                },
                6,
                "deploy_unreadable",
            ),
        ];
        for (err, code, slug) in cases {
            assert_eq!(err.exit_code(), code, "wrong exit code for: {err}");
            assert_eq!(err.code(), slug, "unstable slug for: {err}");
        }
    }

    /// The (exit_code, slug) literal table the Three-Place rule syncs.
    /// DUPLICATED from [`exit_code_mapping_enumerated`]'s triple list by
    /// design: that test is the literal source of truth (enum ↔ literals);
    /// this flat table is what the README cross-check runs against, so a
    /// drift inside error.rs surfaces as a disagreement instead of silently
    /// re-shuffling both sides. Keep the two lists in lockstep — the
    /// enumerated test fails if the enum respells/renumbers, and a stale
    /// copy here fails the README check below until updated.
    const EXIT_SLUG_LITERALS: &[(u8, &str)] = &[
        (1, "internal"),
        (2, "confirmation_required"),
        (2, "profiling_risk_not_accepted"),
        (2, "invalid_import_file"),
        (2, "invalid_input"),
        (2, "gateway_client_error"),
        (2, "deploy_tree_invalid"),
        (2, "embedded_secret"),
        (2, "destructive_change_refused"),
        (3, "profile_not_found"),
        (3, "no_active_profile"),
        (3, "secret_unavailable"),
        (3, "password_unavailable"),
        (3, "config_invalid"),
        (3, "poll_interval_too_small"),
        (3, "module_not_registered"),
        (4, "network_error"),
        (5, "auth_rejected"),
        (6, "gateway_too_old"),
        (6, "gateway_not_commissioned"),
        (6, "gateway_restarting"),
        (6, "not_found"),
        (6, "project_exists"),
        (6, "resource_binary"),
        (6, "trial_not_expired"),
        (6, "provider_not_found"),
        (6, "routes_not_deployed"),
        (6, "webdev_unlicensed"),
        (6, "route_version_mismatch"),
        (6, "webdev_route_error"),
        (6, "tag_collision"),
        (6, "alarm_journal_missing"),
        (6, "import_denied"),
        (6, "session_not_prunable"),
        (6, "eam_not_controller"),
        (6, "eam_task_type_refused"),
        (6, "eam_task_in_flight"),
        (6, "script_exec_not_configured"),
        (6, "lint_tool_absent"),
        (6, "node_tool_absent"),
        (6, "provider_root_unsupported"),
        (6, "bundle_not_available"),
        (4, "module_feed_unreachable"),
        (4, "transport_failed"),
        (6, "module_release_not_found"),
        (6, "module_digest_mismatch"),
        (6, "module_feed_unusable"),
        (6, "module_digest_changed"),
        (6, "module_uninstall_denied"),
        (6, "scan_lock_held"),
        (6, "resource_signature_rejected"),
        (6, "resource_exists"),
        (6, "mode_exists"),
        (6, "deploy_ledger_invalid"),
        (6, "plan_stale"),
        (6, "deploy_blocked"),
        (6, "deploy_preflight_failed"),
        (6, "deploy_journal_present"),
        (6, "deploy_live_changed"),
        (6, "deploy_run_invalid"),
        (6, "rollback_failed"),
        (6, "project_git_managed"),
        (6, "project_parent_invalid"),
        (6, "project_hash_mismatch"),
        (6, "deploy_unreadable"),
        (7, "rig_error"),
    ];

    /// The two deploy slugs (20-02) never carry a signature value or
    /// gateway problem text, and render their payloads sensibly.
    #[test]
    fn deploy_slugs_never_carry_signature_or_problem_text() {
        const SAMPLE_SIG: &str = "d80c81d167362252bf389893ea0f3a81479521ba0bb68ee3bfc46e94bc2540b7";

        let held = CoreError::ScanLockHeld {
            actor: Some("api-token:cap-a:172.17.0.1".into()),
            kind: "config".into(),
            endpoint: Some("http://gw:8088/data/api/v1/scan-lock/config".into()),
        };
        assert_eq!(held.code(), "scan_lock_held");
        assert_eq!(held.exit_code(), 6);
        let shown = held.to_string();
        assert!(shown.contains("api-token:cap-a:172.17.0.1"), "{shown}");
        assert!(shown.contains("config"), "{shown}");
        assert_eq!(
            held.endpoint().as_deref(),
            Some("http://gw:8088/data/api/v1/scan-lock/config")
        );

        let anonymous = CoreError::ScanLockHeld {
            actor: None,
            kind: "config".into(),
            endpoint: None,
        };
        let shown = anonymous.to_string();
        assert!(shown.contains("another actor"), "{shown}");
        assert!(!shown.contains("None"), "{shown}");

        for reason in [SignatureReason::Stale, SignatureReason::Missing] {
            let err = CoreError::ResourceSignatureRejected {
                name: "DB_A".into(),
                reason,
                endpoint: Some("http://gw:8088/data/api/v1/resources/x".into()),
            };
            assert_eq!(err.code(), "resource_signature_rejected");
            assert_eq!(err.exit_code(), 6);
            let shown = err.to_string();
            assert!(shown.contains("DB_A"), "{shown}");
            assert!(shown.contains(&reason.to_string()), "{shown}");
            assert!(!shown.contains(SAMPLE_SIG), "{shown}");
            let hint = err.hint().expect("hint required");
            assert!(!hint.contains(SAMPLE_SIG), "{hint}");
            let endpoint = err.endpoint().expect("endpoint");
            assert!(!endpoint.contains(SAMPLE_SIG), "{endpoint}");
        }
        assert_eq!(SignatureReason::Stale.to_string(), "stale");
        assert_eq!(SignatureReason::Missing.to_string(), "missing");
    }

    /// Parse the README's exit-code table: rows `| <exit> | class | meaning |
    /// \`slug\`, ... |` where `<exit>` is 1–7 (row 0 is the success row, no
    /// slugs). Parsing is SCOPED to the `## Exit codes` section — the README
    /// contains unrelated tables whose rows coincidentally begin `| 5 |`,
    /// `| 3 |`, etc. Std-only string ops: split on `|`, trim, take the LAST
    /// non-empty cell as the slug column (the meaning column can carry
    /// backticked non-slugs like `--yes`), and keep the backtick-delimited
    /// tokens that start with an ASCII letter and contain no spaces.
    fn parse_readme_exit_table(readme: &str) -> Vec<(u8, Vec<String>)> {
        let section = readme.split("## Exit codes").nth(1).unwrap_or_default();
        let mut rows = Vec::new();
        let table_lines = section
            .lines()
            .skip_while(|line| !line.trim_start().starts_with('|'));
        for line in table_lines {
            if !line.trim_start().starts_with('|') {
                break; // table ended
            }
            let cells: Vec<&str> = line.split('|').map(str::trim).collect();
            let Some(exit) = cells.get(1).and_then(|cell| cell.parse::<u8>().ok()) else {
                continue;
            };
            if !(1..=7).contains(&exit) {
                continue;
            }
            let slug_cell = cells
                .iter()
                .rev()
                .find(|cell| !cell.is_empty())
                .copied()
                .unwrap_or_default();
            let slugs: Vec<String> = slug_cell
                .split('`')
                .enumerate()
                .filter(|(idx, _)| idx % 2 == 1)
                .map(|(_, token)| token.trim().to_string())
                .filter(|token| {
                    token.starts_with(|c: char| c.is_ascii_alphabetic()) && !token.contains(' ')
                })
                .collect();
            rows.push((exit, slugs));
        }
        rows
    }

    /// CORE-11, the Three-Place slug rule made executable: the exit-code
    /// table exists in the enum ([`CoreError::exit_code`]), this file's
    /// literal triples, and the README — and the README side is now
    /// machine-checked. The README is parsed verbatim via `include_str!`
    /// and cross-checked against the literal table in BOTH directions:
    /// (a) every literal slug appears under its exit code (a README row
    /// that lost or misspelled a slug fails), (b) every README slug token
    /// exists in the literal table (a stale/deleted row fails). Exit 6
    /// carries 23 slugs, so the full cross-check is the value — not the
    /// happy-path smoke.
    #[test]
    fn readme_exit_table_agreement() {
        let readme = include_str!("../../../README.md");
        let rows = parse_readme_exit_table(readme);
        assert!(
            rows.len() >= 7,
            "README exit-code table not found — the parser must see all 7 \
             failure-class rows (found {})",
            rows.len()
        );

        // Direction (a): every literal (exit, slug) is present in the
        // README row matching its exit code.
        for (exit, slug) in EXIT_SLUG_LITERALS {
            let row = rows
                .iter()
                .find(|(readme_exit, _)| readme_exit == exit)
                .unwrap_or_else(|| panic!("README table has no row for exit {exit}"));
            assert!(
                row.1.iter().any(|s| s == slug),
                "README exit-{exit} row is missing slug {slug:?} (row: {:?})",
                row.1
            );
        }

        // Direction (b): every README slug token exists in the literal
        // table under the same exit code — catches stale/deleted rows.
        for (exit, slugs) in &rows {
            for slug in slugs {
                assert!(
                    EXIT_SLUG_LITERALS
                        .iter()
                        .any(|(lit_exit, lit_slug)| lit_exit == exit && lit_slug == slug),
                    "README exit-{exit} row carries slug {slug:?} that no \
                     CoreError variant emits — stale table row or slug/exit \
                     drift between README and error.rs"
                );
            }
        }
    }

    /// CORE-05: config, auth, and target-state classes carry actionable
    /// hints (and every other class does too).
    #[test]
    fn hints_are_actionable_for_config_auth_target_state() {
        let profile_not_found = CoreError::ProfileNotFound {
            name: "x".into(),
            known: vec!["dev".into(), "prod".into()],
        };
        let hint = profile_not_found.hint().expect("hint required");
        assert!(
            hint.contains("dev"),
            "hint must list known profiles: {hint}"
        );
        assert!(
            hint.contains("ign profile add"),
            "hint must name the fix: {hint}"
        );

        let auth = CoreError::Auth {
            status: 403,
            endpoint: None,
        };
        let hint = auth.hint().expect("hint required");
        assert!(
            hint.contains("three parts"),
            "auth hint must name the three-part token setup: {hint}"
        );

        // Status-aware auth hints (02-RESEARCH Auth §4): 401 = not
        // recognized (name:key format), 403 = under-permitted.
        let unauthorized = CoreError::Auth {
            status: 401,
            endpoint: None,
        };
        let hint = unauthorized.hint().expect("hint required");
        assert!(
            hint.contains("name:key"),
            "401 hint must name the full name:key token format: {hint}"
        );
        assert!(
            hint.contains("API token"),
            "401 hint must say Basic cannot work: {hint}"
        );
        let hint403 = auth.hint().expect("hint required");
        assert!(
            hint403.contains("secure connections"),
            "403 hint must name the secure-channel part: {hint403}"
        );

        let too_old = CoreError::GatewayTooOld {
            found: "8.1.0".into(),
            minimum: "8.3.1".into(),
            endpoint: None,
        };
        let hint = too_old.hint().expect("hint required");
        assert!(
            hint.contains("8.3.1"),
            "target-state hint must name the minimum: {hint}"
        );

        // The WebDev refusal matrix (05-03): every hint names the fix
        // — `ign webdev deploy` for absent/older routes, `update ign`
        // for newer ones (the roadmap's actionable-error criterion).
        let undeployed = CoreError::RoutesNotDeployed {
            project: "ign-cli".into(),
            route: "tags".into(),
            endpoint: None,
        };
        let hint = undeployed.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy"),
            "absent-routes hint must name the fix: {hint}"
        );

        let older = CoreError::RouteVersionMismatch {
            route: "tags".into(),
            deployed: "0.9.0".into(),
            expected: "1.0.0".into(),
            endpoint: None,
        };
        let hint = older.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy") && !hint.contains("update ign"),
            "older-route hint says redeploy: {hint}"
        );

        let newer = CoreError::RouteVersionMismatch {
            route: "tags".into(),
            deployed: "1.1.0".into(),
            expected: "1.0.0".into(),
            endpoint: None,
        };
        let hint = newer.hint().expect("hint required");
        assert!(
            hint.contains("update ign") && !hint.contains("ign webdev deploy"),
            "newer-route hint says update ign: {hint}"
        );

        let secret_gate = CoreError::WebdevRouteError {
            code: "secret_required".into(),
            message: "missing x-ignition-cli-secret header".into(),
            endpoint: None,
        };
        let hint = secret_gate.hint().expect("hint required");
        assert!(
            hint.contains("--with-script-exec"),
            "secret-gate hint names the deploy flag: {hint}"
        );

        // The alarm-journal refusal (05-06): the hint names the missing
        // provisioning chain AND the README section.
        let journal = CoreError::AlarmJournalMissing { endpoint: None };
        let hint = journal.hint().expect("hint required");
        assert!(
            hint.contains("journal profile") && hint.contains("database connection"),
            "journal hint names the chain: {hint}"
        );
        assert!(
            hint.contains("README"),
            "journal hint points at the README section: {hint}"
        );

        // The live-designer prune refusal (06-07): the hint names the
        // action — close the Designer — and the stale-only semantics.
        let prunable = CoreError::SessionNotPrunable {
            id: "d-live-1".into(),
            endpoint: None,
        };
        let hint = prunable.hint().expect("hint required");
        assert!(
            hint.contains("close the Designer"),
            "prune hint must name the action: {hint}"
        );
        assert!(
            hint.contains("stale entries"),
            "prune hint must name stale-only semantics: {hint}"
        );

        // The scan-lock refusal (20-02): the hint names the release
        // conditions and no ign command.
        let held = CoreError::ScanLockHeld {
            actor: None,
            kind: "config".into(),
            endpoint: None,
        };
        let hint = held.hint().expect("hint required");
        assert!(
            hint.contains("holdTimeout") && hint.contains("scan runs"),
            "scan-lock hint names the release conditions: {hint}"
        );
        assert!(
            !hint.contains("ign "),
            "scan-lock hint names no ign command: {hint}"
        );

        // The signature refusal (20-02): re-read and retry.
        let rejected = CoreError::ResourceSignatureRejected {
            name: "DB_A".into(),
            reason: SignatureReason::Stale,
            endpoint: None,
        };
        let hint = rejected.hint().expect("hint required");
        assert!(
            hint.contains("re-read") && hint.contains("signatures change on every write"),
            "signature hint names the action: {hint}"
        );

        // The duplicate-create refusals (20-REVIEW WR-01): each names the
        // next step and carries no gateway problem text.
        let exists = CoreError::ResourceExists {
            name: "DB_A".into(),
            endpoint: None,
        };
        let hint = exists.hint().expect("hint required");
        assert!(
            hint.contains("update it"),
            "resource_exists hint names the action: {hint}"
        );
        assert_eq!(exists.to_string(), "resource \"DB_A\" already exists");
        let mode_exists = CoreError::ModeExists {
            name: "production".into(),
            endpoint: None,
        };
        let hint = mode_exists.hint().expect("hint required");
        assert!(
            hint.contains("skip the create"),
            "mode_exists hint names the action: {hint}"
        );

        // The TTY refusal's hint is contextual (06-07): the ONE
        // InvalidInput reason whose fix is terminal-related. Every
        // other reason keeps the --file/stdin resource-put hint (pinned
        // here so the special case can never leak or regress).
        let tty = CoreError::tui_tty_refusal();
        assert_eq!(tty.code(), "invalid_input", "slug unchanged");
        assert_eq!(tty.exit_code(), 2, "usage class unchanged");
        let hint = tty.hint().expect("hint required");
        assert!(
            hint.contains("interactive terminal"),
            "TTY hint must name the fix: {hint}"
        );
        assert!(
            !hint.contains("--file"),
            "TTY hint must not carry the resource-put hint: {hint}"
        );

        // The itop sibling (ign top): the SAME usage class and slug,
        // but the refusal/hint name the MONITOR's command — a hint
        // naming `ign tui` would not fix an `ign top` run (the
        // RoutesNotDeployed rule at the TTY pair).
        let top = CoreError::top_tty_refusal();
        assert_eq!(top.code(), "invalid_input", "slug unchanged");
        assert_eq!(top.exit_code(), 2, "usage class unchanged");
        let top_hint = top.hint().expect("hint required");
        assert!(
            top_hint.contains("`ign top`"),
            "the top refusal's hint names ign top: {top_hint}"
        );
        assert!(
            !top_hint.contains("ign tui"),
            "the top refusal never names the cockpit command: {top_hint}"
        );
        assert!(
            top_hint.contains("interactive terminal"),
            "the top refusal keeps the terminal-contextual fix: {top_hint}"
        );
        let put = CoreError::InvalidInput {
            reason: "cannot read put.json".into(),
        };
        let hint = put.hint().expect("hint required");
        assert!(
            hint.contains("--file") && hint.contains("stdin"),
            "resource-put hint unchanged: {hint}"
        );

        // The EAM controller state gate (07-02): the hint names the
        // manual flip recipe + the README section (role decisions
        // stay one config-PUT away from the CLI, never one flag).
        let controller = CoreError::EamNotController { endpoint: None };
        let hint = controller.hint().expect("hint required");
        assert!(
            hint.contains("installMode"),
            "controller hint names the flip: {hint}"
        );
        assert!(
            hint.contains("Controller"),
            "controller hint names the target role: {hint}"
        );
        assert!(
            hint.contains("README"),
            "controller hint points at the README section: {hint}"
        );

        // The refused task-type ladder top (07-02 Task 3): the hint
        // names the EAM console + the v2 scope pointer.
        let refused = CoreError::EamTaskTypeRefused {
            task_type: "eam_restoreBackup".into(),
        };
        assert_eq!(refused.exit_code(), 6, "target state");
        let hint = refused.hint().expect("hint required");
        assert!(
            hint.contains("EAM console"),
            "refused hint names where to run it: {hint}"
        );
        assert!(
            hint.contains("fleet-wide") || hint.contains("EXT-03"),
            "refused hint names the fleet consequence / scope: {hint}"
        );

        // The force-route 409 (07-06 gap 4): the hint names the
        // resolution — complete or delete the leftover '(forced)'
        // run via the EAM console (no ign verb deletes runs).
        let in_flight = CoreError::EamTaskInFlight {
            task: "cli-research-backup".into(),
            detail: "the previous '(forced)' run must be completed or deleted first".into(),
            endpoint: None,
        };
        assert_eq!(in_flight.exit_code(), 6, "target state");
        let hint = in_flight.hint().expect("hint required");
        assert!(
            hint.contains("EAM console"),
            "in-flight hint names where to resolve it: {hint}"
        );
        assert!(
            hint.contains("complete or delete"),
            "in-flight hint names the resolution: {hint}"
        );

        // The scriptExec structural gate (07-03): the hint names the
        // deploy flag VERBATIM — the flag IS the opt-in (no --yes
        // exists on script run).
        let unconfigured = CoreError::ScriptExecNotConfigured {
            profile: "dev".into(),
        };
        assert_eq!(unconfigured.exit_code(), 6, "target state");
        let hint = unconfigured.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy --with-script-exec"),
            "the hint names the deploy flag verbatim: {hint}"
        );

        // Totality: no class silently loses its hint later.
        let no_active = CoreError::NoActiveProfile;
        assert!(no_active.hint().is_some());
    }

    /// The failure envelope's serialized field order and endpoint population
    /// are contract: `ok`, `profile`, `error` / `code`, `message`,
    /// `endpoint`, `hint` (string-level comparison because `serde_json::Value`
    /// maps are key-sorted and would hide ordering).
    #[test]
    fn error_envelope_locked_shape_and_endpoint() {
        let auth = CoreError::Auth {
            status: 401,
            endpoint: Some("https://gw.example.com/data/api/v1/gateway-info".into()),
        };
        let envelope: ErrorEnvelope<'_> = auth.envelope(Some("dev"));
        let json = serde_json::to_string(&envelope).expect("serialize envelope");

        assert_eq!(
            json,
            concat!(
                r#"{"ok":false,"profile":"dev","error":{"code":"auth_rejected","#,
                r#""message":"gateway rejected credentials (HTTP 401)","#,
                r#""endpoint":"https://gw.example.com/data/api/v1/gateway-info","#,
                r#""hint":"token not recognized — the X-Ignition-API-Token header must be the FULL `name:key` string from the gateway UI (Platform→Security→API Keys); Basic auth does not work on 8.3 /data routes — create an API token"}}"#
            )
        );

        // Classes without a request involved carry no endpoint.
        let no_request = CoreError::NoActiveProfile;
        let body: &ErrorBody = &no_request.envelope(None).error;
        assert_eq!(body.endpoint, None);
    }

    /// The api-call body cap (09-01): a body at or under
    /// [`GATEWAY_CLIENT_BODY_CAP_BYTES`] rides verbatim (no marker); a
    /// larger body is truncated to the cap on a UTF-8 char boundary with
    /// the exact ASCII marker appended — and the cap is enforced at
    /// CONSTRUCTION, so the variant always carries its final form.
    #[test]
    fn truncates_at_cap_with_marker() {
        // Under the cap: byte-identical passthrough.
        let short = r#"{"error":{"code":"NOT_FOUND"}}"#;
        assert_eq!(truncate_api_body(short), short);
        assert!(!short.contains(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER));

        // Exactly at the cap: still verbatim (the marker only joins an
        // OVER-cap body — the boundary is <=, not <).
        let exact = "x".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES);
        assert_eq!(truncate_api_body(&exact), exact);

        // One byte over: truncated, marker appended, total size bounded.
        let over = "x".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES + 1);
        let truncated = truncate_api_body(&over);
        assert!(
            truncated.ends_with(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER),
            "truncated body must end with the explicit marker"
        );
        assert!(
            truncated.len()
                <= GATEWAY_CLIENT_BODY_CAP_BYTES + GATEWAY_CLIENT_BODY_TRUNCATION_MARKER.len(),
            "truncated body must stay within cap + marker: {}",
            truncated.len()
        );

        // A multi-byte character straddling the cap boundary does not
        // panic (the cut backs up to a char boundary) and still carries
        // the marker.
        let multibyte = "é".repeat(GATEWAY_CLIENT_BODY_CAP_BYTES); // 2 bytes each
        let truncated = truncate_api_body(&multibyte);
        assert!(truncated.ends_with(GATEWAY_CLIENT_BODY_TRUNCATION_MARKER));
        assert!(
            truncated
                .is_char_boundary(truncated.len() - GATEWAY_CLIENT_BODY_TRUNCATION_MARKER.len())
        );
    }

    /// The loss-gate hint override (11-07 gap closure): a reason with the
    /// [`LOSS_GATE_REFUSAL_REASON_PREFIX`] sentinel carries the --yes
    /// hint, while every OTHER InvalidInput reason (generic file-read)
    /// and the TTY-refusal precedent keep their hints byte-identically.
    /// The loss-gate reason is built from the CONST via format! — a
    /// string literal of the sentinel text here would be a third
    /// production-literal hit and break the prefix-uniqueness gate the
    /// plan's verify pins.
    #[test]
    fn loss_gate_hint_override_and_neighbors_unchanged() {
        // Sentinel-prefixed reason (dynamic prose after the header):
        // the --yes hint, never the file-read default.
        let loss_gate = CoreError::InvalidInput {
            reason: format!(
                "{}xml): the scan reports 2 finding(s) before the import:\nre-run \
                 with --yes to import anyway",
                LOSS_GATE_REFUSAL_REASON_PREFIX
            ),
        };
        assert_eq!(loss_gate.code(), "invalid_input", "slug unchanged");
        assert_eq!(loss_gate.exit_code(), 2, "usage class unchanged");
        let hint = loss_gate.hint().expect("hint required");
        assert!(
            hint.contains("--yes"),
            "loss-gate hint must name the --yes re-run: {hint}"
        );
        assert!(
            hint.contains("loss report above"),
            "loss-gate hint must point back at the report: {hint}"
        );
        assert!(
            !hint.contains("fix the input source"),
            "the file-read default must never leak onto the loss-gate path: {hint}"
        );

        // Generic InvalidInput: the file-read default UNCHANGED (the
        // regression pin for every other raise site).
        let generic = CoreError::InvalidInput {
            reason: "x is not valid JSON: expected value at line 1".into(),
        };
        let hint = generic.hint().expect("hint required");
        assert!(
            hint.contains("--file") && hint.contains("stdin"),
            "resource-put hint unchanged: {hint}"
        );
        assert!(
            !hint.contains("--yes"),
            "the --yes hint must not leak onto generic reasons: {hint}"
        );

        // The TTY-refusal precedent intact (06-07).
        let tty = CoreError::tui_tty_refusal();
        let hint = tty.hint().expect("hint required");
        assert!(
            hint.contains("interactive terminal"),
            "TTY hint unchanged: {hint}"
        );
        assert!(
            !hint.contains("--yes"),
            "the --yes hint must not leak onto the TTY path: {hint}"
        );
    }

    /// The testing-scoped `routes_not_deployed` hint (QUICK-p0g): a
    /// `testing/`-prefixed route names the TESTING install commands,
    /// while every other route keeps the generic `ign webdev deploy`
    /// text BYTE-identically. Both branches are pinned so a future
    /// edit cannot silently merge them — sending a caller to
    /// `ign webdev deploy` for an absent testing bundle is a hint
    /// that does not fix the error.
    #[test]
    fn routes_not_deployed_hint_is_testing_scoped() {
        let testing = CoreError::RoutesNotDeployed {
            project: "Flux".into(),
            route: format!("{TESTING_ROUTE_PREFIX}run"),
            endpoint: None,
        };
        assert_eq!(testing.code(), "routes_not_deployed", "slug unchanged");
        assert_eq!(testing.exit_code(), 6, "target-state class unchanged");
        let hint = testing.hint().expect("hint required");
        assert!(
            hint.contains("ign webdev deploy --with-testing"),
            "testing hint must name the deploy flag: {hint}"
        );
        assert!(
            hint.contains("ign adopt") && hint.contains("--testing"),
            "testing hint must name the adopt path: {hint}"
        );

        // Every non-testing route: the generic hint, unchanged.
        let generic = CoreError::RoutesNotDeployed {
            project: "ign-cli".into(),
            route: "tags".into(),
            endpoint: None,
        };
        let hint = generic.hint().expect("hint required");
        assert_eq!(
            hint,
            "run `ign webdev deploy` to install the CLI's WebDev routes into \
             the gateway, then retry",
            "the generic branch is byte-identical to its pre-QUICK-p0g text"
        );
    }

    fn finding(file: &str, line: Option<usize>, column: Option<usize>, msg: &str) -> DeployFinding {
        DeployFinding {
            file: file.into(),
            line,
            column,
            message: msg.into(),
        }
    }

    #[test]
    fn deploy_finding_display_names_file_line_column() {
        let positioned = finding("targets/prod.yaml", Some(3), Some(1), "unknown field `x`");
        assert_eq!(
            positioned.to_string(),
            "targets/prod.yaml:3:1: unknown field `x`"
        );
        let bare = finding("targets/prod.yaml", None, None, "missing field `gateway`");
        assert_eq!(
            bare.to_string(),
            "targets/prod.yaml: missing field `gateway`"
        );
        // A half-positioned finding never claims a position.
        let half = finding("m.yaml", Some(3), None, "m");
        assert_eq!(half.to_string(), "m.yaml: m");
    }

    #[test]
    fn deploy_findings_cap_at_twenty() {
        let many: Vec<DeployFinding> = (0..25)
            .map(|i| finding("manifest.yaml", None, None, &format!("problem {i}")))
            .collect();
        let shown = CoreError::deploy_findings(many).to_string();
        assert!(shown.contains("25 findings: "), "{shown}");
        assert!(shown.contains("problem 19"), "{shown}");
        assert!(!shown.contains("problem 20"), "{shown}");
        assert!(shown.ends_with("; and 5 more"), "{shown}");

        let single = CoreError::deploy_tree_invalid("m.yaml", Some(2), Some(1), "bad");
        assert_eq!(single.to_string(), "deploy tree invalid: m.yaml:2:1: bad");
    }

    #[test]
    fn embedded_secret_display_lists_paths_only() {
        let err = CoreError::embedded_secret(
            vec![
                "ignition/database-connection/A/config.json: settings.password".into(),
                "ignition/database-connection/B/config.json: settings.password".into(),
            ],
            vec![finding("manifest.yaml", None, None, "duplicate type")],
        );
        let shown = err.to_string();
        assert!(shown.contains("2 path(s)"), "{shown}");
        assert!(
            shown.contains("A/config.json: settings.password"),
            "{shown}"
        );
        assert!(
            shown.contains("B/config.json: settings.password"),
            "{shown}"
        );
        assert!(shown.contains("also 1 other tree finding(s)"), "{shown}");
        assert!(shown.contains("manifest.yaml: duplicate type"), "{shown}");

        // The combined list stays within the cap.
        let paths: Vec<String> = (0..25).map(|i| format!("f{i}.json: a.b")).collect();
        let shown =
            CoreError::embedded_secret(paths, vec![finding("m.yaml", None, None, "x")]).to_string();
        assert!(shown.contains("25 path(s)"), "{shown}");
        assert!(shown.contains("and 5 more"), "{shown}");
        assert!(shown.contains("f19.json: a.b"), "{shown}");
        assert!(!shown.contains("f20.json: a.b"), "{shown}");
    }

    #[test]
    fn deploy_slugs_have_their_exit_codes() {
        let errs = [
            (
                CoreError::deploy_tree_invalid("m.yaml", None, None, "bad"),
                2,
            ),
            (
                CoreError::embedded_secret(vec!["a.json: p".into()], vec![]),
                2,
            ),
            (
                CoreError::TransportFailed {
                    operation: "read".into(),
                    node: "nodes.master".into(),
                    detail: "data_dir is missing".into(),
                },
                4,
            ),
            (
                CoreError::DeployLedgerInvalid {
                    location: "ign-deploy/gw/dev/ledger.json".into(),
                    problem: "the file is empty".into(),
                },
                6,
            ),
            (
                CoreError::PlanStale {
                    expected: "a".repeat(64),
                    actual: "b".repeat(64),
                    detail: "review hash".into(),
                },
                6,
            ),
            (
                CoreError::DestructiveChangeRefused {
                    gate: "destructive".into(),
                    keys: vec!["ignition/a/x".into()],
                    count: 1,
                },
                2,
            ),
            (
                CoreError::DeployBlocked {
                    keys: vec!["ignition/a/x".into()],
                },
                6,
            ),
            (
                CoreError::DeployPreflightFailed {
                    failures: vec![PreflightFailure {
                        check: "mode_master".into(),
                        detail: "the gateway is not in the declared mode".into(),
                    }]
                    .into(),
                },
                6,
            ),
            (
                CoreError::DeployJournalPresent {
                    run_id: "20261015T142233Z-a1b2c3".into(),
                    env: "prod".into(),
                    location: "ign-deploy/gw/m/journal.json".into(),
                },
                6,
            ),
            (
                CoreError::DeployLiveChanged {
                    run_id: "r1".into(),
                    paths: vec!["a/b.json".into()],
                    count: 1,
                },
                6,
            ),
            (
                CoreError::DeployRunInvalid {
                    run_id: "r1".into(),
                    problem: "record.json is missing".into(),
                },
                6,
            ),
            (
                CoreError::RollbackFailed(Box::new(RollbackFailure {
                    run_id: "r1".into(),
                    env: "dev".into(),
                    run_dir: Some(".ign/deploy/r1".into()),
                    journal: "ign-deploy/gw/m/journal.json".into(),
                    cause: "write_failed".into(),
                })),
                6,
            ),
            (
                CoreError::ProjectGitManaged {
                    project: "CapApp".into(),
                    location: "projects/CapApp/.git".into(),
                    kind: "directory".into(),
                },
                6,
            ),
            (
                CoreError::ProjectParentInvalid {
                    project: "CapApp".into(),
                    parent: "WHK-Global".into(),
                    reason: "cycle".into(),
                },
                6,
            ),
            (
                CoreError::ProjectHashMismatch {
                    project: "CapApp".into(),
                    expected: "0".repeat(64),
                    actual: "1".repeat(64),
                },
                6,
            ),
            (
                CoreError::DeployUnreadable {
                    node: "master".into(),
                    keys: vec!["ignition/tag-definition/default/Deep".into()],
                },
                6,
            ),
        ];
        let codes: Vec<&str> = errs.iter().map(|(e, _)| e.code()).collect();
        assert_eq!(codes, CoreError::DEPLOY_SLUGS);
        for (err, exit) in &errs {
            assert_eq!(err.exit_code(), *exit, "{err}");
            assert_eq!(err.endpoint(), None, "deploy errors name no URL: {err}");
            let hint = err.hint().expect("hint required");
            assert!(
                !hint.contains("`ign ") && !hint.contains("ign "),
                "hint must not name an ign subcommand: {hint}"
            );
        }
    }

    #[test]
    fn apply_gate_flag_refusals_do_not_get_the_file_hint() {
        for reason in [
            "--plan-sha256 must be 64 lowercase hex characters",
            "--allow-drift reason must not be empty",
            "--artifact-sha256 must be 64 lowercase hex characters",
            "--release <tag>: not a semver tag (for example v1.4.0)",
            "--allow-first-change <reason>: the reason is 1 to 500 characters",
            "deploy projects needs --artifact-sha256 when --json is given",
        ] {
            let hint = CoreError::InvalidInput {
                reason: reason.into(),
            }
            .hint()
            .expect("hint");
            assert!(!hint.contains("--file"), "{hint}");
            assert!(hint.contains("flag value"), "{hint}");
        }
    }

    /// The exact ordered deploy slug list. Verdicts (`deploy_rolled_back`,
    /// `deploy_backup_unsynced`, `deploy_project_unverified`) are payload
    /// slugs on a success envelope and never `CoreError` codes. Later plans
    /// extend this list in README row order (25-09, 25-10, 25-11).
    #[test]
    fn deploy_slugs_are_pinned_and_never_a_verdict() {
        assert_eq!(
            CoreError::DEPLOY_SLUGS,
            &[
                "deploy_tree_invalid",
                "embedded_secret",
                "transport_failed",
                "deploy_ledger_invalid",
                "plan_stale",
                "destructive_change_refused",
                "deploy_blocked",
                "deploy_preflight_failed",
                "deploy_journal_present",
                "deploy_live_changed",
                "deploy_run_invalid",
                "rollback_failed",
                "project_git_managed",
                "project_parent_invalid",
                "project_hash_mismatch",
                "deploy_unreadable",
            ]
        );
        assert_eq!(CoreError::DEPLOY_SLUGS.len(), 16);
        for verdict in [
            "deploy_rolled_back",
            "deploy_backup_unsynced",
            "deploy_project_unverified",
        ] {
            assert!(!CoreError::DEPLOY_SLUGS.contains(&verdict), "{verdict}");
        }
    }

    /// 25-07: the four-place rule for `project_git_managed` (variant, code,
    /// exit class 6, hint) and the message names what the operator needs.
    #[test]
    fn project_git_managed_four_places() {
        let err = CoreError::ProjectGitManaged {
            project: "CapApp".into(),
            location: "projects/CapApp/.git".into(),
            kind: "directory".into(),
        };
        assert_eq!(err.code(), "project_git_managed");
        assert_eq!(err.exit_code(), 6);
        let message = err.to_string();
        for needle in [
            "CapApp",
            "projects/CapApp/.git",
            "directory",
            "administrator",
        ] {
            assert!(message.contains(needle), "{needle}: {message}");
        }
        let hint = err.hint().expect("hint required");
        assert!(!hint.contains("ign "), "{hint}");
        assert!(hint.contains(".git"), "{hint}");
        assert!(CoreError::DEPLOY_SLUGS.contains(&"project_git_managed"));
    }

    /// 25-10: the four-place rule for `project_parent_invalid` (variant,
    /// code, exit class 6, hint per reason) and the message names the
    /// project, the parent and the reason.
    #[test]
    fn project_parent_invalid_four_places() {
        for (reason, needle) in [
            ("missing", "its own repo"),
            ("cycle", "no cycle"),
            ("not_inheritable", "inheritable"),
        ] {
            let err = CoreError::ProjectParentInvalid {
                project: "CapApp".into(),
                parent: "WHK-Global".into(),
                reason: reason.into(),
            };
            assert_eq!(err.code(), "project_parent_invalid");
            assert_eq!(err.exit_code(), 6);
            let message = err.to_string();
            for part in ["CapApp", "WHK-Global", reason] {
                assert!(message.contains(part), "{part}: {message}");
            }
            let hint = err.hint().expect("hint required");
            assert!(!hint.contains("ign "), "{hint}");
            assert!(hint.contains(needle), "{reason}: {hint}");
            assert_eq!(err.endpoint(), None);
        }
        assert!(CoreError::DEPLOY_SLUGS.contains(&"project_parent_invalid"));
    }

    /// 25-11: the four-place rule for `project_hash_mismatch` (variant, code,
    /// exit class 6, hint). The message names the project and both hashes and
    /// says nothing was uploaded; nothing else rides it (SC-1, D-01).
    #[test]
    fn project_hash_mismatch_four_places() {
        let err = CoreError::ProjectHashMismatch {
            project: "CapApp".into(),
            expected: "0".repeat(64),
            actual: "1".repeat(64),
        };
        assert_eq!(err.code(), "project_hash_mismatch");
        assert_eq!(err.exit_code(), 6);
        let message = err.to_string();
        for part in [
            "CapApp",
            "0000000000000000000000000000000000000000000000000000000000000000",
            "1111111111111111111111111111111111111111111111111111111111111111",
            "nothing was uploaded",
        ] {
            assert!(message.contains(part), "{part}: {message}");
        }
        let hint = err.hint().expect("hint required");
        assert!(!hint.contains("ign "), "{hint}");
        assert!(hint.contains("artifact_sha256"), "{hint}");
        assert_eq!(err.endpoint(), None);
        assert!(CoreError::DEPLOY_SLUGS.contains(&"project_hash_mismatch"));
    }

    /// quick-261029-ms3: the four-place rule for `deploy_unreadable`
    /// (variant, code, exit class 6, hint). The message names every unit,
    /// says the host's sftp server cannot read its live path and that nothing
    /// was written; the hint names the two fixes and no `ign` subcommand.
    #[test]
    fn deploy_unreadable_four_places() {
        let keys = vec![
            "ignition/database-translator/OLD".to_string(),
            "ignition/tag-definition/default/Deep".to_string(),
        ];
        let err = CoreError::DeployUnreadable {
            node: "backup".to_string(),
            keys: keys.clone(),
        };
        assert_eq!(err.code(), "deploy_unreadable");
        assert_eq!(err.exit_code(), 6);
        assert_eq!(err.endpoint(), None);
        let message = err.to_string();
        for part in keys.iter().map(String::as_str).chain([
            "backup host's sftp server cannot read",
            "nothing was written",
            "2 unit(s)",
        ]) {
            assert!(message.contains(part), "{part}: {message}");
        }
        let hint = err.hint().expect("hint required");
        assert!(!hint.contains("ign "), "{hint}");
        assert!(hint.contains("exclude_tag_providers"), "{hint}");
        assert!(hint.contains("shorten"), "{hint}");
        assert!(CoreError::DEPLOY_SLUGS.contains(&"deploy_unreadable"));
    }

    /// 25-11 (K15): a stale live project is told apart from a stale plan
    /// hash, and neither hint names an `ign` subcommand.
    #[test]
    fn plan_stale_hint_names_the_live_project_case() {
        let live = CoreError::PlanStale {
            expected: "a".repeat(64),
            actual: "b".repeat(64),
            detail: "live project changed since the plan".into(),
        };
        let hint = live.hint().expect("hint");
        assert!(hint.contains("live project"), "{hint}");
        assert!(hint.contains("nothing was imported"), "{hint}");
        assert!(!hint.contains("ign "), "{hint}");
        let review = CoreError::PlanStale {
            expected: "a".repeat(64),
            actual: "b".repeat(64),
            detail: "review hash".into(),
        };
        assert!(
            review.hint().expect("hint").contains("plan_sha256"),
            "the plan-hash case keeps its hint"
        );
    }

    #[test]
    fn journal_present_message_carries_the_recovery_command() {
        let err = CoreError::DeployJournalPresent {
            run_id: "20261015T142233Z-a1b2c3".into(),
            env: "prod".into(),
            location: "ign-deploy/gw/m/journal.json".into(),
        };
        let shown = err.to_string();
        assert!(
            shown.contains("ign deploy rollback --run 20261015T142233Z-a1b2c3 --env prod"),
            "{shown}"
        );
        assert!(shown.contains("ign-deploy/gw/m/journal.json"), "{shown}");
        let hint = err.hint().expect("hint");
        assert!(
            !hint.contains("ign deploy"),
            "D-09: the command lives in Display: {hint}"
        );
    }

    #[test]
    fn rollback_failed_message_names_run_dir_journal_and_the_guidance() {
        let err = CoreError::RollbackFailed(Box::new(RollbackFailure {
            run_id: "r-7".into(),
            env: "prod".into(),
            run_dir: Some(".ign/deploy/r-7".into()),
            journal: "ign-deploy/gw/m/journal.json".into(),
            cause: "write_failed".into(),
        }));
        let shown = err.to_string();
        for needle in [
            "r-7",
            ".ign/deploy/r-7",
            "ign-deploy/gw/m/journal.json",
            ".gwbk",
            "snapshot",
            "by hand",
            // The retry comes first, with the real env, and the intact
            // pre-images are the on-box directory (review WR-02).
            "ign deploy rollback --run r-7 --env prod",
            "ign-deploy/gw/m/snapshots/r-7/",
        ] {
            assert!(shown.contains(needle), "{needle} missing from: {shown}");
        }
        assert!(
            shown.find("Retry with").expect("retry") < shown.find("by hand").expect("by hand"),
            "the retry precedes the hand deletion: {shown}"
        );
        assert!(
            !shown.contains("run-directory snapshot"),
            "the run directory has no snapshot to offer: {shown}"
        );
        let hint = err.hint().expect("hint");
        assert!(
            hint.contains("retry") && !hint.contains("run-directory snapshot"),
            "{hint}"
        );
        let none = CoreError::RollbackFailed(Box::new(RollbackFailure {
            run_id: "r-7".into(),
            env: "prod".into(),
            run_dir: None,
            journal: "j".into(),
            cause: "c".into(),
        }));
        assert!(!none.to_string().contains("None"), "{none}");
    }

    #[test]
    fn preflight_failed_lists_every_failure_in_order() {
        let err = CoreError::DeployPreflightFailed {
            failures: vec![
                PreflightFailure {
                    check: "mode_master".into(),
                    detail: "first".into(),
                },
                PreflightFailure {
                    check: "gwbk".into(),
                    detail: "second".into(),
                },
            ]
            .into(),
        };
        let shown = err.to_string();
        let first = shown.find("mode_master: first").expect("first");
        let second = shown.find("gwbk: second").expect("second");
        assert!(first < second, "{shown}");
        assert_eq!(shown.lines().count(), 3, "{shown}");
    }

    #[test]
    fn apply_refusal_lists_cap_at_ten() {
        let keys: Vec<String> = (0..10).map(|i| format!("u{i}")).collect();
        let shown = CoreError::DestructiveChangeRefused {
            gate: "destructive".into(),
            keys: keys.clone(),
            count: 13,
        }
        .to_string();
        assert!(shown.contains("13 entries"), "{shown}");
        assert!(shown.contains("and 3 more"), "{shown}");
        assert!(shown.contains("--allow-destructive"), "{shown}");
        let drift = CoreError::DestructiveChangeRefused {
            gate: "drift".into(),
            keys: keys[..1].to_vec(),
            count: 1,
        }
        .to_string();
        assert!(drift.contains("--allow-drift"), "{drift}");
        assert!(drift.contains("1 entry"), "{drift}");
        let downgrade = CoreError::DestructiveChangeRefused {
            gate: "downgrade".into(),
            keys: vec!["CapApp".into()],
            count: 1,
        };
        let shown = downgrade.to_string();
        assert!(shown.contains("downgrade"), "{shown}");
        assert!(shown.contains("CapApp"), "{shown}");
        assert!(
            shown.contains("deploy projects needs --allow-downgrade"),
            "{shown}"
        );
        assert!(!shown.contains("apply needs"), "{shown}");
        let first = CoreError::DestructiveChangeRefused {
            gate: "first_deploy".into(),
            keys: vec!["CapApp".into()],
            count: 1,
        };
        let shown = first.to_string();
        assert!(shown.contains("first_deploy"), "{shown}");
        assert!(
            shown.contains("deploy projects needs --allow-first-change <reason>"),
            "{shown}"
        );
        // each gate has its own hint, and none names an `ign` command
        let hints: Vec<String> = [&downgrade, &first]
            .iter()
            .map(|e| e.hint().expect("hint"))
            .collect();
        assert!(hints[0].contains("--allow-downgrade"), "{}", hints[0]);
        assert!(hints[1].contains("--allow-first-change"), "{}", hints[1]);
        for hint in &hints {
            assert!(!hint.contains("ign "), "{hint}");
            assert!(!hint.contains("--allow-destructive"), "{hint}");
        }

        let many: Vec<String> = (0..25).map(|i| format!("a/{i:02}")).collect();
        let blocked = CoreError::DeployBlocked { keys: many.clone() }.to_string();
        assert!(blocked.contains("and 15 more"), "{blocked}");
        assert!(!blocked.contains("a/10"), "{blocked}");
        let live = CoreError::DeployLiveChanged {
            run_id: "r".into(),
            paths: many[..10].to_vec(),
            count: 12,
        }
        .to_string();
        assert!(live.contains("and 2 more"), "{live}");
    }
}