ignition-cli 1.6.4

ign — operate Ignition 8.3+ gateways from the terminal
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
//! Binary-level contract for `ign deploy projects --check` (25-04, DPRJ-05).
//!
//! The check reads `deploy/project.yaml`, builds the artifact from the
//! checkout and compares it with the live project over GET requests only.
//! Every test here drives the real binary against a wiremock gateway and
//! asserts on what the gateway received as well as on the envelope.

mod common;

use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use common::verify_ign;
use serde_json::{Value, json};
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};

const SCRIPT_RESOURCE: &str = r#"{"scope":"A","files":["code.py"],"attributes":{"enabled":true}}"#;
const CODE_V1: &[u8] = b"def f():\n    return 1\n";
const CODE_V2: &[u8] = b"def f():\n    return 2\n";

fn put(root: &Path, rel: &str, bytes: &[u8]) {
    let target = root.join(rel);
    std::fs::create_dir_all(target.parent().expect("parent")).expect("mkdir");
    std::fs::write(target, bytes).expect("write");
}

/// A project repo for project `CapApp`, deployable to `dev`, plus a targets
/// root holding `targets/dev.yaml` whose master profile is `dev`.
struct Fixture {
    _scratch: tempfile::TempDir,
    repo: PathBuf,
    targets: PathBuf,
    /// The master node's data directory; `projects/` exists and is empty.
    data: PathBuf,
}

fn fixture() -> Fixture {
    let scratch = tempfile::tempdir().expect("tempdir");
    let repo = scratch.path().join("repo");
    let targets = scratch.path().join("targets-root");
    let data = scratch.path().join("data");
    std::fs::create_dir_all(data.join("projects")).expect("data dir");
    put(
        &repo,
        "project.json",
        br#"{"title":"Cap App","enabled":true}"#,
    );
    put(
        &repo,
        "deploy/project.yaml",
        b"schema_version: 1\nproject: CapApp\nenvironments: [dev]\n",
    );
    put(
        &repo,
        "ignition/script-python/cap/resource.json",
        SCRIPT_RESOURCE.as_bytes(),
    );
    put(&repo, "ignition/script-python/cap/code.py", CODE_V1);
    // Not part of the artifact.
    put(&repo, "docs/notes.md", b"not shipped");
    // The host's own name: a confirmed run compares it with the name the
    // gateway reports over REST before it writes anything (25-14).
    put(
        &data,
        "config/resources/core/ignition/system-properties/config.json",
        br#"{"systemName":"capgw"}"#,
    );
    put(
        &targets,
        "targets/dev.yaml",
        format!(
            "schema_version: 1\ngateway: capgw\nmode: dev\nnodes:\n  master:\n    profile: dev\n    local:\n      data_dir: '{}'\n",
            data.display()
        )
        .as_bytes(),
    );
    Fixture {
        _scratch: scratch,
        repo,
        targets,
        data,
    }
}

/// An export zip of the project: the same members as the fixture repo with
/// `code` as the script body. `stamp` adds the volatile `lastModification`
/// attributes the gateway writes into `resource.json`, and the
/// `description` and `parent` keys it adds to `project.json`.
fn export_zip(code: &[u8], stamp: bool) -> Vec<u8> {
    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
    let opts = zip::write::SimpleFileOptions::default();
    let project = if stamp {
        r#"{"title":"Cap App","enabled":true,"description":"","parent":""}"#
    } else {
        r#"{"title":"Cap App","enabled":true}"#
    };
    let resource = if stamp {
        r#"{"scope":"A","files":["code.py"],"attributes":{"enabled":true,"lastModification":{"actor":"admin","timestamp":"2026-10-22T10:00:00Z"},"lastModificationSignature":"abc"}}"#
    } else {
        SCRIPT_RESOURCE
    };
    for (name, bytes) in [
        ("project.json", project.as_bytes()),
        (
            "ignition/script-python/cap/resource.json",
            resource.as_bytes(),
        ),
        ("ignition/script-python/cap/code.py", code),
    ] {
        writer.start_file(name, opts).expect("start");
        writer.write_all(bytes).expect("write");
    }
    writer.finish().expect("finish").into_inner()
}

async fn mount_list(server: &MockServer, names: &[&str]) {
    let items: Vec<Value> = names
        .iter()
        .map(|n| json!({"name": n, "enabled": true}))
        .collect();
    let total = items.len();
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": items,
            "metadata": {"total": total, "matching": total, "limit": -1, "offset": 0}
        })))
        .mount(server)
        .await;
}

async fn mount_find_found(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/find/CapApp"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"name": "CapApp", "title": "Cap App", "enabled": true})),
        )
        .mount(server)
        .await;
}

async fn mount_find_missing(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/find/CapApp"))
        .respond_with(
            ResponseTemplate::new(404).set_body_json(json!({"message": "Project not found"})),
        )
        .mount(server)
        .await;
}

async fn mount_export(server: &MockServer, zip: Vec<u8>) {
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/export/CapApp"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_raw(zip, "application/zip")
                .insert_header(
                    "Content-Disposition",
                    "attachment; filename=\"CapApp-export.zip\"",
                ),
        )
        .mount(server)
        .await;
}

fn check_args(fx: &Fixture, env: &str) -> Vec<String> {
    vec![
        "--json".into(),
        "deploy".into(),
        "projects".into(),
        "--env".into(),
        env.into(),
        "--release".into(),
        "v1.0.0".into(),
        "--check".into(),
        "--repo".into(),
        fx.repo.display().to_string(),
        "--targets".into(),
        fx.targets.display().to_string(),
    ]
}

fn run(server: &MockServer, args: &[String]) -> std::process::Output {
    let (_dir, mut cmd) = verify_ign(&server.uri());
    cmd.args(args).output().expect("spawn ign")
}

fn data_of(out: &std::process::Output) -> Value {
    assert_eq!(
        out.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope: Value = serde_json::from_slice(&out.stdout).expect("envelope");
    assert_eq!(envelope["ok"], true);
    envelope["data"].clone()
}

async fn methods(server: &MockServer) -> Vec<(String, String)> {
    server
        .received_requests()
        .await
        .expect("request recording is on")
        .iter()
        .map(|r| (r.method.to_string(), r.url.path().to_string()))
        .collect()
}

fn assert_only_gets(requests: &[(String, String)]) {
    assert!(!requests.is_empty(), "the check must read the gateway");
    for (verb, url) in requests {
        assert_eq!(verb, "GET", "{url}: a check sends GET requests only");
    }
}

fn is_hex64(value: &Value) -> bool {
    value
        .as_str()
        .is_some_and(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()))
}

#[tokio::test]
async fn projects_check_reports_import() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V2, true)).await;

    // No release record: the first `ign` deploy of this project, which
    // differs from the gateway, needs its reason (D-12).
    let out = run(
        &server,
        &args_with(&fx, "v1.0.0", &["--allow-first-change", "adopt the repo"]),
    );
    let data = data_of(&out);
    assert_eq!(data["action"], "import");
    assert_eq!(data["allow_first_change"], "adopt the repo");
    assert!(data["previous_release"].is_null());
    assert_eq!(data["would_change"], true);
    assert_eq!(data["members"]["changed"], 1);
    assert_eq!(data["members"]["same"], 2);
    assert_eq!(data["members"]["added"], 0);
    assert_eq!(data["members"]["removed"], 0);
    assert_eq!(data["check"], true);
    assert_eq!(data["outcome"], "checked");
    assert_eq!(data["project"], "CapApp");
    assert_eq!(data["gateway"], "capgw");
    assert_eq!(data["release"], "v1.0.0");
    assert_eq!(data["env"], "dev");
    assert!(is_hex64(&data["artifact_sha256"]), "{data}");
    assert!(is_hex64(&data["live_sha256"]), "{data}");
    assert_ne!(data["artifact_sha256"], data["live_sha256"]);
    assert_eq!(data["removed"], json!([]));
    assert_eq!(data["ok"], true);
    assert!(data["slug"].is_null());
    assert_only_gets(&methods(&server).await);
}

/// K14: an unchanged project with no record plans the record only; once the
/// record names this release and this content, nothing is planned. The record
/// is written the way the last deploy left it, with the digest the first check
/// reported.
#[tokio::test]
async fn projects_check_reports_skip() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let first = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(first["action"], "record");
    let sha = first["artifact_sha256"].as_str().expect("sha").to_string();
    put_record_sha(&fx, "v1.0.0", &sha);

    let out = run(&server, &check_args(&fx, "dev"));
    let data = data_of(&out);
    assert_eq!(data["action"], "skip");
    assert_eq!(data["would_change"], false);
    assert_eq!(data["artifact_sha256"], data["live_sha256"]);
    assert_eq!(data["recorded_sha256"], sha.as_str());
    assert_eq!(data["live_matches_last_deploy"], true);
    assert_eq!(data["warnings"], json!([]));
    assert_eq!(data["members"]["changed"], 0);
    assert_eq!(data["members"]["same"], 3);
    assert_only_gets(&methods(&server).await);
}

/// K14, D-12: the git module left the project as the repo has it, no record:
/// only the record is planned, and it counts as a change.
#[tokio::test]
async fn projects_check_reports_record() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(data["action"], "record");
    assert_eq!(data["would_change"], true);
    assert_eq!(data["artifact_sha256"], data["live_sha256"]);
    assert!(data["previous_release"].is_null());
    assert!(data["recorded_sha256"].is_null());
    assert!(data["live_matches_last_deploy"].is_null());
    assert!(data["allow_first_change"].is_null());
    assert_only_gets(&methods(&server).await);

    // A newer release over unchanged content records the release too.
    put_record(&fx, "v0.9.0");
    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(data["action"], "record");
    assert_eq!(data["previous_release"], "v0.9.0");
}

/// D-12, V3: no record and a gateway project that differs: the check refuses
/// like the apply would, naming the gate, the project and the flag.
#[tokio::test]
async fn projects_check_first_deploy_change_refuses() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V2, true)).await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "destructive_change_refused");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["first_deploy", "CapApp", "--allow-first-change"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert_only_gets(&methods(&server).await);
}

/// K13: the gateway no longer holds what `ign` last deployed. A warning in
/// the result, not a refusal.
#[tokio::test]
async fn projects_check_live_drift_warns() {
    let fx = fixture();
    put_record(&fx, "v0.9.0");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V2, true)).await;

    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(data["action"], "import");
    assert_eq!(data["live_matches_last_deploy"], false);
    assert_eq!(data["recorded_sha256"], "a".repeat(64));
    let warnings = data["warnings"].as_array().expect("warnings");
    assert_eq!(warnings.len(), 1, "{data}");
    let text = warnings[0].as_str().expect("text");
    assert!(text.contains("CapApp") && text.contains("v0.9.0"), "{text}");
}

#[tokio::test]
async fn projects_check_reports_create() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &[]).await;
    mount_find_missing(&server).await;

    let out = run(&server, &check_args(&fx, "dev"));
    let data = data_of(&out);
    assert_eq!(data["action"], "create");
    assert_eq!(data["would_change"], true);
    assert!(data["live_sha256"].is_null());
    assert!(is_hex64(&data["artifact_sha256"]));
    assert_eq!(data["members"]["added"], 3);
    let requests = methods(&server).await;
    assert_only_gets(&requests);
    assert!(
        requests.iter().all(|(_, url)| !url.contains("/export/")),
        "an absent project has nothing to export: {requests:?}"
    );
}

#[tokio::test]
async fn projects_check_lists_unmanaged() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp", "Other", "Global"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, false)).await;

    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(data["unmanaged"], json!(["Global", "Other"]));
    assert_eq!(data["unmanaged_count"], 2);
    let requests = methods(&server).await;
    assert_only_gets(&requests);
    assert!(
        requests
            .iter()
            .all(|(_, url)| !url.contains("Other") && !url.contains("Global")),
        "other projects are listed by name and never read: {requests:?}"
    );
}

#[tokio::test]
async fn projects_check_reports_removed_members() {
    let fx = fixture();
    let server = MockServer::start().await;
    // The live project holds a member the repo lacks.
    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
    let opts = zip::write::SimpleFileOptions::default();
    for (name, bytes) in [
        (
            "project.json",
            br#"{"title":"Cap App","enabled":true}"#.as_slice(),
        ),
        (
            "ignition/script-python/cap/resource.json",
            SCRIPT_RESOURCE.as_bytes(),
        ),
        ("ignition/script-python/cap/code.py", CODE_V1),
        ("ignition/script-python/old/code.py", b"gone"),
        (
            "ignition/script-python/old/resource.json",
            br#"{"files":["code.py"]}"#.as_slice(),
        ),
    ] {
        writer.start_file(name, opts).expect("start");
        writer.write_all(bytes).expect("write");
    }
    let live = writer.finish().expect("finish").into_inner();
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, live).await;

    let data = data_of(&run(
        &server,
        &args_with(&fx, "v1.0.0", &["--allow-first-change", "adopt"]),
    ));
    assert_eq!(data["action"], "import");
    assert_eq!(data["members"]["removed"], 2);
    assert_eq!(data["removed_count"], 2);
    assert_eq!(
        data["removed"],
        json!([
            "ignition/script-python/old/code.py",
            "ignition/script-python/old/resource.json"
        ])
    );
}

#[tokio::test]
async fn projects_check_env_not_listed() {
    let fx = fixture();
    // A target file for prod exists; the project file does not list it.
    put(
        &fx.targets,
        "targets/prod.yaml",
        std::fs::read(fx.targets.join("targets/dev.yaml"))
            .expect("dev target")
            .as_slice(),
    );
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "prod"));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(out.stdout.is_empty(), "a refusal leaves stdout empty");
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr envelope");
    assert_eq!(err["error"]["code"], "deploy_tree_invalid");
    assert!(
        err["error"]["message"]
            .as_str()
            .expect("message")
            .contains("deploy/project.yaml"),
        "{err}"
    );
    assert!(
        methods(&server).await.is_empty(),
        "the refusal comes before any request"
    );
}

#[tokio::test]
async fn projects_check_creates_no_ign_dir() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V2, true)).await;

    let out = run(
        &server,
        &args_with(&fx, "v1.0.0", &["--allow-first-change", "adopt"]),
    );
    data_of(&out);
    assert!(
        !fx.repo.join(".ign").exists(),
        "a check writes no run directory"
    );
    assert!(!fx.targets.join(".ign").exists());
    // The check also left the repo exactly as it was.
    assert!(!fx.repo.join("deploy/.ign").exists());
}

#[tokio::test]
async fn projects_check_targets_default_to_the_repo() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;
    // Move the target file into the repo and drop `--targets`.
    let bytes = std::fs::read(fx.targets.join("targets/dev.yaml")).expect("target");
    put(&fx.repo, "targets/dev.yaml", &bytes);
    let mut args = check_args(&fx, "dev");
    let at = args.iter().position(|a| a == "--targets").expect("flag");
    args.drain(at..=at + 1);

    let data = data_of(&run(&server, &args));
    assert_eq!(data["action"], "record", "equal content, no record yet");
}

#[tokio::test]
async fn projects_check_missing_project_json_refuses() {
    let fx = fixture();
    std::fs::remove_file(fx.repo.join("project.json")).expect("rm");
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(out.status.code(), Some(2));
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr envelope");
    assert_eq!(err["error"]["code"], "deploy_tree_invalid");
    assert!(
        err["error"]["message"]
            .as_str()
            .expect("message")
            .contains("a project repo holds project.json at its root"),
        "{err}"
    );
    assert!(methods(&server).await.is_empty());
}

#[cfg(unix)]
#[tokio::test]
async fn projects_check_symlink_in_the_walk_refuses() {
    let fx = fixture();
    let outside = tempfile::tempdir().expect("outside");
    std::fs::write(outside.path().join("secret.txt"), b"secret").expect("write");
    std::os::unix::fs::symlink(
        outside.path().join("secret.txt"),
        fx.repo.join("ignition/script-python/cap/link.py"),
    )
    .expect("symlink");
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(out.status.code(), Some(2));
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr envelope");
    assert_eq!(err["error"]["code"], "deploy_tree_invalid");
    let message = err["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("ignition/script-python/cap/link.py"),
        "{message}"
    );
    assert!(!message.contains("secret"), "{message}");
    assert!(methods(&server).await.is_empty());
}

#[tokio::test]
async fn projects_check_human_lines() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp", "Other"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V2, true)).await;
    let mut args = args_with(&fx, "v1.0.0", &["--allow-first-change", "adopt the repo"]);
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(
        stdout.contains("project CapApp on capgw (env dev, release v1.0.0)"),
        "{stdout}"
    );
    assert!(stdout.contains("check: import (would change)"), "{stdout}");
    assert!(
        stdout.contains("release: v1.0.0 (last deployed by this tool: none)"),
        "{stdout}"
    );
    assert!(
        stdout.contains("first change allowed: adopt the repo"),
        "{stdout}"
    );
    assert!(stdout.contains("artifact sha256 "), "{stdout}");
    assert!(
        stdout.contains("members: 0 added, 1 changed, 0 removed, 2 same"),
        "{stdout}"
    );
    assert!(
        stdout.contains("other projects on the gateway: 1"),
        "{stdout}"
    );
}

/// Put the noise a real checkout carries into the fixture repo, and an
/// `.ignexclude` that removes a scratch script package that would otherwise
/// ship.
fn add_noise(repo: &Path) {
    put(repo, "tags/t.json", b"{}");
    put(repo, "images/i.png", b"png");
    put(
        repo,
        "ignition/script-python/cap/__pycache__/code.cpython-311.pyc",
        b"pyc",
    );
    put(repo, "ignition/script-python/cap/notes.txt", b"unlisted");
    put(repo, "ignition/.git/HEAD", b"ref: refs/heads/main");
    put(repo, ".ign/deploy/gw/run/export/x.zip", b"a previous run");
    put(
        repo,
        "ignition/script-python/scratch/resource.json",
        br#"{"files":["s.py"]}"#,
    );
    put(repo, "ignition/script-python/scratch/s.py", b"pass");
    put(repo, ".ignexclude", b"ignition/script-python/scratch/\n");
}

#[tokio::test]
async fn projects_check_reports_excluded() {
    let fx = fixture();
    add_noise(&fx.repo);
    let server = MockServer::start().await;
    mount_list(&server, &[]).await;
    mount_find_missing(&server).await;

    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(
        data["excluded"],
        json!([
            ".ign/",
            ".ignexclude",
            "deploy/",
            "docs/",
            "ignition/.git/",
            "ignition/script-python/cap/__pycache__/",
            "ignition/script-python/cap/notes.txt",
            "ignition/script-python/scratch/",
            "images/",
            "tags/"
        ])
    );
    assert_eq!(
        data["excluded_count"],
        data["excluded"].as_array().expect("array").len()
    );
    // Only the project.json, the descriptor and the listed script ship.
    assert_eq!(data["members"]["added"], 3);
    assert_only_gets(&methods(&server).await);
    // The run directory of an earlier deploy stays where it was.
    assert!(fx.repo.join(".ign/deploy/gw/run/export/x.zip").exists());
}

#[tokio::test]
async fn projects_check_ignexclude_changes_digest() {
    let fx = fixture();
    add_noise(&fx.repo);
    let server = MockServer::start().await;
    mount_list(&server, &[]).await;
    mount_find_missing(&server).await;

    let excluding = data_of(&run(&server, &check_args(&fx, "dev")));
    // Removing the line puts the scratch package into the artifact.
    std::fs::remove_file(fx.repo.join(".ignexclude")).expect("rm");
    let including = data_of(&run(&server, &check_args(&fx, "dev")));

    assert_ne!(
        excluding["artifact_sha256"], including["artifact_sha256"],
        "the scratch package is part of the artifact once nothing excludes it"
    );
    assert_eq!(including["members"]["added"], 5);
    let listed: Vec<&str> = including["excluded"]
        .as_array()
        .expect("array")
        .iter()
        .filter_map(Value::as_str)
        .collect();
    assert!(!listed.contains(&"ignition/script-python/scratch/"));
}

#[tokio::test]
async fn projects_check_bad_ignexclude_refuses_before_any_request() {
    let fx = fixture();
    put(&fx.repo, ".ignexclude", b"docs/\n**/x\n");
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(out.status.code(), Some(2));
    let err: Value = serde_json::from_slice(&out.stderr).expect("stderr envelope");
    assert_eq!(err["error"]["code"], "deploy_tree_invalid");
    let message = err["error"]["message"].as_str().expect("message");
    assert!(message.contains(".ignexclude:2:1"), "{message}");
    assert!(methods(&server).await.is_empty());
}

#[tokio::test]
async fn projects_check_human_prints_the_excluded_count() {
    let fx = fixture();
    add_noise(&fx.repo);
    let server = MockServer::start().await;
    mount_list(&server, &[]).await;
    mount_find_missing(&server).await;
    let mut args = check_args(&fx, "dev");
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(
        stdout.contains("excluded: 10 path(s) left out of the artifact"),
        "{stdout}"
    );
    assert!(
        stdout.contains("  ignition/script-python/scratch/"),
        "{stdout}"
    );
}

/// A repo file name holding an ESC byte must not reach the terminal raw: the
/// human output escapes it, and the JSON output carries it as a JSON escape.
#[cfg(unix)]
#[tokio::test]
async fn projects_check_human_escapes_control_characters_in_excluded_names() {
    let fx = fixture();
    put(&fx.repo, "tags\u{1b}[2J/t.json", b"{}");
    let server = MockServer::start().await;
    mount_list(&server, &[]).await;
    mount_find_missing(&server).await;

    let mut human = check_args(&fx, "dev");
    human.remove(0);
    let out = run(&server, &human);
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(stdout.contains("  tags\\u{1b}[2J/"), "{stdout:?}");
    assert!(!stdout.contains('\u{1b}'), "no raw ESC in {stdout:?}");

    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    let listed: Vec<&str> = data["excluded"]
        .as_array()
        .expect("array")
        .iter()
        .filter_map(Value::as_str)
        .collect();
    assert!(listed.contains(&"tags\u{1b}[2J/"), "{listed:?}");
}

/// The human error line names the refused path; an ESC byte in that name is
/// written out, not sent to the terminal.
#[cfg(unix)]
#[tokio::test]
async fn projects_check_human_error_escapes_control_characters_in_a_path() {
    let fx = fixture();
    let outside = tempfile::tempdir().expect("outside");
    std::fs::write(outside.path().join("secret.txt"), b"secret").expect("write");
    std::os::unix::fs::symlink(
        outside.path().join("secret.txt"),
        fx.repo.join("ignition/script-python/cap/l\u{1b}[2J.py"),
    )
    .expect("symlink");
    let server = MockServer::start().await;
    let mut args = check_args(&fx, "dev");
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(2));
    let stderr = String::from_utf8(out.stderr).expect("utf-8");
    assert!(stderr.contains("l\\u{1b}[2J.py"), "{stderr:?}");
    assert!(!stderr.contains('\u{1b}'), "no raw ESC in {stderr:?}");
    assert!(methods(&server).await.is_empty());
}

fn error_of(out: &std::process::Output) -> Value {
    assert!(out.stdout.is_empty(), "a refusal leaves stdout empty");
    serde_json::from_slice(&out.stderr).expect("stderr envelope")
}

/// DPRJ-04, D-11: a project the git module still manages is refused before
/// the gateway is contacted. Any `.git` entry counts, whatever its kind.
#[tokio::test]
async fn projects_check_git_dir_refuses() {
    let fx = fixture();
    std::fs::create_dir_all(fx.data.join("projects/CapApp/.git")).expect("git dir");
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "project_git_managed");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["CapApp", "projects/CapApp/.git", "directory"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert!(
        methods(&server).await.is_empty(),
        "the refusal comes before any gateway request"
    );
}

#[tokio::test]
async fn projects_check_git_file_and_symlink_refuse_with_their_kind() {
    for (kind, make) in [("file", false), ("symlink", true)] {
        let fx = fixture();
        let project = fx.data.join("projects/CapApp");
        std::fs::create_dir_all(&project).expect("project dir");
        if make {
            #[cfg(unix)]
            std::os::unix::fs::symlink("/nonexistent", project.join(".git")).expect("symlink");
            #[cfg(not(unix))]
            continue;
        } else {
            std::fs::write(project.join(".git"), b"gitdir: ../x").expect("file");
        }
        let server = MockServer::start().await;
        let out = run(&server, &check_args(&fx, "dev"));
        assert_eq!(out.status.code(), Some(6), "{kind}");
        let err = error_of(&out);
        assert_eq!(err["error"]["code"], "project_git_managed", "{kind}");
        assert!(
            err["error"]["message"]
                .as_str()
                .expect("message")
                .contains(&format!("({kind})")),
            "{err}"
        );
        assert!(methods(&server).await.is_empty(), "{kind}");
    }
}

/// An existing project directory without `.git` proceeds to the gateway read.
#[tokio::test]
async fn projects_check_without_git_proceeds() {
    let fx = fixture();
    std::fs::create_dir_all(fx.data.join("projects/CapApp")).expect("project dir");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;
    let data = data_of(&run(&server, &check_args(&fx, "dev")));
    assert_eq!(data["action"], "record", "equal content, no record yet");
    assert_only_gets(&methods(&server).await);
}

/// A `data/projects` that does not exist is an unreadable host, not "no git".
#[tokio::test]
async fn projects_check_missing_projects_dir_is_transport_failed() {
    let fx = fixture();
    std::fs::remove_dir(fx.data.join("projects")).expect("rmdir");
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(out.status.code(), Some(4));
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "transport_failed");
    assert!(
        err["error"]["message"]
            .as_str()
            .expect("message")
            .contains("nodes.master"),
        "{err}"
    );
    assert!(methods(&server).await.is_empty());
}

/// Research F3: a master node that declares neither `ssh` nor `local` cannot
/// be probed, so the verb refuses before any gateway contact.
#[tokio::test]
async fn projects_check_no_host_access_refuses() {
    let fx = fixture();
    put(
        &fx.targets,
        "targets/dev.yaml",
        b"schema_version: 1\ngateway: capgw\nmode: dev\nnodes:\n  master:\n    profile: dev\n",
    );
    let server = MockServer::start().await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "deploy_tree_invalid");
    assert!(
        err["error"]["message"]
            .as_str()
            .expect("message")
            .contains("set ssh or local; this verb needs host access"),
        "{err}"
    );
    assert!(methods(&server).await.is_empty());
}

/// The human refusal names the entry and what to do about it. The project
/// name in it has passed the `deploy/project.yaml` name check, which refuses
/// control characters, so the line carries no raw terminal escape; the error
/// path escapes them in any case (25-06).
#[tokio::test]
async fn projects_check_human_git_refusal_names_the_entry() {
    let fx = fixture();
    std::fs::create_dir_all(fx.data.join("projects/CapApp/.git")).expect("git dir");
    let server = MockServer::start().await;
    let mut args = check_args(&fx, "dev");
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(6));
    let stderr = String::from_utf8(out.stderr).expect("utf-8");
    assert!(stderr.contains("projects/CapApp/.git"), "{stderr}");
    assert!(stderr.contains("administrator"), "{stderr}");
    assert!(stderr.contains("hint:"), "{stderr}");
    assert!(methods(&server).await.is_empty());
}

/// Write the release record `ign` left for `CapApp` on the fixture's master
/// node (a local node: below the data directory).
fn put_record(fx: &Fixture, release: &str) {
    put_record_sha(fx, release, &"a".repeat(64));
}

/// [`put_record`] naming the artifact digest the last deploy left.
fn put_record_sha(fx: &Fixture, release: &str, artifact_sha256: &str) {
    use ignition_core::deploy::projects::ReleaseRecord;
    let record = ReleaseRecord {
        schema_version: 1,
        gateway: "capgw".to_string(),
        project: "CapApp".to_string(),
        release: release.to_string(),
        artifact_sha256: artifact_sha256.to_string(),
        run_id: "20261020T101500Z-ab12".to_string(),
        deployed_at: "2026-10-20T10:15:00Z".to_string(),
    };
    put(
        &fx.data,
        "ign-deploy/capgw/projects/CapApp/release.json",
        &record.to_bytes(),
    );
}

/// `check_args` with another `--release` and extra flags.
fn args_with(fx: &Fixture, release: &str, extra: &[&str]) -> Vec<String> {
    let mut args = check_args(fx, "dev");
    let at = args.iter().position(|a| a == "--release").expect("flag") + 1;
    args[at] = release.to_string();
    args.extend(extra.iter().map(|s| (*s).to_string()));
    args
}

/// D-03, V3: a release older than the one the gateway last received refuses
/// in the check, before any gateway request.
#[tokio::test]
async fn projects_check_downgrade_refuses() {
    let fx = fixture();
    put_record(&fx, "v1.2.0");
    let server = MockServer::start().await;

    let out = run(&server, &args_with(&fx, "v1.1.0", &[]));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "destructive_change_refused");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["downgrade", "CapApp", "--allow-downgrade"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert!(
        methods(&server).await.is_empty(),
        "the refusal comes before any gateway request"
    );
}

#[tokio::test]
async fn projects_check_downgrade_allowed() {
    let fx = fixture();
    put_record(&fx, "v1.2.0");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let data = data_of(&run(
        &server,
        &args_with(&fx, "v1.1.0", &["--allow-downgrade"]),
    ));
    assert_eq!(data["allow_downgrade"], true);
    assert_eq!(data["previous_release"], "v1.2.0");
    assert_eq!(data["release"], "v1.1.0");
    assert_only_gets(&methods(&server).await);
}

#[tokio::test]
async fn projects_check_equal_release_allowed() {
    let fx = fixture();
    put_record(&fx, "v1.2.0");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let data = data_of(&run(&server, &args_with(&fx, "v1.2.0", &[])));
    assert_eq!(data["allow_downgrade"], false);
    assert_eq!(data["previous_release"], "v1.2.0");
}

#[tokio::test]
async fn projects_check_newer_release_reports_the_previous_one() {
    let fx = fixture();
    put_record(&fx, "v1.2.0-rc.1");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let data = data_of(&run(&server, &args_with(&fx, "v1.2.0", &[])));
    assert_eq!(data["previous_release"], "v1.2.0-rc.1");
}

/// V4: the tag is validated before any host or gateway contact.
#[tokio::test]
async fn projects_check_bad_release_refuses() {
    for bad in ["banana", "1.0", "vv1.0.0", ""] {
        let fx = fixture();
        // A host that would refuse if it were reached.
        std::fs::remove_dir(fx.data.join("projects")).expect("rmdir");
        let server = MockServer::start().await;
        let out = run(&server, &args_with(&fx, bad, &[]));
        assert_eq!(out.status.code(), Some(2), "{bad:?}");
        let err = error_of(&out);
        assert_eq!(err["error"]["code"], "invalid_input", "{bad:?}");
        assert!(
            err["error"]["message"]
                .as_str()
                .expect("message")
                .contains("--release"),
            "{err}"
        );
        assert!(methods(&server).await.is_empty(), "{bad:?}");
    }
}

/// A record that cannot be trusted refuses; it is never read as absent.
#[tokio::test]
async fn projects_check_corrupt_record_refuses() {
    let fx = fixture();
    put(
        &fx.data,
        "ign-deploy/capgw/projects/CapApp/release.json",
        b"{\"schema_version\":1}",
    );
    let server = MockServer::start().await;
    let out = run(&server, &args_with(&fx, "v1.1.0", &["--allow-downgrade"]));
    assert_eq!(out.status.code(), Some(6));
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "deploy_run_invalid");
    assert!(
        err["error"]["message"]
            .as_str()
            .expect("message")
            .contains("ign-deploy/capgw/projects/CapApp/release.json"),
        "{err}"
    );
    assert!(methods(&server).await.is_empty());
}

#[tokio::test]
async fn projects_check_overlong_first_change_reason_refuses() {
    let fx = fixture();
    let server = MockServer::start().await;
    let long = "x".repeat(501);
    for reason in [long.as_str(), ""] {
        let out = run(
            &server,
            &args_with(&fx, "v1.0.0", &["--allow-first-change", reason]),
        );
        assert_eq!(out.status.code(), Some(2), "{} chars", reason.len());
        assert_eq!(error_of(&out)["error"]["code"], "invalid_input");
    }
    assert!(methods(&server).await.is_empty());
}

/// The human check says what the apply would do for the record-only case, and
/// prints the drift warning.
#[tokio::test]
async fn projects_check_human_record_and_drift_lines() {
    let fx = fixture();
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;
    let mut args = check_args(&fx, "dev");
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(
        stdout.contains("check: record the release only (no project change)"),
        "{stdout}"
    );
    assert!(
        stdout.contains("release: v1.0.0 (last deployed by this tool: none)"),
        "{stdout}"
    );

    put_record(&fx, "v0.9.0");
    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(0));
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(
        stdout.contains("release: v1.0.0 (last deployed by this tool: v0.9.0)"),
        "{stdout}"
    );
    assert!(
        stdout.contains(
            "warning: project CapApp: the live project no longer matches the last release this tool deployed (v0.9.0)"
        ),
        "{stdout}"
    );
}

/// The repo's `project.json` with a `parent`.
fn set_repo_parent(fx: &Fixture, parent: &str) {
    put(
        &fx.repo,
        "project.json",
        format!(r#"{{"title":"Cap App","enabled":true,"parent":"{parent}"}}"#).as_bytes(),
    );
}

/// `projects/list` with full records (parent, inheritable, invalidParent).
async fn mount_list_records(server: &MockServer, items: Vec<Value>) {
    let total = items.len();
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": items,
            "metadata": {"total": total, "matching": total, "limit": -1, "offset": 0}
        })))
        .mount(server)
        .await;
}

/// K6 a, D-05: a parent the gateway does not list refuses
/// `project_parent_invalid` with reason `missing`, before any export and with
/// nothing but GET requests sent.
#[tokio::test]
async fn projects_check_parent_missing_refuses() {
    let fx = fixture();
    set_repo_parent(&fx, "WHK-Global");
    let server = MockServer::start().await;
    mount_list(&server, &["CapApp"]).await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let out = run(&server, &check_args(&fx, "dev"));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "project_parent_invalid");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["CapApp", "WHK-Global", "missing"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    let requests = methods(&server).await;
    assert!(
        requests.iter().all(|(_, url)| !url.contains("/export/")),
        "no project export before the refusal: {requests:?}"
    );
    assert_only_gets(&requests);
}

/// A present, inheritable parent passes and is reported.
#[tokio::test]
async fn projects_check_parent_present_passes() {
    let fx = fixture();
    set_repo_parent(&fx, "WHK-Global");
    let server = MockServer::start().await;
    mount_list_records(
        &server,
        vec![
            json!({"name": "WHK-Global", "enabled": true, "inheritable": true, "invalidParent": false}),
            json!({"name": "CapApp", "enabled": true}),
        ],
    )
    .await;
    mount_find_found(&server).await;
    mount_export(&server, export_zip(CODE_V1, true)).await;

    let out = run(
        &server,
        &args_with(&fx, "v1.0.0", &["--allow-first-change", "adopt the repo"]),
    );
    let data = data_of(&out);
    assert_eq!(data["parent"], "WHK-Global");
    assert_eq!(data["action"], "import");
    assert_only_gets(&methods(&server).await);
}

// ---------------------------------------------------------------------------
// The guarded apply (25-11): DPRJ-01, DPRJ-03.
// ---------------------------------------------------------------------------

/// The canonical digest of the artifact the fixture repo builds: what
/// `--check --json` reports as `artifact_sha256`.
fn artifact_hash(fx: &Fixture) -> String {
    ignition_core::deploy::project_artifact::build_artifact(&fx.repo)
        .expect("the fixture builds")
        .digest
        .sha256
}

/// Make the fixture repo a git work tree that ignores `.ign/`, as the run
/// directory's guard requires.
fn git_ignore_runs(fx: &Fixture) {
    let status = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(&fx.repo)
        .status()
        .expect("git runs");
    assert!(status.success());
    put(&fx.repo, ".gitignore", b".ign/\n");
}

/// `check_args` as a deploy: no `--check`, the reviewed hash, `--yes`.
fn apply_args(fx: &Fixture, release: &str, hash: Option<&str>, yes: bool) -> Vec<String> {
    let mut args = args_with(fx, release, &[]);
    args.retain(|a| a != "--check");
    if let Some(hash) = hash {
        args.push("--artifact-sha256".into());
        args.push(hash.into());
    }
    if yes {
        args.push("--yes".into());
    }
    args
}

/// The export answers `before` until the import was received and `after`
/// from then on: a gateway that holds the old project until it is replaced.
struct ExportAfterImport {
    imported: Arc<AtomicBool>,
    before: Vec<u8>,
    after: Vec<u8>,
}

impl Respond for ExportAfterImport {
    fn respond(&self, _request: &Request) -> ResponseTemplate {
        let zip = if self.imported.load(Ordering::SeqCst) {
            self.after.clone()
        } else {
            self.before.clone()
        };
        ResponseTemplate::new(200)
            .set_body_raw(zip, "application/zip")
            .insert_header(
                "Content-Disposition",
                "attachment; filename=\"CapApp-export.zip\"",
            )
    }
}

/// The import answer of the real gateway (C8c); receiving it flips the
/// export.
struct ImportAnswer {
    imported: Arc<AtomicBool>,
}

impl Respond for ImportAnswer {
    fn respond(&self, _request: &Request) -> ResponseTemplate {
        self.imported.store(true, Ordering::SeqCst);
        ResponseTemplate::new(200)
            .set_body_json(json!({"success": true, "changes": [{"name": "CapApp"}]}))
    }
}

/// The designers list body for `(user, project, address)` sessions.
fn designers_body(sessions: &[(&str, &str, &str)]) -> Value {
    let items: Vec<Value> = sessions
        .iter()
        .enumerate()
        .map(|(i, (user, project, address))| {
            json!({
                "id": format!("d-{i}"),
                "user": user,
                "project": project,
                "address": address,
                "uptime": 1,
                "lastcomm": 1,
                "timeout": 1,
                "memory": {},
            })
        })
        .collect();
    json!({
        "items": items,
        "metadata": {"total": items.len(), "matching": items.len(), "limit": -1, "offset": 0}
    })
}

/// `gateway-info` answering `name` at `priority` (a lower number wins).
async fn mount_gateway_name(server: &MockServer, name: &str, priority: u8) {
    Mock::given(method("GET"))
        .and(path("/data/api/v1/gateway-info"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "name": name,
            "deploymentMode": "dev",
            "ignitionVersion": "8.3.6 (b2026042713)"
        })))
        .with_priority(priority)
        .mount(server)
        .await;
}

/// The Designer list answering `sessions`. Mounted at the default priority,
/// so it wins over the empty list [`mount_deployable`] leaves behind.
async fn mount_designers(server: &MockServer, sessions: &[(&str, &str, &str)]) {
    Mock::given(method("GET"))
        .and(path("/data/api/v1/designers"))
        .respond_with(ResponseTemplate::new(200).set_body_json(designers_body(sessions)))
        .mount(server)
        .await;
}

/// A gateway that holds `before` (or no project) until `import?overwrite=` is
/// posted, then holds `after`. `list` names the project when it exists.
async fn mount_deployable(server: &MockServer, before: Option<Vec<u8>>, after: Vec<u8>) {
    let imported = Arc::new(AtomicBool::new(false));
    let overwrite = before.is_some();
    // The gateway is the one the fixture names, unless a test mounts another
    // name ahead of this one.
    mount_gateway_name(server, "capgw", 10).await;
    // No Designer session is open unless a test mounts one.
    Mock::given(method("GET"))
        .and(path("/data/api/v1/designers"))
        .respond_with(ResponseTemplate::new(200).set_body_json(designers_body(&[])))
        .with_priority(10)
        .mount(server)
        .await;
    match &before {
        Some(_) => {
            mount_list(server, &["CapApp"]).await;
            mount_find_found(server).await;
        }
        None => {
            mount_list(server, &[]).await;
            mount_find_missing(server).await;
        }
    }
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/export/CapApp"))
        .respond_with(ExportAfterImport {
            imported: imported.clone(),
            before: before.unwrap_or_else(|| after.clone()),
            after,
        })
        .mount(server)
        .await;
    Mock::given(method("POST"))
        .and(path("/data/api/v1/projects/import/CapApp"))
        .and(query_param(
            "overwrite",
            if overwrite { "true" } else { "false" },
        ))
        .respond_with(ImportAnswer { imported })
        .mount(server)
        .await;
}

fn run_dirs(fx: &Fixture) -> Vec<PathBuf> {
    let root = fx.repo.join(".ign/deploy/capgw");
    match std::fs::read_dir(&root) {
        Ok(entries) => entries.map(|e| e.expect("entry").path()).collect(),
        Err(_) => Vec::new(),
    }
}

fn position(requests: &[(String, String)], verb: &str, needle: &str) -> Vec<usize> {
    requests
        .iter()
        .enumerate()
        .filter(|(_, (v, p))| v == verb && p.contains(needle))
        .map(|(i, _)| i)
        .collect()
}

/// DPRJ-03, K15, V5: the live project is saved before the import, the import
/// is verified by canonical hash and the release is recorded.
#[tokio::test]
async fn projects_apply_imports_and_records() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    let old = export_zip(CODE_V2, true);
    mount_deployable(&server, Some(old.clone()), export_zip(CODE_V1, true)).await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    let data = data_of(&out);
    assert_eq!(data["outcome"], "imported");
    assert_eq!(data["ok"], true);
    assert_eq!(data["check"], false);
    assert_eq!(data["record_written"], true);
    assert_eq!(data["artifact_sha256"], hash.as_str());
    let run_id = data["run_id"].as_str().expect("run id").to_string();
    assert_eq!(data["run_dir"], format!(".ign/deploy/capgw/{run_id}"));

    // The run directory holds the audit files and the pre-image.
    let dir = fx.repo.join(".ign/deploy/capgw").join(&run_id);
    for file in ["run.json", "plan.json", "events.ndjson", "result.json"] {
        assert!(dir.join(file).is_file(), "{file}");
    }
    let saved = dir.join("export/CapApp.zip");
    assert_eq!(std::fs::read(&saved).expect("pre-image"), old);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = |p: &Path| std::fs::metadata(p).expect("metadata").permissions().mode() & 0o777;
        assert_eq!(mode(&saved), 0o600);
        assert_eq!(mode(&dir.join("export")), 0o700);
        assert_eq!(mode(&dir), 0o700);
    }
    let run_json: Value =
        serde_json::from_slice(&std::fs::read(dir.join("run.json")).expect("run.json"))
            .expect("run.json is json");
    assert_eq!(run_json["release"], "v1.1.0");
    assert_eq!(run_json["allow_downgrade"], false);
    assert_eq!(run_json["artifact_sha256"], hash.as_str());

    // The record names this release, this artifact and this run.
    use ignition_core::deploy::projects::ReleaseRecord;
    let bytes = std::fs::read(
        fx.data
            .join("ign-deploy/capgw/projects/CapApp/release.json"),
    )
    .expect("record");
    let record = ReleaseRecord::parse(&bytes, "release.json", "capgw", "CapApp").expect("parses");
    assert_eq!(record.release, "v1.1.0");
    assert_eq!(record.artifact_sha256, hash);
    assert_eq!(record.run_id, run_id);

    // Export before import, import once, the read-back after it.
    let requests = methods(&server).await;
    let exports = position(&requests, "GET", "/export/");
    let imports = position(&requests, "POST", "/import/");
    assert_eq!(imports.len(), 1, "{requests:?}");
    assert!(
        exports.iter().filter(|i| **i < imports[0]).count() >= 2,
        "plan and pre-image exports precede the import: {requests:?}"
    );
    assert!(
        exports.iter().any(|i| *i > imports[0]),
        "the project is read back: {requests:?}"
    );
    assert_eq!(requests.iter().filter(|(v, _)| v == "POST").count(), 1);
}

/// D-13, K10: an absent project is created with `overwrite=false`, no
/// pre-image, through the same guard and hash gate.
#[tokio::test]
async fn projects_apply_creates_absent() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(&server, None, export_zip(CODE_V1, true)).await;

    let out = run(&server, &apply_args(&fx, "v1.0.0", Some(&hash), true));
    let data = data_of(&out);
    assert_eq!(data["outcome"], "created");
    assert_eq!(data["ok"], true);
    assert_eq!(data["record_written"], true);
    let dirs = run_dirs(&fx);
    assert_eq!(dirs.len(), 1);
    assert!(
        !dirs[0].join("export").exists(),
        "an absent project has no pre-image"
    );
    assert!(
        fx.data
            .join("ign-deploy/capgw/projects/CapApp/release.json")
            .is_file()
    );
    let requests = methods(&server).await;
    let imports = position(&requests, "POST", "/import/");
    assert_eq!(imports.len(), 1, "{requests:?}");
    assert!(
        position(&requests, "GET", "/export/")
            .iter()
            .all(|i| *i > imports[0]),
        "no export before the create: {requests:?}"
    );
}

/// SC-1, D-01: a hash that is not the artifact's is refused with nothing
/// contacted, not the gateway and not the host.
#[tokio::test]
async fn projects_apply_hash_mismatch_uploads_nothing() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;

    let zeros = "0".repeat(64);
    let out = run(&server, &apply_args(&fx, "v1.0.0", Some(&zeros), true));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "project_hash_mismatch");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["CapApp", zeros.as_str(), artifact_hash(&fx).as_str()] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert!(
        methods(&server).await.is_empty(),
        "nothing is requested before the hash passes"
    );
    assert!(run_dirs(&fx).is_empty());
    assert!(!fx.repo.join(".ign").exists());
}

/// Decision C: an unattended apply names the artifact it reviewed.
#[tokio::test]
async fn projects_apply_needs_hash_noninteractive() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let server = MockServer::start().await;

    let out = run(&server, &apply_args(&fx, "v1.0.0", None, true));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "invalid_input");
    let message = err["error"]["message"].as_str().expect("message");
    assert!(message.contains("--artifact-sha256"), "{message}");
    assert!(
        !err["error"]["hint"]
            .as_str()
            .unwrap_or_default()
            .contains("--file"),
        "a flag refusal does not point at --file"
    );
    assert!(methods(&server).await.is_empty());
    assert!(!fx.repo.join(".ign").exists());
}

/// The hash is 64 lowercase hex characters, or the input is refused before
/// anything is contacted.
#[tokio::test]
async fn projects_apply_bad_hash_format() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let server = MockServer::start().await;
    let upper = artifact_hash(&fx).to_uppercase();

    for bad in [upper.as_str(), "abc", &"g".repeat(64)] {
        let out = run(&server, &apply_args(&fx, "v1.0.0", Some(bad), true));
        assert_eq!(
            out.status.code(),
            Some(2),
            "{bad}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(error_of(&out)["error"]["code"], "invalid_input", "{bad}");
    }
    assert!(methods(&server).await.is_empty());
}

/// The guard: without `--yes` the plan is the refusal, and nothing but reads
/// reached the gateway.
#[tokio::test]
async fn projects_apply_needs_yes() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), false));
    assert_eq!(
        out.status.code(),
        Some(2),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "confirmation_required");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["CapApp", "import", hash.as_str(), "capgw", "v1.1.0"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert_only_gets(&methods(&server).await);
    assert!(run_dirs(&fx).is_empty());
    assert!(!fx.repo.join(".ign").exists());
}

/// K14: this release is already recorded and the project is the artifact:
/// nothing is written, not even a run directory.
#[tokio::test]
async fn projects_apply_skip_writes_nothing() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let hash = artifact_hash(&fx);
    put_record_sha(&fx, "v1.1.0", &hash);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V1, true)),
        export_zip(CODE_V1, true),
    )
    .await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    let data = data_of(&out);
    assert_eq!(data["outcome"], "skipped");
    assert_eq!(data["ok"], true);
    assert!(data["run_id"].is_null());
    assert_eq!(data["record_written"], false);
    assert!(!fx.repo.join(".ign").exists());
    assert_only_gets(&methods(&server).await);
}

/// K14, D-12: the project already is the artifact and no record names this
/// release: only the record is written.
#[tokio::test]
async fn projects_apply_record_only() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V1, true)),
        export_zip(CODE_V1, true),
    )
    .await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    let data = data_of(&out);
    assert_eq!(data["outcome"], "recorded");
    assert_eq!(data["ok"], true);
    assert_eq!(data["record_written"], true);
    assert!(data["run_id"].is_string());
    assert!(
        fx.data
            .join("ign-deploy/capgw/projects/CapApp/release.json")
            .is_file()
    );
    assert_only_gets(&methods(&server).await);
    let dirs = run_dirs(&fx);
    assert_eq!(dirs.len(), 1);
    assert!(
        !dirs[0].join("export").exists(),
        "the project is not replaced, so nothing is saved"
    );
}

// ---------------------------------------------------------------------------
// The unverified verdict (25-12): DPRJ-03, V6, K11.
// ---------------------------------------------------------------------------

/// A gateway that replaces `CapApp` with something other than the artifact
/// (the read-back after the import differs), so the verify cannot pass.
async fn mount_unverifiable(server: &MockServer) {
    mount_deployable(
        server,
        Some(export_zip(CODE_V2, true)),
        export_zip(b"def f():\n    return 3\n", true),
    )
    .await;
}

fn record_path(fx: &Fixture) -> PathBuf {
    fx.data
        .join("ign-deploy/capgw/projects/CapApp/release.json")
}

/// V6, K11, T-25-64, T-25-66: a read-back that differs from the artifact is a
/// success envelope that says so, then exit 6. The live project stays as
/// imported, nothing is restored, no second import is sent and the release
/// record is not replaced.
#[tokio::test]
async fn projects_apply_unverified_exit_6() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let record_before = std::fs::read(record_path(&fx)).expect("record");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_unverifiable(&server).await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        out.stderr.is_empty(),
        "under --json stderr is empty: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope: Value = serde_json::from_slice(&out.stdout).expect("one envelope");
    assert_eq!(
        envelope["ok"], true,
        "a success envelope, then the exit code"
    );
    let data = &envelope["data"];
    assert_eq!(data["outcome"], "imported_unverified");
    assert_eq!(data["ok"], false);
    assert_eq!(data["slug"], "deploy_project_unverified");
    assert_eq!(data["record_written"], false);
    assert_eq!(data["artifact_sha256"], hash.as_str());
    let run_id = data["run_id"].as_str().expect("run id");
    let run_dir = format!(".ign/deploy/capgw/{run_id}");
    assert_eq!(data["run_dir"], run_dir.as_str());
    assert_eq!(
        data["restore_command"],
        format!(
            "ign project import CapApp --file {run_dir}/export/CapApp.zip --collision-policy overwrite --yes"
        )
        .as_str()
    );

    // The file the command names is the saved pre-image.
    let saved = fx.repo.join(&run_dir).join("export/CapApp.zip");
    assert_eq!(
        std::fs::read(&saved).expect("pre-image"),
        export_zip(CODE_V2, true)
    );

    // result.json holds the same verdict.
    let result: Value = serde_json::from_slice(
        &std::fs::read(fx.repo.join(&run_dir).join("result.json")).expect("result.json"),
    )
    .expect("json");
    assert_eq!(result["outcome"], "imported_unverified");
    assert_eq!(result["ok"], false);
    assert_eq!(result["slug"], "deploy_project_unverified");
    assert_eq!(result["restore_command"], data["restore_command"]);

    // One import, no restore, and the earlier record is untouched.
    let requests = methods(&server).await;
    assert_eq!(
        position(&requests, "POST", "/import/").len(),
        1,
        "no second, unreviewed import: {requests:?}"
    );
    assert_eq!(requests.iter().filter(|(v, _)| v == "POST").count(), 1);
    assert_eq!(
        std::fs::read(record_path(&fx)).expect("record"),
        record_before,
        "no release record is written for an unverified import"
    );
}

/// A project that was created has no pre-image: the verdict still stands and
/// there is no restore command to print.
#[tokio::test]
async fn projects_apply_unverified_create_has_no_restore_command() {
    let fx = fixture();
    git_ignore_runs(&fx);
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(&server, None, export_zip(b"def f():\n    return 3\n", true)).await;

    let out = run(&server, &apply_args(&fx, "v1.0.0", Some(&hash), true));
    assert_eq!(out.status.code(), Some(6));
    let envelope: Value = serde_json::from_slice(&out.stdout).expect("envelope");
    let data = &envelope["data"];
    assert_eq!(data["outcome"], "imported_unverified");
    assert_eq!(data["ok"], false);
    assert_eq!(data["slug"], "deploy_project_unverified");
    assert!(data["restore_command"].is_null(), "{data}");
    assert!(
        !record_path(&fx).exists(),
        "no record for an unverified create"
    );
}

/// Human mode: the outcome, the hashes, the run directory and the restore
/// command on stdout; one `ign deploy projects:` line per step on stderr.
#[tokio::test]
async fn projects_apply_human_output() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_unverifiable(&server).await;
    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(out.status.code(), Some(6));
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    let stderr = String::from_utf8(out.stderr).expect("utf-8");

    assert!(
        stdout.contains("project CapApp on capgw (env dev, release v1.1.0)"),
        "{stdout}"
    );
    assert!(
        stdout.contains("outcome: imported_unverified (NOT verified)"),
        "{stdout}"
    );
    assert!(
        stdout.contains("verdict: deploy_project_unverified"),
        "{stdout}"
    );
    assert!(
        stdout.contains(&format!("artifact sha256 {hash}")),
        "{stdout}"
    );
    assert!(stdout.contains("live sha256     "), "{stdout}");
    assert!(
        stdout.contains("run directory .ign/deploy/capgw/"),
        "{stdout}"
    );
    assert!(
        stdout.contains("ign project import CapApp --file .ign/deploy/capgw/"),
        "{stdout}"
    );
    assert!(
        stdout.contains("/export/CapApp.zip --collision-policy overwrite --yes"),
        "{stdout}"
    );
    assert!(stdout.contains("release record: not written"), "{stdout}");

    // Progress: pre-image, import and verify, each on a prefixed line.
    let lines: Vec<&str> = stderr.lines().collect();
    for needle in ["pre-image saved", "import sent", "verify NOT green"] {
        assert!(
            lines
                .iter()
                .any(|l| l.starts_with("ign deploy projects: ") && l.contains(needle)),
            "{needle}: {stderr}"
        );
    }
    // Names and hashes only: the progress never prints file content.
    assert!(!stderr.contains("return 3"), "{stderr}");
    assert!(!stderr.contains("return 2"), "{stderr}");
}

/// A deploy that verifies is human-quiet about verdicts: no slug, no restore
/// line, exit 0.
#[tokio::test]
async fn projects_apply_verified_human_has_no_verdict_lines() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;
    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    args.remove(0);

    let out = run(&server, &args);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(stdout.contains("outcome: imported\n"), "{stdout}");
    assert!(!stdout.contains("verdict:"), "{stdout}");
    assert!(!stdout.contains("restore"), "{stdout}");
    let stderr = String::from_utf8(out.stderr).expect("utf-8");
    assert!(
        stderr.contains("ign deploy projects: verify green"),
        "{stderr}"
    );
}

// ---------------------------------------------------------------------------
// The Designer pre-check (25-14): DPRJ-03, K12, T-25-45.
// ---------------------------------------------------------------------------

/// K12 a: an open Designer session refuses a confirmed import before anything
/// is written: no run directory, no pre-image, no POST.
#[tokio::test]
async fn projects_apply_designer_open_refuses() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;
    mount_designers(&server, &[("alice", "CapApp", "10.0.0.5:52526")]).await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "deploy_preflight_failed");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["designers", "alice on CapApp from 10.0.0.5:52526"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert!(run_dirs(&fx).is_empty(), "nothing is written");
    assert!(!fx.repo.join(".ign").exists());
    let requests = methods(&server).await;
    assert!(
        position(&requests, "POST", "/import/").is_empty(),
        "nothing is imported: {requests:?}"
    );
    assert_eq!(requests.iter().filter(|(v, _)| v == "POST").count(), 0);
    let record = std::fs::read_to_string(record_path(&fx)).expect("record");
    assert!(
        record.contains("v1.0.0"),
        "the record is untouched: {record}"
    );
}

/// D-15: `--designers proceed` goes ahead, and the sessions are on record in
/// `run.json` (names only) and in the events.
#[tokio::test]
async fn projects_apply_designers_proceed_records() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;
    mount_designers(&server, &[("alice", "CapApp", "10.0.0.5:52526")]).await;

    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    args.extend(["--designers".to_string(), "proceed".to_string()]);
    let out = run(&server, &args);
    let data = data_of(&out);
    assert_eq!(data["outcome"], "imported");
    let run_id = data["run_id"].as_str().expect("run id");
    let dir = fx.repo.join(".ign/deploy/capgw").join(run_id);
    let run_json: Value =
        serde_json::from_slice(&std::fs::read(dir.join("run.json")).expect("run.json"))
            .expect("run.json is json");
    assert_eq!(run_json["designers"], "proceed");
    assert_eq!(
        run_json["designers_seen"],
        json!([{"user": "alice", "project": "CapApp", "host": "10.0.0.5:52526"}])
    );
    let events = std::fs::read_to_string(dir.join("events.ndjson")).expect("events");
    let proceeded: Vec<Value> = events
        .lines()
        .map(|l| serde_json::from_str::<Value>(l).expect("line"))
        .filter(|l| l["event"] == "designers_proceed")
        .collect();
    assert_eq!(proceeded.len(), 1, "{events}");
    assert_eq!(
        proceeded[0]["sessions"],
        json!([{"user": "alice", "project": "CapApp", "host": "10.0.0.5:52526"}])
    );
}

// ---------------------------------------------------------------------------
// The wrong-target pre-check (25-14): DPRJ-03, T-25-44.
// ---------------------------------------------------------------------------

/// T-25-44: the gateway the profile points at is not the host the target
/// names (the REST name is not the host's `systemName`): refused before
/// anything is written, whatever the project holds.
#[tokio::test]
async fn projects_apply_wrong_target_refuses() {
    let fx = fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;
    mount_gateway_name(&server, "somewhere-else", 1).await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(&out);
    assert_eq!(err["error"]["code"], "deploy_preflight_failed");
    let message = err["error"]["message"].as_str().expect("message");
    for needle in ["wrong_target", "host's systemName"] {
        assert!(message.contains(needle), "{needle}: {message}");
    }
    assert!(
        !message.contains("somewhere-else"),
        "a name the gateway reports is not echoed: {message}"
    );
    assert!(run_dirs(&fx).is_empty(), "nothing is written");
    assert!(!fx.repo.join(".ign").exists());
    let requests = methods(&server).await;
    assert!(
        position(&requests, "POST", "/import/").is_empty(),
        "nothing is imported: {requests:?}"
    );
    assert_eq!(
        position(&requests, "GET", "/designers").len(),
        0,
        "the Designer list is read after the target is proven: {requests:?}"
    );
}

// ---------------------------------------------------------------------------
// The children report (25-15): D-06, K7, T-25-47.
// ---------------------------------------------------------------------------

/// `projects/list` for a parent deploy: `CapApp` itself, the `(name, parent)`
/// projects given, mounted ahead of the plain list [`mount_deployable`]
/// leaves behind.
async fn mount_family(server: &MockServer, family: &[(&str, &str)]) {
    let mut items = vec![json!({"name": "CapApp", "enabled": true})];
    items.extend(
        family
            .iter()
            .map(|(name, parent)| json!({"name": name, "enabled": true, "parent": parent})),
    );
    let total = items.len();
    Mock::given(method("GET"))
        .and(path("/data/api/v1/projects/list"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": items,
            "metadata": {"total": total, "matching": total, "limit": -1, "offset": 0}
        })))
        .with_priority(1)
        .mount(server)
        .await;
}

/// The export of a child project.
async fn mount_child_export(server: &MockServer, name: &str, zip: Vec<u8>) {
    Mock::given(method("GET"))
        .and(path(format!("/data/api/v1/projects/export/{name}")))
        .respond_with(ResponseTemplate::new(200).set_body_raw(zip, "application/zip"))
        .mount(server)
        .await;
}

/// The release record `ign` left for a child project on the fixture's host.
fn put_child_record(fx: &Fixture, child: &str, release: &str, artifact_sha256: &str) {
    use ignition_core::deploy::projects::ReleaseRecord;
    let record = ReleaseRecord {
        schema_version: 1,
        gateway: "capgw".to_string(),
        project: child.to_string(),
        release: release.to_string(),
        artifact_sha256: artifact_sha256.to_string(),
        run_id: "20261020T101500Z-cd34".to_string(),
        deployed_at: "2026-10-20T10:15:00Z".to_string(),
    };
    put(
        &fx.data,
        &format!("ign-deploy/capgw/projects/{child}/release.json"),
        &record.to_bytes(),
    );
}

/// The canonical sha256 of an export zip.
fn export_sha(zip: &[u8]) -> String {
    ignition_core::deploy::project_artifact::canonical_digest(zip)
        .expect("a project export")
        .sha256
}

/// A parent deploy with `ChildA` (its record equals its export) and `ChildB`
/// (its record differs), a grandchild under `ChildA` and an unrelated
/// project. Returns the fixture, the server, the reviewed hash and the live
/// hash of `ChildA`.
async fn parent_deploy() -> (Fixture, MockServer, String, String) {
    let fx = fixture();
    git_ignore_runs(&fx);
    // The live parent is what the last deploy left, so the only warning a
    // run can carry is about a child.
    put_record_sha(&fx, "v1.0.0", &export_sha(&export_zip(CODE_V2, true)));
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CODE_V2, true)),
        export_zip(CODE_V1, true),
    )
    .await;
    mount_family(
        &server,
        &[
            ("ChildA", "CapApp"),
            ("ChildB", "CapApp"),
            ("GrandChild", "ChildA"),
            ("Unrelated", "Elsewhere"),
        ],
    )
    .await;
    let a = export_zip(CODE_V1, true);
    let a_sha = export_sha(&a);
    mount_child_export(&server, "ChildA", a).await;
    mount_child_export(&server, "ChildB", export_zip(CODE_V2, true)).await;
    put_child_record(&fx, "ChildA", "v0.9.0", &a_sha);
    put_child_record(&fx, "ChildB", "v0.8.0", &"b".repeat(64));
    (fx, server, hash, a_sha)
}

/// D-06, K7: after the parent is imported each direct child is compared with
/// the hash its own last deploy recorded. A drifted child is a warning, never
/// a failure; nothing is written to a child.
#[tokio::test]
async fn projects_apply_children_ok_and_mismatch() {
    let (fx, server, hash, a_sha) = parent_deploy().await;

    let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
    let data = data_of(&out);
    assert_eq!(data["outcome"], "imported");
    assert_eq!(data["ok"], true);

    let children = data["children"].as_array().expect("children is a list");
    assert_eq!(children.len(), 2, "direct children only: {children:?}");
    assert_eq!(children[0]["name"], "ChildA");
    assert_eq!(children[0]["status"], "ok");
    assert_eq!(children[0]["release"], "v0.9.0");
    assert_eq!(children[0]["recorded_sha256"], a_sha.as_str());
    assert_eq!(children[0]["live_sha256"], a_sha.as_str());
    assert_eq!(children[1]["name"], "ChildB");
    assert_eq!(children[1]["status"], "mismatch");
    assert_eq!(children[1]["release"], "v0.8.0");
    assert_eq!(children[1]["recorded_sha256"], "b".repeat(64).as_str());
    assert!(is_hex64(&children[1]["live_sha256"]), "{children:?}");
    assert_ne!(children[1]["live_sha256"], children[1]["recorded_sha256"]);

    let warnings: Vec<&str> = data["warnings"]
        .as_array()
        .expect("warnings")
        .iter()
        .filter_map(Value::as_str)
        .collect();
    assert_eq!(warnings.len(), 1, "{warnings:?}");
    assert!(warnings[0].contains("child project ChildB"), "{warnings:?}");
    assert!(warnings[0].contains("v0.8.0"), "{warnings:?}");

    // Reads only: the one write is the parent's own import.
    let requests = methods(&server).await;
    let writes: Vec<_> = requests.iter().filter(|(v, _)| v != "GET").collect();
    assert_eq!(writes.len(), 1, "{requests:?}");
    assert_eq!(writes[0].1, "/data/api/v1/projects/import/CapApp");
    for (verb, url) in &requests {
        if url.contains("Child") || url.contains("Unrelated") {
            assert_eq!(verb, "GET", "{url}");
            assert!(url.contains("/projects/export/Child"), "{url}");
        }
    }
    assert!(
        !requests.iter().any(|(_, url)| url.contains("GrandChild")),
        "a grandchild is not swept: {requests:?}"
    );
}

/// The human form lists every child with its status, and the mismatch is a
/// warning line.
#[tokio::test]
async fn projects_apply_children_human() {
    let (fx, server, hash, _) = parent_deploy().await;
    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    args.remove(0); // human mode

    let out = run(&server, &args);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).expect("utf-8");
    assert!(stdout.contains("\nchildren:\n"), "{stdout}");
    assert!(stdout.contains("\n  ChildA: ok (v0.9.0)\n"), "{stdout}");
    assert!(
        stdout.contains("\n  ChildB: MISMATCH (v0.8.0)\n"),
        "{stdout}"
    );
    assert!(stdout.contains("warning: child project ChildB"), "{stdout}");
    let stderr = String::from_utf8(out.stderr).expect("utf-8");
    assert!(
        stderr.contains("ign deploy projects: child ChildB: MISMATCH"),
        "{stderr}"
    );
}

// ============================================================================
// 25-17: the secret canary (SC-5, DSURF-03, DPRJ-03)
// ============================================================================

use ignition_core::actions::deploy_projects::PROJECTS_CANARY_EXEMPT;

/// Scripts can embed credentials. This string is placed in a project resource
/// of the checkout and in the live project the gateway exports; the only
/// file allowed to hold it afterwards is the pre-image export, named by
/// [`PROJECTS_CANARY_EXEMPT`].
const CANARY_PROJECT: &str = "CANARY-PROJECT-25";
/// The checkout's script.
const CANARY_CHECKOUT: &[u8] = b"PASSWORD = 'CANARY-PROJECT-25'\n";
/// The live project's script: the canary, and a line the checkout lacks.
const CANARY_LIVE: &[u8] = b"PASSWORD = 'CANARY-PROJECT-25'\nOLD = 1\n";
/// A read-back that is not the checkout.
const CANARY_BAD: &[u8] = b"PASSWORD = 'CANARY-PROJECT-25'\nOTHER = 3\n";

/// [`fixture`] whose script carries the canary.
fn canary_fixture() -> Fixture {
    let fx = fixture();
    put(
        &fx.repo,
        "ignition/script-python/cap/code.py",
        CANARY_CHECKOUT,
    );
    fx
}

/// Whether `rel` (below a run directory) is named by
/// [`PROJECTS_CANARY_EXEMPT`]: a bare name matches the top-level entry and
/// everything below it.
fn is_canary_exempt(rel: &Path) -> bool {
    let first = rel
        .components()
        .next()
        .map(|c| c.as_os_str().to_string_lossy().into_owned())
        .unwrap_or_default();
    PROJECTS_CANARY_EXEMPT.contains(&first.as_str())
}

/// Every file below `dir`, relative to it, sorted.
fn files_below(dir: &Path) -> Vec<PathBuf> {
    fn walk(root: &Path, dir: &Path, found: &mut Vec<PathBuf>) {
        for entry in std::fs::read_dir(dir).expect("read_dir") {
            let path = entry.expect("entry").path();
            if path.is_dir() {
                walk(root, &path, found);
            } else {
                found.push(path.strip_prefix(root).expect("below root").to_path_buf());
            }
        }
    }
    let mut found = Vec::new();
    walk(dir, dir, &mut found);
    found.sort();
    found
}

fn holds_canary(bytes: &[u8]) -> bool {
    bytes
        .windows(CANARY_PROJECT.len())
        .any(|w| w == CANARY_PROJECT.as_bytes())
}

/// Whether any member of the zip `bytes` holds the canary. The members are
/// deflated, so the canary is not a literal run of bytes in the archive.
fn zip_holds_canary(bytes: &[u8]) -> bool {
    use std::io::Read as _;
    let Ok(mut archive) = zip::ZipArchive::new(std::io::Cursor::new(bytes)) else {
        return false;
    };
    (0..archive.len()).any(|i| {
        let mut member = Vec::new();
        archive
            .by_index(i)
            .expect("member")
            .read_to_end(&mut member)
            .expect("read member");
        holds_canary(&member)
    })
}

/// The files below `dir` that hold the canary, leaving out the entries
/// [`PROJECTS_CANARY_EXEMPT`] names when `honour_exempt`.
fn canary_files(dir: &Path, honour_exempt: bool) -> Vec<PathBuf> {
    files_below(dir)
        .into_iter()
        .filter(|rel| !(honour_exempt && is_canary_exempt(rel)))
        .filter(|rel| {
            let bytes = std::fs::read(dir.join(rel)).expect("read file");
            holds_canary(&bytes) || zip_holds_canary(&bytes)
        })
        .collect()
}

/// The canary is on neither stream.
fn assert_streams_canary_free(out: &std::process::Output, what: &str) {
    assert!(
        !String::from_utf8_lossy(&out.stdout).contains(CANARY_PROJECT),
        "canary on stdout: {what}"
    );
    assert!(
        !String::from_utf8_lossy(&out.stderr).contains(CANARY_PROJECT),
        "canary on stderr: {what}"
    );
}

/// The canary is in no scanned file of any run directory, and not in the
/// release record directory. The scan is never vacuous: each run directory
/// must hold the four audit files and the walk must have found them.
/// Returns the run directories scanned.
fn assert_run_files_canary_free(fx: &Fixture, what: &str) -> Vec<PathBuf> {
    let dirs = run_dirs(fx);
    for dir in &dirs {
        let walked = files_below(dir);
        for file in ["run.json", "plan.json", "events.ndjson", "result.json"] {
            assert!(
                walked.iter().any(|rel| rel == Path::new(file)),
                "{file} was scanned in {dir:?}: {what}"
            );
        }
        let leaks = canary_files(dir, true);
        assert!(leaks.is_empty(), "canary in {leaks:?} of {dir:?}: {what}");
    }
    let records = fx.data.join("ign-deploy");
    if records.exists() {
        let leaks = canary_files(&records, false);
        assert!(leaks.is_empty(), "canary in the record {leaks:?}: {what}");
    }
    dirs
}

/// The one exempt file exists, holds the canary, is owner-only inside owner
/// -only directories, is the only exempt file, and git ignores it.
fn assert_exempt_pre_image(fx: &Fixture, run_dir: &Path) {
    let exempt: Vec<PathBuf> = files_below(run_dir)
        .into_iter()
        .filter(|rel| is_canary_exempt(rel))
        .collect();
    assert_eq!(
        exempt,
        [PathBuf::from("export/CapApp.zip")],
        "the pre-image is the only exempt file"
    );
    let pre = run_dir.join("export/CapApp.zip");
    assert!(
        zip_holds_canary(&std::fs::read(&pre).expect("pre-image")),
        "the exempt file holds the canary (the exemption is not vacuous)"
    );
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = |p: &Path| std::fs::metadata(p).expect("stat").permissions().mode() & 0o777;
        assert_eq!(mode(&pre), 0o600, "the pre-image is 0600");
        assert_eq!(mode(&run_dir.join("export")), 0o700);
        assert_eq!(mode(run_dir), 0o700, "inside a 0700 run directory");
    }
    let status = std::process::Command::new("git")
        .arg("-C")
        .arg(&fx.repo)
        .args(["check-ignore", "-q", "--"])
        .arg(&pre)
        .status()
        .expect("git check-ignore");
    assert_eq!(status.code(), Some(0), "git ignores the pre-image");
}

/// A confirmed import of a project whose checkout and live copy both carry
/// the canary, in `--json` or human mode.
async fn canary_apply(human: bool) {
    let what = if human { "apply, human" } else { "apply, json" };
    let fx = canary_fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CANARY_LIVE, true)),
        export_zip(CANARY_CHECKOUT, true),
    )
    .await;
    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    if human {
        args.remove(0);
    }

    let out = run(&server, &args);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{what}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // The import really ran, so the canary-bearing export really was read.
    let imports = position(&methods(&server).await, "POST", "/import/");
    assert_eq!(imports.len(), 1, "{what}");
    assert_streams_canary_free(&out, what);
    let dirs = assert_run_files_canary_free(&fx, what);
    assert_eq!(dirs.len(), 1, "{what}");
    assert_exempt_pre_image(&fx, &dirs[0]);
    // The release record exists (so the scan of it is not vacuous).
    let record = std::fs::read_to_string(record_path(&fx)).expect("record");
    assert!(record.contains("v1.1.0"), "{what}: {record}");
}

/// SC-5, DSURF-03, DPRJ-03: a confirmed import never lets project content
/// reach stdout, stderr, a run file or the release record; only the pre-image
/// holds it.
#[tokio::test]
async fn projects_canary_apply_json_and_human() {
    canary_apply(false).await;
    canary_apply(true).await;
}

/// A deploy whose read-back differs from the checkout, in `--json` or human
/// mode: the verdict path prints names and hashes only.
async fn canary_unverified(human: bool) {
    let what = if human {
        "unverified, human"
    } else {
        "unverified, json"
    };
    let fx = canary_fixture();
    git_ignore_runs(&fx);
    put_record(&fx, "v1.0.0");
    let record_before = std::fs::read(record_path(&fx)).expect("record");
    let hash = artifact_hash(&fx);
    let server = MockServer::start().await;
    mount_deployable(
        &server,
        Some(export_zip(CANARY_LIVE, true)),
        export_zip(CANARY_BAD, true),
    )
    .await;
    let mut args = apply_args(&fx, "v1.1.0", Some(&hash), true);
    if human {
        args.remove(0);
    }

    let out = run(&server, &args);
    assert_eq!(
        out.status.code(),
        Some(6),
        "{what}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("imported_unverified"),
        "{what}: the verdict path ran"
    );
    assert_streams_canary_free(&out, what);
    let dirs = assert_run_files_canary_free(&fx, what);
    assert_eq!(dirs.len(), 1, "{what}");
    assert_exempt_pre_image(&fx, &dirs[0]);
    assert_eq!(
        std::fs::read(record_path(&fx)).expect("record"),
        record_before,
        "{what}: no record for an unverified import"
    );
}

/// `--check` over a canary-bearing live project, and an `imported_unverified`
/// verdict, in both output modes.
#[tokio::test]
async fn projects_canary_check_and_verdict() {
    for human in [false, true] {
        let what = if human { "check, human" } else { "check, json" };
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let server = MockServer::start().await;
        mount_list(&server, &["CapApp"]).await;
        mount_find_found(&server).await;
        mount_export(&server, export_zip(CANARY_LIVE, true)).await;
        let mut args = args_with(&fx, "v1.1.0", &[]);
        if human {
            args.remove(0);
        }

        let out = run(&server, &args);
        assert_eq!(
            out.status.code(),
            Some(0),
            "{what}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        // The live export was read and compared (the check is not vacuous).
        let requests = methods(&server).await;
        assert!(
            !position(&requests, "GET", "/export/").is_empty(),
            "{what}: {requests:?}"
        );
        if !human {
            let envelope: Value = serde_json::from_slice(&out.stdout).expect("envelope");
            assert_eq!(envelope["data"]["action"], "import", "{what}");
        }
        assert_streams_canary_free(&out, what);
        assert!(
            !fx.repo.join(".ign").exists(),
            "{what}: a check writes no run"
        );
        assert!(assert_run_files_canary_free(&fx, what).is_empty());
    }
    canary_unverified(false).await;
    canary_unverified(true).await;
}

/// The export answers `first` once and `later` from then on: a project that
/// another administrator edits between the plan and the pre-image.
struct ExportMoves {
    calls: Arc<std::sync::atomic::AtomicUsize>,
    first: Vec<u8>,
    later: Vec<u8>,
}

impl Respond for ExportMoves {
    fn respond(&self, _request: &Request) -> ResponseTemplate {
        let n = self.calls.fetch_add(1, Ordering::SeqCst);
        let zip = if n == 0 { &self.first } else { &self.later };
        ResponseTemplate::new(200)
            .set_body_raw(zip.clone(), "application/zip")
            .insert_header(
                "Content-Disposition",
                "attachment; filename=\"CapApp-export.zip\"",
            )
    }
}

/// A refused run: exit 6, one error envelope on stderr with `code`, nothing
/// on stdout, and the canary on neither stream nor in the message.
fn assert_canary_refusal(out: &std::process::Output, code: &str) {
    assert_eq!(
        out.status.code(),
        Some(6),
        "{code}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = error_of(out);
    assert_eq!(err["error"]["code"], code);
    assert_streams_canary_free(out, code);
}

/// SC-5, DSURF-03: every refusal of a confirmed run says nothing of the
/// project, and leaves nothing but the exempt pre-image behind. The checkout
/// and the live export both hold the canary throughout.
#[tokio::test]
async fn projects_canary_refusals() {
    // project_hash_mismatch: refused before any request, no run directory.
    {
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let server = MockServer::start().await;
        mount_deployable(
            &server,
            Some(export_zip(CANARY_LIVE, true)),
            export_zip(CANARY_CHECKOUT, true),
        )
        .await;
        let zeros = "0".repeat(64);
        let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&zeros), true));
        assert_canary_refusal(&out, "project_hash_mismatch");
        assert!(methods(&server).await.is_empty(), "no request was sent");
        assert!(!fx.repo.join(".ign").exists(), "no run directory");
    }

    // deploy_preflight_failed, designers: refused before the run directory.
    {
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let hash = artifact_hash(&fx);
        let server = MockServer::start().await;
        mount_deployable(
            &server,
            Some(export_zip(CANARY_LIVE, true)),
            export_zip(CANARY_CHECKOUT, true),
        )
        .await;
        mount_designers(&server, &[("alice", "CapApp", "10.0.0.5:52526")]).await;
        let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
        assert_canary_refusal(&out, "deploy_preflight_failed");
        let requests = methods(&server).await;
        assert!(!position(&requests, "GET", "/export/").is_empty());
        assert!(position(&requests, "POST", "/import/").is_empty());
        assert!(!fx.repo.join(".ign").exists(), "no run directory");
    }

    // deploy_preflight_failed, wrong target.
    {
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let hash = artifact_hash(&fx);
        let server = MockServer::start().await;
        mount_deployable(
            &server,
            Some(export_zip(CANARY_LIVE, true)),
            export_zip(CANARY_CHECKOUT, true),
        )
        .await;
        mount_gateway_name(&server, "somewhere-else", 1).await;
        let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
        assert_canary_refusal(&out, "deploy_preflight_failed");
        let requests = methods(&server).await;
        assert!(!position(&requests, "GET", "/export/").is_empty());
        assert!(position(&requests, "POST", "/import/").is_empty());
        assert!(!fx.repo.join(".ign").exists(), "no run directory");
    }

    // plan_stale: the live project moves between the plan and the pre-image.
    {
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let hash = artifact_hash(&fx);
        let record_before = std::fs::read(record_path(&fx)).expect("record");
        let server = MockServer::start().await;
        mount_deployable(
            &server,
            Some(export_zip(CANARY_LIVE, true)),
            export_zip(CANARY_CHECKOUT, true),
        )
        .await;
        // Ahead of the plain export of `mount_deployable`.
        Mock::given(method("GET"))
            .and(path("/data/api/v1/projects/export/CapApp"))
            .respond_with(ExportMoves {
                calls: Arc::default(),
                first: export_zip(CANARY_LIVE, true),
                later: export_zip(CANARY_BAD, true),
            })
            .with_priority(1)
            .mount(&server)
            .await;
        let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
        assert_canary_refusal(&out, "plan_stale");
        let requests = methods(&server).await;
        assert!(
            position(&requests, "POST", "/import/").is_empty(),
            "nothing is imported: {requests:?}"
        );
        let dirs = assert_run_files_canary_free(&fx, "plan_stale");
        assert_eq!(dirs.len(), 1, "plan_stale");
        assert_exempt_pre_image(&fx, &dirs[0]);
        let result: Value = serde_json::from_slice(
            &std::fs::read(dirs[0].join("result.json")).expect("result.json"),
        )
        .expect("result.json is json");
        assert_eq!(result["slug"], "plan_stale");
        assert_eq!(
            std::fs::read(record_path(&fx)).expect("record"),
            record_before,
            "no record for a stale run"
        );
    }

    // import_denied: the gateway refuses the import over a 200 answer.
    {
        let fx = canary_fixture();
        git_ignore_runs(&fx);
        put_record(&fx, "v1.0.0");
        let hash = artifact_hash(&fx);
        let record_before = std::fs::read(record_path(&fx)).expect("record");
        let server = MockServer::start().await;
        mount_deployable(
            &server,
            Some(export_zip(CANARY_LIVE, true)),
            export_zip(CANARY_CHECKOUT, true),
        )
        .await;
        Mock::given(method("POST"))
            .and(path("/data/api/v1/projects/import/CapApp"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "success": false,
                "problem": "the gateway refused the import"
            })))
            .with_priority(1)
            .mount(&server)
            .await;
        let out = run(&server, &apply_args(&fx, "v1.1.0", Some(&hash), true));
        assert_canary_refusal(&out, "import_denied");
        let requests = methods(&server).await;
        assert_eq!(
            position(&requests, "POST", "/import/").len(),
            1,
            "the import was sent: {requests:?}"
        );
        let dirs = assert_run_files_canary_free(&fx, "import_denied");
        assert_eq!(dirs.len(), 1, "import_denied");
        assert_exempt_pre_image(&fx, &dirs[0]);
        let result: Value = serde_json::from_slice(
            &std::fs::read(dirs[0].join("result.json")).expect("result.json"),
        )
        .expect("result.json is json");
        assert_eq!(result["slug"], "import_denied");
        assert_eq!(
            std::fs::read(record_path(&fx)).expect("record"),
            record_before,
            "no record for a denied import"
        );
    }
}