paperboy 0.6.0

A Rust TUI API tester
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
//! Static validation of a [`ReportFlow`] — run on open/edit and before a run.
//!
//! The parser already guarantees a structurally well-formed flow (balanced
//! `FOR`/`END`, valid syntax, reserved `JOIN`/`ON` rejected). This pass adds the
//! *semantic* checks that need the whole flow (and, when available, the bound
//! collection + loaded environments):
//!
//! - a `collection:` directive is present and (with context) every
//!   `REQUEST`/`REPORT REQUEST` name resolves to exactly one entry;
//! - destructuring arity matches the producer, where statically known;
//! - `LIST` names are unique and referenced only after declaration;
//! - `ENVS` role clauses obey the ≤1 `BASELINE` / ≥1 `COMPARISON` rule and
//!   (with context) name only loaded environments;
//! - `output:` is a supported format.
//!
//! Diagnostics never abort; the caller decides whether any `Error` blocks a run.

use std::collections::{HashMap, HashSet};

use super::flow::{
    Element, EnvClause, FlowNode, OverrideTarget, ParamKind, Pattern, Producer, ReportFlow,
    ReportStmt, RoleRef, ShowField, UsingItem,
};
use crate::i18n::{Strings, fill};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    Error,
    Warning,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    pub severity: Severity,
    pub message: String,
}

impl Diagnostic {
    fn error(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Error,
            message: msg.into(),
        }
    }
    fn warning(msg: impl Into<String>) -> Self {
        Diagnostic {
            severity: Severity::Warning,
            message: msg.into(),
        }
    }
}

/// What's known about the environment a flow will run in. Both fields are
/// optional: `None` means "not bound yet", so name-resolution checks are
/// skipped (with a single reminder diagnostic) rather than producing noise.
pub struct Context<'a> {
    /// Full entry titles (incl. virtual-folder paths) of the bound collection.
    pub request_titles: Option<&'a [String]>,
    /// Names of environments currently loaded (for `ENVS` resolution).
    pub env_names: Option<&'a [String]>,
    /// Each bound-collection entry's full title paired with its `[Reports]`
    /// field names — used to validate a `SHOW(...)` selector's field list
    /// against the fields the request can actually produce. `None` when no
    /// collection is bound (the check is then skipped).
    pub request_fields: Option<&'a [(String, Vec<String>)]>,
    /// The directory relative paths resolve against (the report's folder or a
    /// `# root:` override). When present, a `# baseline:` snapshot that doesn't
    /// exist on disk is flagged so the user finds out before running rather
    /// than after. `None` skips the filesystem check (e.g. an unsaved report).
    pub root: Option<&'a std::path::Path>,
    /// Variable names that the report's effective base environment provides
    /// (global + pinned, or the `# environment:` override). `None` means the
    /// environment isn't known at validation time — the variable-availability
    /// check is skipped entirely to avoid false positives.
    pub base_var_names: Option<&'a [String]>,
    /// Union of every variable name defined across ALL loaded environments —
    /// used conservatively inside `FOR … IN ENVS` loop bodies, where any of
    /// the named environments may be active so any of their variables is
    /// potentially in scope. `None` skips the check inside ENVS bodies.
    pub all_env_var_names: Option<&'a [String]>,
    /// The bound collection's entries, used to scan each request's `{{VAR}}`
    /// references and to know which names its `[Captures]` block defines after
    /// it runs. `None` (unbound collection) skips the variable-availability
    /// check entirely.
    pub request_entries: Option<&'a [crate::hurl::HurlEntry]>,
    /// Aliased helper collections declared by extra `# collection: … AS x`
    /// directives, already loaded. Names resolve within one of these only when
    /// written `alias/name`, exactly as at run time — validation must agree with
    /// [`super::run::resolve_qualified`] or a report passes here and fails there.
    pub helpers: &'a [super::run::HelperCollection],
    /// Helper collections that were declared but couldn't be read, as
    /// `(reference, reason)`. Flagged on the directive so it's a validation
    /// error rather than a surprise mid-run.
    pub helper_errors: &'a [(String, String)],
    /// The language to phrase diagnostics in. They are user-facing text like
    /// any other, so they live in the `i18n` table rather than as literals
    /// here — a validation message is often the only thing standing between a
    /// user and a report that runs, which is exactly when it must be readable.
    pub strings: &'a Strings,
}

impl Default for Context<'_> {
    /// An empty context in English — every optional check skipped. Hand-written
    /// only because a `&Strings` has no `Default` of its own.
    fn default() -> Self {
        Self {
            request_titles: None,
            env_names: None,
            request_fields: None,
            root: None,
            base_var_names: None,
            all_env_var_names: None,
            request_entries: None,
            helpers: &[],
            helper_errors: &[],
            strings: Strings::english(),
        }
    }
}

/// Whether any step anywhere in the flow (loop bodies included) emits a column.
fn emits_a_column(nodes: &[FlowNode]) -> bool {
    nodes.iter().any(|n| match n {
        FlowNode::Report(_) => true,
        FlowNode::ForEach { body, .. }
        | FlowNode::ForEnvs { body, .. }
        | FlowNode::Graph { body, .. } => emits_a_column(body),
        _ => false,
    })
}

/// Validate `flow` against `ctx`, returning all diagnostics (errors + warnings).
pub fn validate(flow: &ReportFlow, ctx: &Context) -> Vec<Diagnostic> {
    let mut diags = Vec::new();
    let s = ctx.strings;

    // Header: collection binding + output format. A `REQUESTS` section is its
    // own declaration — a flow that carries its requests needs no binding, and
    // demanding one would make the single-file monitor impossible.
    // The declaration is the section, not the requests it yielded: a malformed
    // one must be reported as malformed, not compounded with "and you have no
    // collection either".
    let embedded = flow.embedded_entries();
    let declares = flow.requests.is_some();
    match flow.header.collection() {
        None if declares => {}
        None => diags.push(Diagnostic::error(s.diag_collection_unset)),
        Some(c) if c.trim().is_empty() && !declares => {
            diags.push(Diagnostic::error(s.diag_collection_unset))
        }
        Some(_) => {}
    }
    check_embedded_requests(flow, &embedded, ctx, &mut diags);
    check_collection_directives(flow, ctx, &mut diags);
    if let Some(out) = flow.header.output() {
        let out = out.trim();
        if !out.is_empty()
            && !super::writer::OUTPUT_EXTENSIONS
                .iter()
                .any(|e| out.eq_ignore_ascii_case(e))
        {
            diags.push(Diagnostic::error(fill(
                s.diag_output_unsupported,
                &[out, &super::writer::OUTPUT_EXTENSIONS.join(", ")],
            )));
        }
    }
    // Two resolved columns that share the same header collide when the report is
    // written as JSON (row objects are keyed by header, so the later column
    // silently overwrites the earlier one) — a data loss the other formats don't
    // have. Reject a duplicate header up front so every format stays faithful;
    // the fix is to give each column a distinct `AS <name>`.
    if let Some(spec) = flow.header.columns() {
        let cols = super::model::parse_columns(spec);
        let mut seen: Vec<&str> = Vec::new();
        let mut reported: Vec<&str> = Vec::new();
        for header in cols.iter().map(|c| c.header.as_str()) {
            if seen.contains(&header) {
                if !reported.contains(&header) {
                    diags.push(Diagnostic::error(fill(s.diag_duplicate_column, &[&header])));
                    reported.push(header);
                }
            } else {
                seen.push(header);
            }
        }
    }
    // Ground truth: the `# labels:` vocabulary and the `TRUTH` clauses that use
    // it. None of these block a run — a report that scores nothing still runs
    // and still produces its table — but each one is a silent no-op otherwise,
    // and a silently unscored column is exactly what ground truth exists to
    // stop happening.
    let labels = super::labels::LabelMap::parse(&flow.header.labels());
    for line in labels.malformed() {
        diags.push(Diagnostic::warning(fill(s.diag_labels_malformed, &[line])));
    }
    for (synonym, kept, asked) in labels.conflicts() {
        diags.push(Diagnostic::warning(fill(
            s.diag_labels_conflict,
            &[synonym, kept, asked, kept],
        )));
    }
    let images = flow.column_images();
    for (header, template) in flow.column_truths() {
        if template.trim().is_empty() {
            diags.push(Diagnostic::warning(fill(s.diag_truth_empty, &[&header])));
        }
        if images.contains_key(&header) {
            diags.push(Diagnostic::warning(fill(s.diag_truth_on_image, &[&header])));
        }
    }

    // An optional `# environment:` names a single already-loaded environment to
    // use as the report's base variable layer (the plain, no-comparison run).
    // Like an `ENVS` loop, the environment must be loaded — flag it when it
    // isn't (only once the loaded set is known).
    if let Some(env) = flow.header.environment() {
        let env = env.trim();
        if env.is_empty() {
            diags.push(Diagnostic::error(s.diag_environment_unset));
        } else if let Some(loaded) = ctx.env_names
            && !loaded.iter().any(|e| e == env)
        {
            diags.push(Diagnostic::error(fill(
                s.diag_environment_not_loaded,
                &[env],
            )));
        }
    }

    // A `# baseline:` snapshot diff and a live `ENVS BASELINE/COMPARISON`
    // clause both fill the `Result` column; the live comparison takes
    // precedence (see `run::run_flow`), so flag the directive as ignored rather
    // than let it silently do nothing.
    if flow.header.baseline().is_some_and(|b| !b.trim().is_empty())
        && super::compare::comparison_roles(flow).is_some()
    {
        diags.push(Diagnostic::warning(s.diag_baseline_ignored));
    } else if let Some(rel) = flow
        .header
        .baseline()
        .map(str::trim)
        .filter(|b| !b.is_empty())
        && let Some(root) = ctx.root
    {
        // The snapshot will be diffed against at finalize time; a missing file
        // there is only a non-fatal run error, so warn up front (once the
        // report is anchored) that the referenced snapshot can't be found.
        let path = super::producers::resolve_path(Some(root), rel);
        if !path.exists() {
            diags.push(Diagnostic::warning(fill(
                s.diag_baseline_missing,
                &[rel, &path.display().to_string()],
            )));
        }
    }

    // A report whose steps never emit a column runs perfectly and produces an
    // empty table. That is almost always a `REQUEST` that should have been a
    // `REPORT` — the distinction is the first thing a newcomer to the block
    // editor trips over, and nothing else in the UI mentions it.
    if !flow.nodes.is_empty() && !emits_a_column(&flow.nodes) {
        diags.push(Diagnostic::warning(s.diag_no_columns));
    }

    if ctx.request_titles.is_none() {
        diags.push(Diagnostic::warning(s.diag_collection_not_loaded));
    }

    // Parameters are read off the flow without executing it, so they have to
    // be findable: confined to the prelude, uniquely named, and consistent
    // with their own declared type.
    check_params(flow, ctx, &mut diags);

    // An `ENVS` clause may name its environments through parameters, which is
    // how one report compares two stacks this week and two others the next.
    // Those names are judged here rather than in `check_env_clause`, which sees
    // one clause at a time and not the declarations they refer to.
    check_env_refs(flow, ctx, &mut diags);

    // Walk the tree with a scope stack of declared LIST producers.
    let mut scopes: Vec<HashMap<String, Producer>> = vec![HashMap::new()];
    walk(&flow.nodes, ctx, &mut scopes, &mut diags);

    // Step identity: every request statement has to be nameable, and a name has
    // to identify one step within the scopes that can see it.
    check_step_names(flow, ctx, &mut diags);

    // `GRAPH` regions: what may appear inside one, where one may appear, and
    // whether the graph it declares can be ordered at all.
    check_regions(&flow.nodes, ctx, false, &mut diags);

    // Variable-availability analysis: walk the flow in execution order and
    // warn when a request references a `{{VAR}}` that is provably not defined
    // at that point. Only runs when both the base-env variable names AND the
    // bound collection's entries are known; if either is absent we can't
    // distinguish "definitely undefined" from "defined by an unknown source"
    // and must stay silent to avoid false positives.
    if ctx.request_entries.is_some() && ctx.base_var_names.is_some() {
        let mut defined = initial_defined_vars(ctx);
        check_var_availability(&flow.nodes, ctx, &mut defined, &mut diags);
    }

    diags
}

/// Whether a node is one of the "does nothing yet" statements a `PARAM` may
/// legally follow: another parameter, a plain assignment (`PRELUDE_*` settings
/// and constants), or a comment.
fn is_prelude_node(node: &FlowNode) -> bool {
    matches!(
        node,
        FlowNode::Param(_) | FlowNode::Assign { .. } | FlowNode::Comment(_)
    )
}

/// Check every `PARAM` in the flow: that it is in the prelude at all (a
/// parameter buried in a loop can never be offered before the run, so it would
/// silently be an ordinary assignment), that no two share a name, and that
/// each default agrees with its declared type.
fn check_params(flow: &ReportFlow, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let s = ctx.strings;

    // Anything after the first statement that acts can't be offered up front.
    let prelude_end = flow
        .nodes
        .iter()
        .position(|n| !is_prelude_node(n))
        .unwrap_or(flow.nodes.len());
    for p in nested_params(&flow.nodes[prelude_end..]) {
        diags.push(Diagnostic::error(fill(
            s.diag_param_not_in_prelude,
            &[&p.name],
        )));
    }

    let mut seen: HashSet<&str> = HashSet::new();
    // Two parameters that prompt with the same words make a form nobody can
    // fill in correctly, whether the clash is between two `LABEL`s or between
    // two names that read the same once made readable (`TICKET_REF` and
    // `ticket_ref`). It isn't an error — the report still runs, and the names
    // are distinct — but it is always a mistake worth saying out loud.
    let mut prompts: HashSet<String> = HashSet::new();
    for p in flow.params() {
        if !seen.insert(&p.name) {
            diags.push(Diagnostic::error(fill(s.diag_param_duplicate, &[&p.name])));
        }
        let prompt = p.prompt();
        if !prompts.insert(prompt.to_lowercase()) {
            diags.push(Diagnostic::warning(fill(
                s.diag_param_prompt_clash,
                &[&prompt],
            )));
        }
        check_param_default(p, ctx, diags);
    }
}

/// Every `PARAM` anywhere in `nodes`, loop bodies included — used to find the
/// ones that are past the prelude, wherever they are hiding.
fn nested_params<'a>(nodes: &'a [FlowNode]) -> Vec<&'a super::flow::ParamDecl> {
    let mut out = Vec::new();
    for node in nodes {
        match node {
            FlowNode::Param(p) => out.push(p),
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                out.extend(nested_params(body));
            }
            _ => {}
        }
    }
    out
}

/// Judge the `ENVS` names that are written as `{{PARAM}}` rather than spelled
/// out: once the parameters' defaults are filled in, is what the name
/// currently means actually loaded? Only a warning — changing it per run is
/// the entire point — and only answerable at all when every reference in the
/// name is a parameter, since nothing else has a value to substitute here.
///
/// Whether the reference resolves to *anything* is a separate question, asked
/// by `check_var_availability` where the scope at the clause is known. It used
/// to be asked here, and answered "only a parameter will do", on the grounds
/// that an `ENVS` clause is read before the first request has run. That was
/// never true of the interpreter: `run_for_envs` resolves the clause when it
/// reaches it, against everything then in scope, so a loop variable — the way
/// `BASELINE("prod-{{region}}")` inside a `FOR` is written, and the reason
/// role targets are resolved per visit — is perfectly resolvable.
fn check_env_refs(flow: &ReportFlow, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let s = ctx.strings;
    let declared = flow.params();
    let defaults = super::params::effective(&declared, &Default::default());
    for name in env_ref_names(&flow.nodes) {
        let resolved = crate::environment::substitute(name, &defaults);
        if resolved.contains("{{") {
            // Still unresolved: a required parameter with no default. What it
            // will be is decided in the run settings, so there is nothing to
            // check here.
            continue;
        }
        if let Some(loaded) = ctx.env_names
            && !loaded.iter().any(|e| *e == resolved)
        {
            diags.push(Diagnostic::warning(fill(
                s.diag_env_ref_default_not_loaded,
                &[name, &resolved],
            )));
        }
    }
}

/// Every live environment name in every `ENVS` clause in the tree that is
/// written through a `{{…}}` reference (a `FILE(…)` role is a path, not an
/// environment, and is left to the snapshot checks).
fn env_ref_names<'a>(nodes: &'a [FlowNode]) -> Vec<&'a String> {
    let mut out = Vec::new();
    for node in nodes {
        match node {
            FlowNode::ForEnvs { clause, body, .. } => {
                let names: Vec<&String> = match clause {
                    EnvClause::Plain(names) => names.iter().collect(),
                    EnvClause::Roles {
                        baseline,
                        comparisons,
                        ..
                    } => baseline
                        .iter()
                        .chain(comparisons.iter())
                        .filter_map(|r| match r {
                            RoleRef::Env(n) => Some(n),
                            RoleRef::File(_) => None,
                        })
                        .collect(),
                };
                out.extend(names.into_iter().filter(|n| n.contains("{{")));
                out.extend(env_ref_names(body));
            }
            FlowNode::ForEach { body, .. } => out.extend(env_ref_names(body)),
            _ => {}
        }
    }
    out
}

fn check_param_default(p: &super::flow::ParamDecl, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let s = ctx.strings;
    let default = p.default.as_deref().map(str::trim);
    match &p.kind {
        ParamKind::Choice(options) => {
            if options.is_empty() {
                diags.push(Diagnostic::error(fill(s.diag_param_no_choices, &[&p.name])));
            } else if let Some(d) = default.filter(|d| !d.is_empty())
                && !options.iter().any(|o| o == d)
            {
                diags.push(Diagnostic::error(fill(
                    s.diag_param_bad_choice,
                    &[&p.name, d, &options.join(", ")],
                )));
            }
        }
        // A default that interpolates something is checked at run time, when
        // there is something to interpolate; refusing `{{PORT}}` here would
        // reject a perfectly good report.
        ParamKind::Number => {
            if let Some(d) = default.filter(|d| !d.is_empty())
                && !d.contains("{{")
                && d.parse::<f64>().is_err()
            {
                diags.push(Diagnostic::error(fill(
                    s.diag_param_not_a_number,
                    &[&p.name, d],
                )));
            }
        }
        // An environment parameter is *meant* to be changed per run, so a
        // default naming an environment that isn't loaded right now is a
        // warning, not an error — unlike the `# environment:` directive, which
        // is the report's fixed choice.
        ParamKind::Env => {
            if let Some(d) = default.filter(|d| !d.is_empty())
                && !d.contains("{{")
                && let Some(loaded) = ctx.env_names
                && !loaded.iter().any(|e| e == d)
            {
                diags.push(Diagnostic::warning(fill(
                    s.diag_param_env_not_loaded,
                    &[&p.name, d],
                )));
            }
        }
        ParamKind::Text | ParamKind::Folder | ParamKind::File => {}
    }
}

fn walk(
    nodes: &[FlowNode],
    ctx: &Context,
    scopes: &mut Vec<HashMap<String, Producer>>,
    diags: &mut Vec<Diagnostic>,
) {
    for node in nodes {
        match node {
            // Nothing to check in a comment.
            FlowNode::Comment(_) => {}
            FlowNode::Assign { .. } => {}
            // Parameters are checked as a set, before this walk.
            FlowNode::Param(_) => {}
            FlowNode::ListDecl { name, producer } => {
                check_producer(producer, ctx, scopes, diags);
                if scopes.iter().any(|s| s.contains_key(name)) {
                    diags.push(Diagnostic::warning(fill(
                        ctx.strings.diag_list_shadowed,
                        &[name],
                    )));
                }
                scopes
                    .last_mut()
                    .unwrap()
                    .insert(name.clone(), producer.clone());
            }
            FlowNode::Request { name, using, .. } | FlowNode::Cleanup { name, using, .. } => {
                check_request_name(name, ctx, diags);
                check_using(name, using, ctx, diags);
            }
            FlowNode::Report(stmt) => check_report(stmt, ctx, diags),
            FlowNode::ForEach {
                pattern,
                producer,
                body,
                ..
            } => {
                check_producer(producer, ctx, scopes, diags);
                check_arity(pattern, producer, scopes, ctx.strings, diags);
                scopes.push(HashMap::new());
                walk(body, ctx, scopes, diags);
                scopes.pop();
            }
            FlowNode::ForEnvs { clause, body, .. } => {
                check_env_clause(clause, ctx, diags);
                scopes.push(HashMap::new());
                walk(body, ctx, scopes, diags);
                scopes.pop();
            }
            // A region is not a scope — it holds only requests, and the names
            // they use come from outside it. It reorders its body; it does not
            // enclose anything.
            FlowNode::Graph { body, .. } => walk(body, ctx, scopes, diags),
        }
    }
}

fn check_report(stmt: &ReportStmt, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    if let ReportStmt::Request {
        name,
        using,
        show,
        hide,
        with,
        ..
    } = stmt
    {
        check_request_name(name, ctx, diags);
        check_using(name, using, ctx, diags);
        check_show_hide_overlap(show, hide, ctx.strings, diags);
        check_show_fields(name, show, with, ctx, diags);
        check_hide_fields(name, hide, with, ctx, diags);
    }
}

/// Check a `USING(…)` clause against the request it names.
///
/// This is the check the clause exists for. A flow binds a request's parameters
/// just by having them in scope, which reads well but means a flow copied onto
/// a collection whose `upload_document` was never parameterised still *runs* —
/// sending the request's own hardcoded value and reporting a healthy `200`.
/// `USING(FILE)` states the requirement, and this turns a mismatch into an
/// error the moment the report is opened, quoting what the request does
/// declare so the fix is obvious.
///
/// Every check is skipped when the request can't be resolved (its name is
/// already being reported) or the collection isn't bound — validation never
/// invents a complaint out of what it can't see.
fn check_using(name: &str, using: &[UsingItem], ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let Some(entries) = ctx.request_entries else {
        return;
    };
    let Some(entry) = super::run::resolve_qualified(entries, ctx.helpers, name) else {
        return;
    };
    let s = ctx.strings;

    for item in using {
        match item {
            UsingItem::Require(param) => {
                if entry.declares_variable(param) {
                    continue;
                }
                let declared = entry.variable_defaults();
                let declared = if declared.is_empty() {
                    s.diag_using_none.to_string()
                } else {
                    declared
                        .iter()
                        .map(|(n, _)| n.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                diags.push(Diagnostic::error(fill(
                    s.diag_using_undeclared,
                    &[name, param, &declared, param],
                )));
            }
            // Only the payload-shaped targets are checked. A `header`/`query`/
            // `cookie`/`option` override upserts by design (adding a header the
            // request never had is a normal thing to want), so there is nothing
            // to be wrong about; a `form`/`multipart` field that doesn't exist
            // is a typo that would otherwise send a subtly wrong body.
            UsingItem::Override { target, .. } => match target {
                OverrideTarget::Form(k) | OverrideTarget::Multipart(k) => {
                    if entry.form_fields.iter().any(|f| &f.key == k) {
                        continue;
                    }
                    let known: Vec<&str> =
                        entry.form_fields.iter().map(|f| f.key.as_str()).collect();
                    let known = if known.is_empty() {
                        s.diag_using_no_fields.to_string()
                    } else {
                        fill(s.diag_using_has_fields, &[&known.join(", ")])
                    };
                    let section = match target {
                        OverrideTarget::Form(_) => "form",
                        _ => "multipart",
                    };
                    diags.push(Diagnostic::error(fill(
                        s.diag_using_no_such_field,
                        &[name, section, k, &known],
                    )));
                }
                // Hurl builds a body and a form onto the same libcurl handle,
                // so the pair is unsendable — see `BODY_FORM_CONFLICT_ERROR`.
                // Overriding the body of a form request creates exactly that
                // pair, silently, which is worth catching here rather than at
                // the send.
                OverrideTarget::Body if entry.form_fields.iter().any(|f| f.enabled) => {
                    diags.push(Diagnostic::error(fill(
                        s.diag_using_body_form_conflict,
                        &[name],
                    )));
                }
                _ => {}
            },
        }
    }

    // The nudge: a request that declares parameters is meant to be driven, and
    // a statement that drives one without saying so is the copy-paste hazard
    // this feature is about. A warning rather than an error — the flow is
    // correct *here*, it just won't complain when it stops being.
    let required: Vec<&str> = using
        .iter()
        .filter_map(|i| match i {
            UsingItem::Require(p) => Some(p.as_str()),
            _ => None,
        })
        .collect();
    if required.is_empty() {
        let declared: Vec<String> = entry
            .variable_defaults()
            .into_iter()
            .map(|(n, _)| n)
            .collect();
        if !declared.is_empty() {
            diags.push(Diagnostic::warning(fill(
                s.diag_using_parameter_not_required,
                &[name, &declared.join(", ")],
            )));
        }
    }
}

/// Warn when a `SHOW(...)` field can't be produced by the request: it is
/// neither an intrinsic (`HttpStatus`/`Time`/`Asserts`/`Error`/`Response`), a
/// `WITH` field on this statement, nor a `[Reports]` field of the resolved
/// request.  Under the additive model such a field is silently ignored at
/// runtime (it will not appear in the output), so this is a warning rather than
/// an error — consistent with how `check_hide_fields` handles unknown fields.
/// Skipped when the collection isn't bound (the field set is unknown), so it
/// never false-warns on a real `[Reports]` field we can't see.
fn check_show_fields(
    name: &str,
    show: &[ShowField],
    with: &[super::flow::WithItem],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    if show.is_empty() {
        return;
    }
    // An unresolved name is already reported by `check_request_name`, so bail
    // quietly here.
    let Some(report_fields) = declared_report_fields(name, ctx) else {
        return;
    };
    let report_fields = &report_fields;
    let with_fields: Vec<&str> = with
        .iter()
        .filter_map(|w| match w {
            super::flow::WithItem::Field { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    for field in show {
        let field = field.name();
        let known = super::run::INTRINSIC_FIELDS.contains(&field)
            || with_fields.contains(&field)
            || report_fields.iter().any(|f| f == field);
        if !known {
            diags.push(Diagnostic::warning(fill(
                ctx.strings.diag_show_unknown,
                &[field, name],
            )));
        }
    }
}

/// Error when the same field suffix appears in both SHOW and HIDE — the two
/// clauses are contradictory (SHOW keeps, HIDE removes) and no ordering of
/// evaluation resolves the conflict sensibly.
fn check_show_hide_overlap(
    show: &[ShowField],
    hide: &[String],
    s: &Strings,
    diags: &mut Vec<Diagnostic>,
) {
    for field in show {
        let field = field.name();
        if hide.iter().any(|h| h == field) {
            diags.push(Diagnostic::error(fill(s.diag_show_hide_conflict, &[field])));
        }
    }
}

/// Warn when a `HIDE(...)` field can't be produced by the request (mirrors
/// `check_show_fields`): it is neither an intrinsic, a WITH field, nor a
/// `[Reports]` field of the resolved request. Skipped when the collection isn't
/// bound (the field set is unknown).
fn check_hide_fields(
    name: &str,
    hide: &[String],
    with: &[super::flow::WithItem],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    if hide.is_empty() {
        return;
    }
    let Some(report_fields) = declared_report_fields(name, ctx) else {
        return;
    };
    let resolved = Some((String::new(), report_fields));
    let Some((_, report_fields)) = resolved else {
        return;
    };
    let with_fields: Vec<&str> = with
        .iter()
        .filter_map(|w| match w {
            super::flow::WithItem::Field { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    for field in hide {
        let known = super::run::INTRINSIC_FIELDS.contains(&field.as_str())
            || with_fields.contains(&field.as_str())
            || report_fields.iter().any(|f| f == field);
        if !known {
            diags.push(Diagnostic::warning(fill(
                ctx.strings.diag_hide_unknown,
                &[field, name],
            )));
        }
    }
}

/// Resolve a request name against the bound collection's titles: exact
/// full-title → unique leaf name → error. Skipped when no collection is bound.
/// Split a `alias/name` reference when `alias` is a *declared* helper. Returns
/// the helper and the name within it. A `/` that isn't a declared alias is left
/// alone — it is far more likely a virtual-folder path.
fn split_helper<'a>(
    name: &'a str,
    ctx: &'a Context,
) -> Option<(&'a super::run::HelperCollection, &'a str)> {
    let (alias, rest) = name.split_once('/')?;
    ctx.helpers
        .iter()
        .find(|h| h.alias == alias)
        .map(|h| (h, rest))
}

/// The `# collection:` directives: exactly one primary (unaliased, first), every
/// helper aliased, aliases distinct identifiers that don't collide with a
/// top-level virtual folder, and every declared helper actually loadable.
/// Check a `REQUESTS` section: that the keyword bought something, that no
/// embedded name collides, and that nothing embedded is dead weight.
fn check_embedded_requests(
    flow: &ReportFlow,
    embedded: &[crate::hurl::HurlEntry],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    let Some(text) = &flow.requests else {
        return;
    };
    if embedded.is_empty() {
        // A section that parsed to nothing is nearly always a malformed one,
        // and the Hurl parser's own reason is far more useful than "no
        // requests" on its own.
        // Offset to the file's own numbering: the section is a slice of a
        // `.trail`, and the `.trail` is the file the reader has open.
        let why = crate::hurl::parse_hurl_error_from(text, flow.requests_line.max(1));
        diags.push(Diagnostic::error(fill(
            ctx.strings.diag_requests_section_empty,
            &[why.as_deref().unwrap_or("")],
        )));
        return;
    }

    // A collision is counted against the merged title list rather than against
    // the external collection alone, so two embedded requests sharing a name
    // are caught by the same rule — both leave a reference meaning one of two
    // things, which is the actual problem.
    if let Some(titles) = ctx.request_titles {
        for e in embedded {
            if titles.iter().filter(|t| **t == e.title).count() > 1 {
                diags.push(Diagnostic::error(fill(
                    ctx.strings.diag_requests_name_collision,
                    &[&e.title],
                )));
            }
        }
    }

    // Unreferenced is a warning, not an error: "unused by this --targets
    // selection" is ordinary, but "unused by any step" is worth saying, because
    // an embedded request nothing calls is dead text in the one file that was
    // supposed to be self-contained.
    let mut called = Vec::new();
    collect_called(&flow.nodes, &mut called);
    let titles = ctx.request_titles.unwrap_or(&[]);
    for e in embedded {
        // Resolution order, not a looser guess: a call is only a use of this
        // embedded request if it names it exactly, or if it is a path whose
        // leaf matches *and* nothing declares that exact path. Otherwise
        // `REQUEST folder/ping` against an external `folder/ping` would count
        // as calling an embedded `ping` that in fact never runs.
        let used = called.iter().any(|c| {
            if *c == e.title {
                return true;
            }
            // A helper alias is resolved *before* any title, so `helper/ping`
            // is a call on the helper collection and says nothing about an
            // embedded `ping` — which stays dead text, and has to still be
            // reported as such.
            if c.split_once('/')
                .is_some_and(|(alias, _)| ctx.helpers.iter().any(|h| h.alias == alias))
            {
                return false;
            }
            c.rsplit('/').next() == Some(e.title.as_str()) && !titles.iter().any(|t| t == c)
        });
        if !used {
            diags.push(Diagnostic::warning(fill(
                ctx.strings.diag_requests_unreferenced,
                &[&e.title],
            )));
        }
    }
}

/// Every request name the flow calls, at any depth.
fn collect_called(nodes: &[FlowNode], out: &mut Vec<String>) {
    for node in nodes {
        match node {
            FlowNode::Request { name, .. } | FlowNode::Cleanup { name, .. } => {
                out.push(name.clone())
            }
            FlowNode::Report(ReportStmt::Request { name, .. }) => out.push(name.clone()),
            FlowNode::ForEach { body, .. }
            | FlowNode::ForEnvs { body, .. }
            | FlowNode::Graph { body, .. } => collect_called(body, out),
            _ => {}
        }
    }
}

fn check_collection_directives(flow: &ReportFlow, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let s = ctx.strings;
    let refs = flow.header.collections();
    let mut seen: Vec<&str> = Vec::new();
    for (i, c) in refs.iter().enumerate() {
        if i == 0 {
            // The primary is *the* collection under test, not a helper; an alias
            // on it would suggest its requests are addressed `alias/name`, which
            // they aren't.
            if c.alias.is_some() {
                diags.push(Diagnostic::error(s.diag_collection_primary_alias));
            }
            continue;
        }
        let Some(alias) = c.alias else {
            diags.push(Diagnostic::error(fill(
                s.diag_collection_alias_missing,
                // The reference appears twice: once naming the collection,
                // once inside the `# collection: … AS name` line being
                // suggested.
                &[c.reference, c.reference],
            )));
            continue;
        };
        if !crate::report::parser::is_ident(alias) {
            diags.push(Diagnostic::error(fill(
                s.diag_collection_alias_invalid,
                &[alias],
            )));
            continue;
        }
        if seen.contains(&alias) {
            diags.push(Diagnostic::error(fill(
                s.diag_collection_alias_duplicate,
                &[alias],
            )));
            continue;
        }
        seen.push(alias);
        // `/` is also the virtual-folder separator, so an alias sharing a name
        // with a top-level folder makes `folder/request` ambiguous. PaperTrail
        // never picks silently between two readings of a name, so this is an
        // error rather than a precedence rule.
        if let Some(titles) = ctx.request_titles
            && titles
                .iter()
                .any(|t| t.split('/').next() == Some(alias) && t.contains('/'))
        {
            diags.push(Diagnostic::error(fill(
                s.diag_collection_alias_shadows_folder,
                &[alias, alias],
            )));
        }
    }
    for (reference, reason) in ctx.helper_errors {
        diags.push(Diagnostic::error(fill(
            s.diag_collection_helper_unreadable,
            &[reference, reason],
        )));
    }
}

/// The step name a request statement contributes, and the request it names.
///
/// `alias` is `None` for a defaulted name, which is what tells the diagnostics
/// apart: a clash between two written names is a different mistake from a
/// clash between two names nobody wrote.
struct StepUse<'a> {
    request: &'a str,
    alias: Option<&'a str>,
    /// A cleanup runs when its *block* unwinds, not where it is written, which
    /// is what makes an inner block's reference to one in an enclosing block
    /// unsatisfiable — see the `DEPENDS` check in [`walk_step_names`].
    is_cleanup: bool,
}

fn step_use(node: &FlowNode) -> Option<StepUse<'_>> {
    match node {
        FlowNode::Request { name, alias, .. } => Some(StepUse {
            request: name,
            alias: alias.as_deref(),
            is_cleanup: false,
        }),
        FlowNode::Report(ReportStmt::Request { name, alias, .. }) => Some(StepUse {
            request: name,
            alias: alias.as_deref(),
            is_cleanup: false,
        }),
        // A cleanup is a step: it is sent, it can be named, and `DEPENDS` and
        // `{{step.var}}` both refer to it. Leaving it out let two steps share
        // one identity, and let a cleanup carry a name that is not an
        // identifier at all.
        FlowNode::Cleanup { name, alias, .. } => Some(StepUse {
            request: name,
            alias: alias.as_deref(),
            is_cleanup: true,
        }),
        _ => None,
    }
}

/// Check that every step can be named, and that a name identifies one step.
///
/// A *step* is one execution of a request. Its name is the unit of identity —
/// what a dependency clause refers to and what qualifies a capture reference —
/// so it has to be an identifier, and it has to be unambiguous. `AS` supplies
/// it; with no `AS` the request's leaf name is used, which is only viable when
/// that leaf is already an identifier.
///
/// **Uniqueness is lexical, not flow-global.** A name must be unique along any
/// one root-to-leaf path, because that is exactly the set of steps a reference
/// can see: a statement can refer to its own body and to enclosing ones, never
/// sideways into a sibling block. Two sibling loops may therefore each contain
/// a `CreateSession`, or each report `AS Liveness` to pour their rows into one
/// shared set of columns — a deliberate idiom, since a column is identified by
/// its name rather than by which statement filled it. A flow-global rule would
/// reject both, and would be rejecting readable, unambiguous flows to no end.
/// Check every `GRAPH` region's shape and its graph.
///
/// The restrictions are v1 restrictions, all relaxable later, and all errors
/// rather than warnings. The reason they are errors is the same one that makes
/// the region a construct at all: a region is an assertion about ordering, and
/// a construct whose ordering the region cannot describe — a loop, a variable
/// assignment that later steps read, a nested region with its own promise —
/// would silently narrow the assertion to something weaker than it reads as.
fn check_regions(nodes: &[FlowNode], ctx: &Context, in_region: bool, diags: &mut Vec<Diagnostic>) {
    let s = ctx.strings;
    for node in nodes {
        match node {
            FlowNode::Graph { body, .. } => {
                if in_region {
                    diags.push(Diagnostic::error(s.diag_graph_nested.to_string()));
                }
                for inner in body {
                    match inner {
                        // A comment is not a step and orders nothing, so it is
                        // simply carried; everything else in the body is.
                        FlowNode::Comment(_)
                        | FlowNode::Request { .. }
                        | FlowNode::Report(ReportStmt::Request { .. }) => {}
                        // Reported by the recursive walk below, which knows it
                        // is in a region; naming it here as well would say the
                        // same thing twice.
                        FlowNode::Cleanup { .. } => {}
                        FlowNode::ForEach { .. } | FlowNode::ForEnvs { .. } => {
                            diags.push(Diagnostic::error(s.diag_graph_loop_inside.to_string()));
                        }
                        FlowNode::Graph { .. } => {}
                        other => diags.push(Diagnostic::error(fill(
                            s.diag_graph_only_requests,
                            &[&other.label()],
                        ))),
                    }
                }
                check_regions(body, ctx, true, diags);
                check_region_graph(body, ctx, diags);
            }
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                if body.iter().any(|n| matches!(n, FlowNode::Graph { .. })) {
                    diags.push(Diagnostic::error(s.diag_graph_in_loop.to_string()));
                }
                check_regions(body, ctx, in_region, diags);
            }
            // A cleanup is already deferred and already ordered by what it
            // depends on, so its `DEPENDS` means something wherever it is
            // written. Everything else needs a region.
            FlowNode::Cleanup { .. } => {
                if in_region {
                    diags.push(Diagnostic::error(s.diag_cleanup_in_graph.to_string()));
                }
            }
            // `DEPENDS` places a step in a graph, and there is only a graph
            // inside a region. Written anywhere else it is not merely useless
            // but misleading: statements already run in the order they are
            // written, so the clause would read as a constraint while
            // constraining nothing. That covers the `FOR` case too — a region
            // may not appear in a loop, so a loop body is never in one.
            other => {
                if !in_region && !super::graph::declared_deps(other).is_empty() {
                    diags.push(Diagnostic::error(fill(
                        s.diag_depends_outside_graph,
                        &[&other.label()],
                    )));
                }
            }
        }
    }
}

/// Order the region's graph now, so a cycle or an ambiguous reference is
/// reported when the file is opened rather than partway through a run that has
/// already sent requests.
fn check_region_graph(body: &[FlowNode], ctx: &Context, diags: &mut Vec<Diagnostic>) {
    // Without a bound collection nothing is knowable about captures, so every
    // inferred edge would be missing and the "graph" would be a list.
    let Some(entries) = ctx.request_entries else {
        return;
    };
    if let Err(errs) = super::graph::build(body, entries, ctx.helpers, ctx.strings) {
        diags.extend(errs.into_iter().map(Diagnostic::error));
    }
}

fn check_step_names(flow: &ReportFlow, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let mut path: Vec<HashMap<String, StepInfo>> = vec![HashMap::new()];
    walk_step_names(&flow.nodes, ctx, &mut path, false, diags);
}

/// What the lexical walk remembers about a step already in scope.
struct StepInfo {
    /// Whether the name was written with `AS`. Recorded so a clash can name the
    /// mistake actually made: two `AS Foo`s are a duplicate the author chose,
    /// while two bare requests with the same leaf are an accident of naming
    /// that `AS` is the fix for.
    written: bool,
    /// The request this step runs, so a `{{step.var}}` reference can be checked
    /// against the captures that request actually declares.
    request: String,
    /// Whether the step is a `CLEANUP`.
    is_cleanup: bool,
}

/// The step name a use contributes, before validity is considered.
fn step_name_of(use_: &StepUse<'_>) -> String {
    match use_.alias {
        Some(a) => a.to_string(),
        None => use_
            .request
            .rsplit('/')
            .next()
            .unwrap_or(use_.request)
            .to_string(),
    }
}

fn walk_step_names(
    nodes: &[FlowNode],
    ctx: &Context,
    path: &mut Vec<HashMap<String, StepInfo>>,
    in_region: bool,
    diags: &mut Vec<Diagnostic>,
) {
    // A cleanup is written where it belongs logically but runs at the end of
    // its block, so every step in that block has already run by the time it
    // sends. Checking it in written position would reject the ordinary shape —
    // a teardown written beside the thing it tears down, above the rest of the
    // setup — so its references are checked once the block's frame is complete.
    let mut deferred: Vec<&FlowNode> = Vec::new();
    for node in nodes {
        // Outside a region, checked *before* this node's name is recorded,
        // which is what makes a step unable to refer to itself: its captures
        // don't exist until it has run. Inside one the names are registered up
        // front (a reference may point forward), so the same rule has to be
        // stated rather than fall out of the order.
        let own = if in_region {
            step_use(node).map(|u| step_name_of(&u))
        } else {
            None
        };
        check_hurl_side_qualified(node, ctx, path, diags);
        if matches!(node, FlowNode::Cleanup { .. }) {
            deferred.push(node);
        } else {
            check_qualified_refs(node, ctx, path, own.as_deref(), diags);
        }
        if in_region {
            // Already registered by the region pass below.
            if let FlowNode::Graph { body, .. } = node {
                walk_step_names(body, ctx, path, true, diags);
            }
            continue;
        }
        if let Some(use_) = step_use(node) {
            register_step(&use_, ctx, path, diags);
        }
        // A loop body is a new lexical frame: names inside it are visible to
        // the body and to nothing outside it.
        match node {
            FlowNode::ForEach { body, .. } | FlowNode::ForEnvs { body, .. } => {
                path.push(HashMap::new());
                walk_step_names(body, ctx, path, false, diags);
                path.pop();
            }
            // A region is not a lexical frame — its steps are named in the
            // enclosing one — but its names are registered *before* its body is
            // checked, because inside a region a reference may point at a step
            // written below it. That is the whole difference a region makes.
            FlowNode::Graph { body, .. } => {
                for inner in body {
                    if let Some(use_) = step_use(inner) {
                        register_step(&use_, ctx, path, diags);
                    }
                }
                walk_step_names(body, ctx, path, true, diags);
            }
            _ => {}
        }
    }
    // The block's frame is complete now, so a cleanup may name anything in it.
    let mut cleanup_deps: Vec<(String, Vec<String>)> = Vec::new();
    for node in deferred {
        let own = step_use(node).map(|u| step_name_of(&u));
        check_qualified_refs(node, ctx, path, own.as_deref(), diags);
        // A cleanup runs only if what it depends on succeeded, so a `DEPENDS`
        // naming no step at all reads as "it didn't succeed" and the teardown
        // is quietly skipped — a typo that leaves things behind and says
        // nothing. The name has to exist.
        let FlowNode::Cleanup { depends, .. } = node else {
            continue;
        };
        let here = own.as_deref().unwrap_or_default();
        cleanup_deps.push((here.to_string(), depends.clone()));
        for dep in depends {
            if dep == here {
                // It can never have succeeded when it is asked, so it would
                // always skip itself — a cycle of one, said plainly.
                diags.push(Diagnostic::error(fill(
                    ctx.strings.diag_graph_depends_self,
                    &[here],
                )));
            } else if let Some((depth, info)) = path
                .iter()
                .enumerate()
                .rev()
                .find_map(|(i, f)| f.get(dep.as_str()).map(|info| (i, info)))
            {
                // A cleanup runs when its own block unwinds. An enclosing
                // block unwinds *after* this one, so a cleanup out there
                // cannot have succeeded by the time this one is asked — it
                // would be skipped on every iteration, every run, with only a
                // warning to show for it.
                if info.is_cleanup && depth + 1 < path.len() {
                    diags.push(Diagnostic::error(fill(
                        ctx.strings.diag_cleanup_depends_outer,
                        &[here, dep, dep],
                    )));
                }
            } else {
                diags.push(Diagnostic::error(fill(
                    ctx.strings.diag_graph_depends_unknown,
                    &[here, dep],
                )));
            }
        }
    }
    check_cleanup_cycles(&cleanup_deps, ctx, diags);
}

/// Reject a `DEPENDS` cycle between two or more cleanups.
///
/// A self-dependency is caught above and says something clearer; this is for
/// the longer ring, which has no honest execution at all: every member is
/// waiting on another member that has not run, so each in turn reads its
/// prerequisite as unsuccessful and skips — the whole ring is silently torn
/// down by nobody, leaking exactly the resources it was written to reclaim.
/// Ordering cannot break the tie, so it has to be refused before the run.
fn check_cleanup_cycles(
    deps: &[(String, Vec<String>)],
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    let names: HashSet<&str> = deps.iter().map(|(n, _)| n.as_str()).collect();
    // Kahn's algorithm over the cleanup-to-cleanup edges alone: a dependency on
    // an ordinary step is a real edge but never part of a cleanup ring, and
    // pulling it in here would only report the innocent step as a member.
    let mut waiting: Vec<(&str, Vec<&str>)> = deps
        .iter()
        .map(|(n, d)| {
            let edges: Vec<&str> = d
                .iter()
                .map(String::as_str)
                .filter(|x| names.contains(x) && *x != n.as_str())
                .collect();
            (n.as_str(), edges)
        })
        .collect();
    loop {
        let Some(at) = waiting.iter().position(|(_, edges)| edges.is_empty()) else {
            break;
        };
        let (done, _) = waiting.remove(at);
        for (_, edges) in &mut waiting {
            edges.retain(|e| *e != done);
        }
    }
    if !waiting.is_empty() {
        let stuck: Vec<&str> = waiting.iter().map(|(n, _)| *n).collect();
        diags.push(Diagnostic::error(fill(
            ctx.strings.diag_graph_cycle,
            &[&stuck.join(", ")],
        )));
    }
}

/// The PaperTrail source text on `node` that is `{{VAR}}`-interpolated at run
/// time, and so may carry a step-qualified capture reference.
///
/// Only PaperTrail's own text is collected. A `.hurl` request body is left
/// alone deliberately: Hurl's expression grammar has no dotted path, so a
/// qualified name can't be written there in the first place, and the request
/// stays runnable on its own outside any flow.
pub(super) fn interpolated_source(node: &FlowNode) -> Vec<&str> {
    fn using(items: &[UsingItem]) -> Vec<&str> {
        items
            .iter()
            .filter_map(|i| match i {
                UsingItem::Override { value, .. } => Some(value.as_str()),
                UsingItem::Require(_) => None,
            })
            .collect()
    }
    // A producer path is interpolated the same way and against the same map,
    // so a dotted name written there means a step reference there too. Without
    // this the one text `vars_for_source` substitutes that validation never
    // looked at could carry a name that silently resolves to nothing.
    fn producer<'p>(p: &'p Producer, out: &mut Vec<&'p str>) {
        match p {
            Producer::Files { dir, glob } => {
                out.push(dir.as_str());
                out.extend(glob.as_deref());
            }
            Producer::Folders { dir, glob, roles } => {
                out.push(dir.as_str());
                out.extend(glob.as_deref());
                out.extend(roles.iter().map(|r| r.glob.as_str()));
            }
            Producer::Tuples { path } => out.push(path.as_str()),
            // A list literal's elements are interpolated too — `expand_producer`
            // substitutes each one — so a reference written there is as real as
            // one in a path.
            Producer::List(items) => {
                for item in items {
                    match item {
                        Element::Scalar(v) => out.push(v.as_str()),
                        Element::Tuple(parts) => out.extend(parts.iter().map(String::as_str)),
                    }
                }
            }
            Producer::Zip(ps) | Producer::Concat(ps) => {
                for p in ps {
                    producer(p, out);
                }
            }
            // A named list is checked where it is declared.
            Producer::Named(_) => {}
        }
    }
    match node {
        FlowNode::ForEach { producer: p, .. } => {
            let mut out = Vec::new();
            producer(p, &mut out);
            out
        }
        FlowNode::ListDecl { producer: p, .. } => {
            let mut out = Vec::new();
            producer(p, &mut out);
            out
        }
        FlowNode::Assign { value, .. } => vec![value.as_str()],
        FlowNode::Request { using: u, .. } => using(u),
        FlowNode::Cleanup { using: u, .. } => using(u),
        FlowNode::Report(ReportStmt::Request { using: u, .. }) => using(u),
        FlowNode::Report(ReportStmt::Computed { template, .. }) => vec![template.as_str()],
        // A `FILE(…)` snapshot path is resolved like a producer path, against
        // the same dotted-capable map, so it is an interpolation site like any
        // other. The role *names* beside it are checked by `check_env_refs`.
        FlowNode::ForEnvs { clause, .. } => match clause {
            EnvClause::Plain(_) => vec![],
            EnvClause::Roles {
                baseline,
                comparisons,
                ..
            } => baseline
                .iter()
                .chain(comparisons)
                .filter_map(|r| match r {
                    RoleRef::File(p) => Some(p.as_str()),
                    RoleRef::Env(_) => None,
                })
                .collect(),
        },
        _ => vec![],
    }
}

/// Catch a step-qualified name written in a *request's own* Hurl, where it
/// cannot work: PaperTrail resolves `{{step.var}}` in its own source before the
/// request is built, and never hands a dotted name to Hurl — whose expression
/// grammar has no dotted path, so the placeholder is left verbatim and the run
/// fails on an undefined variable with no hint as to why.
///
/// Only reported when the prefix names a step in scope. A dotted `.vars` key is
/// legal (environment keys are not restricted to identifiers), so the mere
/// presence of a dot proves nothing; a prefix that matches a step the author
/// can see is what makes the intent unambiguous.
fn check_hurl_side_qualified(
    node: &FlowNode,
    ctx: &Context,
    path: &[HashMap<String, StepInfo>],
    diags: &mut Vec<Diagnostic>,
) {
    let Some(use_) = step_use(node) else { return };
    let Some(entry) = resolve_entry_qualified(use_.request, ctx) else {
        return;
    };
    let mut bad: Vec<String> = crate::request::entry_referenced_keys(entry)
        .into_iter()
        .filter(|k| {
            k.split_once('.')
                .is_some_and(|(step, _)| path.iter().rev().any(|f| f.contains_key(step)))
        })
        .collect();
    bad.sort();
    for key in bad {
        diags.push(Diagnostic::error(fill(
            ctx.strings.diag_step_ref_in_hurl,
            &[use_.request, &key],
        )));
    }
}

/// Check every `{{step.var}}` written on `node` against the steps visible at
/// this point in the walk.
///
/// A dotted placeholder is unambiguously a step reference: PaperTrail variable
/// names are identifiers, so a `.` can only be the qualifier. Both halves are
/// checked — the step has to be one that has already run in an enclosing scope,
/// and it has to be a step whose request declares that capture — because the
/// failure this feature exists to prevent is a value silently resolving to the
/// wrong producer's copy.
fn check_qualified_refs(
    node: &FlowNode,
    ctx: &Context,
    path: &[HashMap<String, StepInfo>],
    own: Option<&str>,
    diags: &mut Vec<Diagnostic>,
) {
    let s = ctx.strings;
    for text in interpolated_source(node) {
        for key in crate::environment::referenced_keys(text) {
            let Some((step, var)) = key.split_once('.') else {
                continue;
            };
            // A step's own captures don't exist until it has run. Outside a
            // region that falls out of the walk order; inside one the names are
            // registered up front, so it has to be said explicitly.
            if own == Some(step) {
                diags.push(Diagnostic::error(fill(
                    s.diag_step_ref_unknown,
                    &[&key, step],
                )));
                continue;
            }
            let Some((depth, info)) = path
                .iter()
                .enumerate()
                .rev()
                .find_map(|(i, f)| f.get(step).map(|info| (i, info)))
            else {
                diags.push(Diagnostic::error(fill(
                    s.diag_step_ref_unknown,
                    &[&key, step],
                )));
                continue;
            };
            // Reading a capture is a dependency as surely as naming one, so
            // the rules that govern `DEPENDS` on a cleanup govern this too —
            // otherwise the same mistake written as a value slips through,
            // makes no edge at run time, and puts the literal `{{…}}` on the
            // wire without a word said.
            if info.is_cleanup {
                if !matches!(node, FlowNode::Cleanup { .. }) {
                    diags.push(Diagnostic::error(fill(
                        s.diag_step_ref_cleanup,
                        &[&key, step],
                    )));
                    continue;
                }
                // An enclosing block unwinds after this one, so a cleanup out
                // there cannot have run by the time this value is needed.
                if depth + 1 < path.len() {
                    let here = own.unwrap_or(step);
                    diags.push(Diagnostic::error(fill(
                        s.diag_cleanup_depends_outer,
                        &[here, step, step],
                    )));
                    continue;
                }
            }
            // Unbound collection: the request's captures aren't knowable, so
            // the second half of the check is skipped rather than guessed at.
            if ctx.request_entries.is_none() {
                continue;
            }
            let Some(entry) = resolve_entry_qualified(&info.request, ctx) else {
                continue; // unresolvable request — already reported
            };
            let known = entry
                .captures
                .iter()
                .chain(entry.generators.iter())
                .any(|(n, _)| n == var);
            if !known {
                diags.push(Diagnostic::error(fill(
                    s.diag_step_ref_no_capture,
                    &[step, &info.request, var],
                )));
            }
        }
    }
}

/// Validate one step's name and record it in the innermost frame.
fn register_step(
    use_: &StepUse<'_>,
    ctx: &Context,
    path: &mut [HashMap<String, StepInfo>],
    diags: &mut Vec<Diagnostic>,
) {
    let s = ctx.strings;
    let name = match use_.alias {
        Some(a) => {
            if !super::parser::is_ident(a) {
                diags.push(Diagnostic::error(fill(s.diag_step_name_invalid, &[a])));
                return;
            }
            a
        }
        None => {
            let leaf = use_.request.rsplit('/').next().unwrap_or(use_.request);
            if !super::parser::is_ident(leaf) {
                diags.push(Diagnostic::error(fill(
                    s.diag_step_name_not_identifier,
                    &[use_.request],
                )));
                return;
            }
            leaf
        }
    };
    // `written` records how the *existing* name got there, so the message
    // names the mistake actually made.
    if let Some(prev) = path.iter().find_map(|f| f.get(name)) {
        let msg = if prev.written || use_.alias.is_some() {
            fill(s.diag_step_name_duplicate, &[name, "2"])
        } else {
            fill(s.diag_step_name_ambiguous, &[use_.request, "2"])
        };
        diags.push(Diagnostic::error(msg));
    } else {
        path.last_mut().unwrap().insert(
            name.to_string(),
            StepInfo {
                written: use_.alias.is_some(),
                request: use_.request.to_string(),
                is_cleanup: use_.is_cleanup,
            },
        );
    }
}

fn check_request_name(name: &str, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    if let Some((helper, rest)) = split_helper(name, ctx) {
        let titles: Vec<String> = helper.entries.iter().map(|e| e.title.clone()).collect();
        check_name_in(rest, &titles, name, ctx, diags);
        return;
    }
    let Some(titles) = ctx.request_titles else {
        return;
    };
    check_name_in(name, titles, name, ctx, diags);
}

/// The shared exact-title → unique-leaf → error ladder. `shown` is the name as
/// the user wrote it (alias included), so a diagnostic quotes their own text.
fn check_name_in(
    name: &str,
    titles: &[String],
    shown: &str,
    ctx: &Context,
    diags: &mut Vec<Diagnostic>,
) {
    let exact = titles.iter().filter(|t| t.as_str() == name).count();
    if exact == 1 {
        return;
    }
    if exact > 1 {
        diags.push(Diagnostic::error(fill(
            ctx.strings.diag_request_ambiguous_title,
            &[shown, &exact.to_string()],
        )));
        return;
    }
    // No exact full-title match: try a unique leaf (last '/'-segment) match.
    let leaves: Vec<&String> = titles
        .iter()
        .filter(|t| t.rsplit('/').next() == Some(name))
        .collect();
    match leaves.len() {
        1 => {}
        0 => diags.push(Diagnostic::error(fill(
            ctx.strings.diag_request_not_found,
            &[shown],
        ))),
        n => diags.push(Diagnostic::error(fill(
            ctx.strings.diag_request_ambiguous_leaf,
            &[shown, &n.to_string()],
        ))),
    }
}

fn check_env_clause(clause: &EnvClause, ctx: &Context, diags: &mut Vec<Diagnostic>) {
    let names: Vec<&String> = match clause {
        EnvClause::Plain(names) => {
            if names.is_empty() {
                diags.push(Diagnostic::error(ctx.strings.diag_envs_empty));
            }
            names.iter().collect()
        }
        EnvClause::Roles {
            baseline,
            comparisons,
            ..
        } => {
            if baseline.len() > 1 {
                diags.push(Diagnostic::error(ctx.strings.diag_baseline_multiple));
            }
            if comparisons.is_empty() {
                diags.push(Diagnostic::error(ctx.strings.diag_comparison_missing));
            }
            // A `FILE(…)` snapshot stands in for a live run of its role, so a
            // path that isn't there means the role produces nothing — which
            // surfaces at run time only as an unmatched comparison, long after
            // the run has been paid for. Warn up front instead, exactly as the
            // `# baseline:` directive does, and for the same reason: it is only
            // a non-fatal error at run time, and the check needs the report to
            // be anchored (`ctx.root`) before a relative path means anything.
            if let Some(root) = ctx.root {
                for rel in baseline
                    .iter()
                    .chain(comparisons.iter())
                    .filter_map(|r| match r {
                        RoleRef::File(p) => Some(p),
                        RoleRef::Env(_) => None,
                    })
                {
                    let path = super::producers::resolve_path(Some(root), rel);
                    if !path.exists() {
                        diags.push(Diagnostic::warning(fill(
                            ctx.strings.diag_baseline_missing,
                            &[rel, &path.display().to_string()],
                        )));
                    }
                }
            }
            // Only live env-name refs are checked against the loaded set; a
            // `FILE(…)` snapshot is a path, not an environment.
            baseline
                .iter()
                .chain(comparisons.iter())
                .filter_map(|r| match r {
                    RoleRef::Env(n) => Some(n),
                    RoleRef::File(_) => None,
                })
                .collect()
        }
    };
    if let Some(loaded) = ctx.env_names {
        for n in names {
            // A name written through a parameter isn't an environment name yet
            // — `check_env_refs` judges those against what the parameter can
            // actually become.
            if n.contains("{{") {
                continue;
            }
            if !loaded.iter().any(|e| e == n) {
                diags.push(Diagnostic::error(fill(
                    ctx.strings.diag_environment_not_loaded,
                    &[n],
                )));
            }
        }
    }
}

/// The static element arity of a producer, if knowable without touching the
/// filesystem. `None` = runtime-determined (e.g. `TUPLES FROM` a CSV).
fn producer_arity(p: &Producer, scopes: &[HashMap<String, Producer>]) -> Option<usize> {
    match p {
        // A folder path (roles are accessed by name, not destructured).
        Producer::Files { .. } | Producer::Folders { .. } => Some(1),
        Producer::Zip(ps) => Some(ps.len()),
        Producer::Concat(ps) => {
            // CONCAT preserves arity: it appends items, it doesn't widen them.
            // The whole is knowable only when every input's arity is known and
            // they all agree (a disagreement is reported by check_producer).
            let arities: Vec<usize> = ps
                .iter()
                .filter_map(|p| producer_arity(p, scopes))
                .collect();
            if arities.len() != ps.len() {
                return None;
            }
            match arities.first() {
                Some(&first) if arities.iter().all(|&a| a == first) => Some(first),
                _ => None,
            }
        }
        Producer::Tuples { .. } => None,
        Producer::List(elems) => {
            let arities: Vec<usize> = elems
                .iter()
                .map(|e| match e {
                    super::flow::Element::Scalar(_) => 1,
                    super::flow::Element::Tuple(items) => items.len(),
                })
                .collect();
            match arities.first() {
                None => Some(1),
                Some(&first) if arities.iter().all(|&a| a == first) => Some(first),
                // Inconsistent — reported by check_arity via the mismatch below.
                _ => None,
            }
        }
        Producer::Named(name) => scopes
            .iter()
            .rev()
            .find_map(|s| s.get(name))
            .and_then(|inner| producer_arity(inner, scopes)),
    }
}

fn check_arity(
    pattern: &Pattern,
    producer: &Producer,
    scopes: &[HashMap<String, Producer>],
    s: &Strings,
    diags: &mut Vec<Diagnostic>,
) {
    let Some(arity) = producer_arity(producer, scopes) else {
        return; // Runtime-determined (or inconsistent — flagged by check_producer).
    };
    let binders = pattern.binders.len();
    if pattern.rest {
        if binders > arity {
            diags.push(Diagnostic::error(fill(
                s.diag_pattern_before_rest,
                &[&binders.to_string(), &arity.to_string()],
            )));
        }
    } else if binders != arity {
        diags.push(Diagnostic::error(fill(
            s.diag_pattern_arity,
            &[&binders.to_string(), &arity.to_string()],
        )));
    }
}

fn check_producer(
    producer: &Producer,
    ctx: &Context,
    scopes: &[HashMap<String, Producer>],
    diags: &mut Vec<Diagnostic>,
) {
    if let Producer::Named(name) = producer
        && !scopes.iter().rev().any(|s| s.contains_key(name))
    {
        diags.push(Diagnostic::error(fill(
            ctx.strings.diag_unknown_list,
            &[name, name],
        )));
    }
    // Inconsistent list-literal arity (a mix of scalars/tuples of different
    // sizes) is caught wherever the literal appears — a `LIST` declaration or an
    // inline `FOR … IN [ … ]` — so it surfaces at its definition site.
    if let Producer::List(elems) = producer {
        let arities: Vec<usize> = elems
            .iter()
            .map(|e| match e {
                super::flow::Element::Scalar(_) => 1,
                super::flow::Element::Tuple(items) => items.len(),
            })
            .collect();
        if let Some(&first) = arities.first()
            && !arities.iter().all(|&a| a == first)
        {
            diags.push(Diagnostic::error(ctx.strings.diag_list_arity));
        }
    }
    if let Producer::Zip(ps) = producer {
        for p in ps {
            check_producer(p, ctx, scopes, diags);
        }
    }
    if let Producer::Concat(ps) = producer {
        for p in ps {
            check_producer(p, ctx, scopes, diags);
        }
        // All inputs must yield items of the same arity, else the loop pattern
        // can't destructure them uniformly. Only flag when statically knowable.
        let arities: Vec<usize> = ps
            .iter()
            .filter_map(|p| producer_arity(p, scopes))
            .collect();
        if let Some(&first) = arities.first()
            && arities.len() == ps.len()
            && !arities.iter().all(|&a| a == first)
        {
            diags.push(Diagnostic::error(ctx.strings.diag_concat_arity));
        }
    }
}

// ---------------------------------------------------------------------------
// Variable-availability analysis
// ---------------------------------------------------------------------------

/// Build the initial set of variable names available before the first
/// statement executes: the base environment's keys plus the engine's
/// built-in `PRELUDE_*` names (which always have defaults, so a request
/// that references one is never provably undefined).
fn initial_defined_vars(ctx: &Context) -> HashSet<String> {
    let mut defined = HashSet::new();
    if let Some(names) = ctx.base_var_names {
        defined.extend(names.iter().cloned());
    }
    // Engine defaults — any flow can reference these without an explicit
    // assignment and they will always resolve.
    for name in [
        "PRELUDE_NO_MATCH_MARKER",
        "PRELUDE_RESPONSE_FORMAT",
        "PRELUDE_MAX_PARALLEL",
    ] {
        defined.insert(name.to_string());
    }
    defined
}

/// Resolve a request name against the bound entries — same leaf/exact logic
/// as [`check_request_name`] — returning the first matching entry, or `None`
/// for an ambiguous/missing name (those cases are already reported by the
/// structural walk; here we silently skip to avoid double-reporting).
/// The `[Reports]` field names a request can declare, alias-aware: exact full
/// title, then a unique leaf match, within the collection the name addresses.
fn declared_report_fields(name: &str, ctx: &Context) -> Option<Vec<String>> {
    if let Some((helper, rest)) = split_helper(name, ctx) {
        return resolve_entry_by_name(&helper.entries, rest)
            .map(|e| e.reports.iter().map(|(n, _)| n.clone()).collect());
    }
    let entries = ctx.request_fields?;
    let by_exact = entries.iter().find(|(t, _)| t == name);
    by_exact
        .or_else(|| {
            let mut leaves = entries
                .iter()
                .filter(|(t, _)| t.rsplit('/').next() == Some(name));
            match (leaves.next(), leaves.next()) {
                (Some(hit), None) => Some(hit),
                _ => None,
            }
        })
        .map(|(_, f)| f.clone())
}

/// The entry a name addresses, alias-aware — the validation-side twin of
/// [`super::run::resolve_qualified`].
fn resolve_entry_qualified<'a>(
    name: &'a str,
    ctx: &'a Context,
) -> Option<&'a crate::hurl::HurlEntry> {
    if let Some((helper, rest)) = split_helper(name, ctx) {
        return resolve_entry_by_name(&helper.entries, rest);
    }
    resolve_entry_by_name(ctx.request_entries?, name)
}

fn resolve_entry_by_name<'a>(
    entries: &'a [crate::hurl::HurlEntry],
    name: &str,
) -> Option<&'a crate::hurl::HurlEntry> {
    let exact: Vec<_> = entries.iter().filter(|e| e.title == name).collect();
    if exact.len() == 1 {
        return Some(exact[0]);
    }
    if exact.len() > 1 {
        return None; // ambiguous
    }
    let leaves: Vec<_> = entries
        .iter()
        .filter(|e| e.title.rsplit('/').next() == Some(name))
        .collect();
    if leaves.len() == 1 {
        Some(leaves[0])
    } else {
        None
    }
}

/// The named fields a producer binds by name (not position) — specifically
/// the role names in a `FOLDERS … WITH role="glob", …` producer. These bind
/// directly into the loop scope like `FOR (A, B) IN …` would bind `A` and `B`,
/// so they must be treated as defined inside the loop body.
fn producer_static_named_fields(producer: &Producer) -> Vec<String> {
    match producer {
        Producer::Folders { roles, .. } => roles.iter().map(|r| r.name.clone()).collect(),
        // ZIP/CONCAT: union the named fields from all sub-producers.
        Producer::Zip(ps) | Producer::Concat(ps) => {
            ps.iter().flat_map(producer_static_named_fields).collect()
        }
        _ => Vec::new(),
    }
}

/// Emit a warning for each `{{VAR}}` that `name`'s request references but
/// that isn't in `defined` at the call site. Silently skips unresolvable
/// request names (already reported by the structural walk).
fn warn_if_vars_undefined(
    name: &str,
    ctx: &Context,
    defined: &HashSet<String>,
    diags: &mut Vec<Diagnostic>,
) {
    if ctx.request_entries.is_none() {
        return;
    }
    let Some(entry) = resolve_entry_qualified(name, ctx) else {
        return; // unresolvable — structural check already warned
    };
    let refs = crate::request::entry_referenced_keys(entry);
    // Sorted, because `entry_referenced_keys` hands back a `HashSet` and its
    // iteration order differs from one instance to the next. Emitting warnings
    // straight out of it made the validation panel's contents reshuffle every
    // time it was rebuilt, so a request with several unset variables flickered.
    // Alphabetical is also simply the more useful order to read them in.
    let mut refs: Vec<&String> = refs.iter().collect();
    refs.sort();
    // A name the request declares in its own `[Options]` can never be unset:
    // the declared value is a default, and the whole point of a request
    // parameter is that the request still works when nobody binds it. Warning
    // about those made a properly parameterised collection noisier than an
    // unparameterised one, which is exactly backwards.
    let mut declared: HashSet<String> = entry
        .variable_defaults()
        .into_iter()
        .map(|(n, _)| n)
        .collect();
    // A `# [Gen]` row defines its name for the request it is on. The value
    // genuinely does not exist until the request is sent, which is exactly why
    // warning about it is wrong: the run computes it, and being told a
    // signature "may be undefined" on every request that signs one teaches the
    // user to stop reading the panel.
    declared.extend(entry.generators.iter().map(|(n, _)| n.clone()));
    for var in refs {
        if !defined.contains(var.as_str()) && !declared.contains(var.as_str()) {
            diags.push(Diagnostic::warning(fill(
                ctx.strings.diag_var_maybe_undefined,
                &[name, &format!("{{{{{var}}}}}")],
            )));
        }
    }
}

/// Thread the names a successfully-resolved request defines — its captures and
/// its computed values — into `defined`, so that subsequent requests in the
/// same block can use them. A `[Gen]` row is bound for its own request onwards,
/// the same way a capture is, so a later request reading `{{transaction_id}}`
/// is reading something that exists.
fn add_entry_captures(name: &str, ctx: &Context, defined: &mut HashSet<String>) {
    if ctx.request_entries.is_none() {
        return;
    }
    let Some(entry) = resolve_entry_qualified(name, ctx) else {
        return;
    };
    for (cap_name, _) in &entry.captures {
        defined.insert(cap_name.clone());
    }
    for (gen_name, _) in &entry.generators {
        defined.insert(gen_name.clone());
    }
}

/// Walk `nodes` in execution order, maintaining `defined` (the set of
/// variable names provably in scope), and emit a warning for every `{{VAR}}`
/// in a request that isn't covered by any in-scope source.
///
/// Conservative design: when a scope source can't be statically enumerated
/// (e.g. `TUPLES FROM` column names, or a `FOR … IN ENVS` body when the
/// loaded env variable names aren't known), we skip that scope entirely and
/// produce no warnings — under-warning is far better than a false positive.
fn check_var_availability(
    nodes: &[FlowNode],
    ctx: &Context,
    defined: &mut HashSet<String>,
    diags: &mut Vec<Diagnostic>,
) {
    for node in nodes {
        match node {
            // A comment defines nothing and uses nothing.
            FlowNode::Comment(_) => {}
            // An assignment defines the key for all subsequent nodes.
            FlowNode::Assign { key, .. } => {
                defined.insert(key.clone());
            }
            // A parameter always has a value by the time anything runs —
            // its default, or whatever the run settings supplied instead.
            FlowNode::Param(p) => {
                defined.insert(p.name.clone());
            }
            FlowNode::ListDecl { .. } => {}
            // A bare REQUEST (no report output) — check its vars, then thread
            // its captures forward.
            FlowNode::Request { name, .. } => {
                warn_if_vars_undefined(name, ctx, defined, diags);
                add_entry_captures(name, ctx, defined);
            }
            // A cleanup is checked where it is written even though it runs at
            // the end of its block, so a variable defined *after* it can warn
            // when it would in fact be available. That is the conservative
            // direction for a warning, and a teardown written above the setup
            // it tears down is worth a second look anyway. Its own captures are
            // not threaded forward: nothing runs after a teardown to read them.
            FlowNode::Cleanup { name, .. } => {
                warn_if_vars_undefined(name, ctx, defined, diags);
            }
            // A REPORT statement — only the REQUEST form sends HTTP.
            FlowNode::Report(stmt) => {
                if let ReportStmt::Request { name, .. } = stmt {
                    warn_if_vars_undefined(name, ctx, defined, diags);
                    add_entry_captures(name, ctx, defined);
                }
            }
            // A FOR loop over a producer: pattern binders and any named fields
            // (FOLDERS roles, TUPLES headers when statically unknown are left
            // out — they're runtime-determined, so we err on the side of not
            // warning). The loop body runs with a snapshot of `defined` plus
            // those new names; changes inside the body don't leak outward.
            FlowNode::ForEach {
                pattern,
                producer,
                body,
                ..
            } => {
                let mut inner = defined.clone();
                for binder_name in pattern.named() {
                    inner.insert(binder_name.to_string());
                }
                // FOLDERS roles are known statically and bind by name.
                for fname in producer_static_named_fields(producer) {
                    inner.insert(fname);
                }
                // TUPLES FROM / ZIP / CONCAT may also yield named fields at
                // runtime (CSV headers, etc.) — we can't enumerate them here,
                // so we don't add them. This means we may miss some true
                // negatives inside TUPLES loops, but we'll never false-positive.
                check_var_availability(body, ctx, &mut inner, diags);
            }
            // A FOR … IN ENVS loop: the loop variable is in scope, and each
            // iteration's environment also makes its variables available.
            // We add the union of ALL loaded env vars so we don't false-warn
            // inside the body regardless of which env is active. If the loaded
            // env variable names are unknown (`all_env_var_names` is None) we
            // skip the body entirely to stay conservative.
            FlowNode::ForEnvs {
                var, body, clause, ..
            } => {
                // The clause itself is read in *this* scope, not the body's:
                // `BASELINE("prod-{{region}}")` is resolved afresh on every
                // visit against whatever is bound where the loop is written.
                // Anything in scope will do — a parameter, a loop variable, an
                // assignment, a capture from a step above.
                warn_if_env_names_undefined(clause, ctx, defined, diags);
                let mut inner = defined.clone();
                inner.insert(var.clone());
                if let Some(env_vars) = ctx.all_env_var_names {
                    inner.extend(env_vars.iter().cloned());
                    check_var_availability(body, ctx, &mut inner, diags);
                }
                // If all_env_var_names is None, skip the body — we can't know
                // what the environment will provide, so no warnings here.
            }
            // A region reorders its body, so "written earlier" no longer means
            // "runs earlier": a step may legitimately read a capture from a
            // step written below it. Every capture the region produces is
            // therefore made available to all of it before the walk, and the
            // question of whether a particular step may see a particular
            // capture is left to the graph itself, which alone knows ancestry.
            //
            // They stay in `defined` afterwards: the region's closing barrier
            // means everything in it has run by the time anything after it
            // does.
            FlowNode::Graph { body, .. } => {
                for node in body {
                    if let Some(name) = step_request_name(node) {
                        add_entry_captures(name, ctx, defined);
                    }
                }
                check_var_availability(body, ctx, defined, diags);
            }
        }
    }
}

/// Warn for every `{{VAR}}` in an `ENVS` clause's environment names that
/// nothing in scope at the clause can answer.
///
/// Conservative in the same way as `warn_if_vars_undefined`: when the loaded
/// environments' variable names are unknown the check is skipped entirely,
/// because an environment may itself supply the name and a false warning about
/// a working report is worse than a missed one. A `FILE(…)` role is a path
/// rather than an environment and is left to the snapshot checks.
fn warn_if_env_names_undefined(
    clause: &EnvClause,
    ctx: &Context,
    defined: &HashSet<String>,
    diags: &mut Vec<Diagnostic>,
) {
    let Some(env_vars) = ctx.all_env_var_names else {
        return;
    };
    let names: Vec<&String> = match clause {
        EnvClause::Plain(names) => names.iter().collect(),
        EnvClause::Roles {
            baseline,
            comparisons,
            ..
        } => baseline
            .iter()
            .chain(comparisons.iter())
            .filter_map(|r| match r {
                RoleRef::Env(n) => Some(n),
                RoleRef::File(_) => None,
            })
            .collect(),
    };
    for name in names {
        let mut keys: Vec<String> = crate::environment::referenced_keys(name)
            .into_iter()
            .collect();
        // Sorted for the same reason `warn_if_vars_undefined` sorts: the panel
        // is rebuilt often and a set's order is not stable between builds.
        keys.sort();
        for key in keys {
            if !defined.contains(&key) && !env_vars.iter().any(|v| *v == key) {
                diags.push(Diagnostic::warning(fill(
                    ctx.strings.diag_env_ref_not_in_scope,
                    &[&key, name],
                )));
            }
        }
    }
}

/// The request a step node sends, for the node kinds that send one.
fn step_request_name(node: &FlowNode) -> Option<&str> {
    match node {
        FlowNode::Request { name, .. } => Some(name),
        FlowNode::Report(ReportStmt::Request { name, .. }) => Some(name),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report::parser::parse_flow;

    /// Validate a flow parsed from source under an optional collection/env
    /// context. Returns all diagnostics.
    fn diags_for(src: &str, titles: Option<&[String]>, envs: Option<&[String]>) -> Vec<Diagnostic> {
        let flow = parse_flow(src).expect("test source should parse");
        let ctx = Context {
            request_titles: titles,
            env_names: envs,
            ..Default::default()
        };
        validate(&flow, &ctx)
    }

    /// Validate a flow against real entries — needed for anything that checks a
    /// request's own shape (its declared parameters, its form fields).
    fn diags_with_entries(src: &str, entries: &[crate::hurl::HurlEntry]) -> Vec<Diagnostic> {
        let flow = parse_flow(src).expect("test source should parse");
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let ctx = Context {
            request_titles: Some(&titles),
            request_entries: Some(entries),
            ..Default::default()
        };
        validate(&flow, &ctx)
    }

    /// Diagnostics for a flow with a `REQUESTS` section, with the title list
    /// assembled the way [`super::super::context::bound_entries`] assembles it
    /// at run time: the external collection's entries, then the embedded ones.
    /// Building it any other way would test a context that never occurs.
    fn diags_embedded(src: &str, external: &[crate::hurl::HurlEntry]) -> Vec<Diagnostic> {
        let flow = parse_flow(src).expect("test source should parse");
        let mut entries = external.to_vec();
        entries.extend(flow.embedded_entries());
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let ctx = Context {
            request_titles: Some(&titles),
            request_entries: Some(&entries),
            ..Default::default()
        };
        validate(&flow, &ctx)
    }

    #[test]
    fn a_flow_that_embeds_its_requests_needs_no_collection() {
        // The single-file monitor. The section's presence is the declaration,
        // so demanding a `# collection:` as well would make it impossible.
        let diags = diags_embedded(
            "# name: solo\n\nREPORT REQUEST ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n",
            &[],
        );
        let errs: Vec<&str> = diags
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message.as_str())
            .collect();
        assert!(errs.is_empty(), "{errs:?}");
    }

    #[test]
    fn a_helper_qualified_call_does_not_count_as_using_an_embedded_request() {
        // A helper alias resolves before any title, so `helper/ping` runs the
        // helper's request and says nothing about the embedded `ping` — which
        // is dead text in the one file that was supposed to be self-contained,
        // and has to still be reported as such.
        let flow = parse_flow(
            "# collection: c\n\nREPORT REQUEST helper/ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n",
        )
        .expect("test source should parse");
        let entries = flow.embedded_entries();
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let helpers = [crate::report::run::HelperCollection {
            alias: "helper".into(),
            entries: vec![capturing_entry("ping", &[])],
        }];
        let ctx = Context {
            request_titles: Some(&titles),
            request_entries: Some(&entries),
            helpers: &helpers,
            ..Default::default()
        };
        let diags = validate(&flow, &ctx);
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("ping")),
            "{diags:?}"
        );
    }

    #[test]
    fn an_embedded_name_may_not_collide_with_an_external_one() {
        let diags = diags_embedded(
            "# collection: c\n\nREPORT REQUEST ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n",
            &[capturing_entry("ping", &[])],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("ping")),
            "a reference would mean either of two requests: {diags:?}"
        );
    }

    #[test]
    fn an_embedded_request_nothing_calls_is_a_warning_not_an_error() {
        let diags = diags_embedded(
            "# name: solo\n\nREPORT REQUEST ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n\n# spare\nGET https://x/spare\n",
            &[],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("spare")),
            "{diags:?}"
        );
        assert!(
            !diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("spare")),
            "unused is normal enough not to fail the file: {diags:?}"
        );
    }

    #[test]
    fn a_requests_section_that_declares_nothing_is_an_error() {
        // The keyword bought nothing, which is nearly always a malformed
        // section rather than a deliberately empty one.
        let diags = diags_embedded("# name: solo\n\nREQUESTS\nnot hurl at all\n", &[]);
        assert!(
            diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
    }

    #[test]
    fn a_malformed_section_is_reported_as_malformed_not_as_a_missing_collection() {
        // The declaration is the keyword, not the requests it yielded. Telling
        // an author who wrote a `REQUESTS` section that they have no collection
        // buries the one thing they need to know: why their Hurl didn't parse.
        let diags = diags_embedded("# name: solo\n\nREQUESTS\nnot hurl at all\n", &[]);
        let errs: Vec<&str> = diags
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message.as_str())
            .collect();
        assert!(
            errs.iter().any(|m| m.contains("REQUESTS")),
            "the malformed section must be named: {errs:?}"
        );
        assert!(
            !errs
                .iter()
                .any(|m| *m == Strings::english().diag_collection_unset),
            "and it must not also be accused of having no collection: {errs:?}"
        );
    }

    #[test]
    fn a_hurl_error_in_the_section_counts_lines_from_the_file() {
        // The section is a slice of a `.trail`, and the `.trail` is the only
        // file the reader has open — a line number counted from the section
        // sends them to the wrong place in it.
        let diags = diags_embedded(
            "# name: solo\n# out: csv\n\nREQUESTS\nnot hurl at all\n",
            &[],
        );
        let msg = diags
            .iter()
            .find(|d| d.severity == Severity::Error)
            .map(|d| d.message.clone())
            .unwrap_or_default();
        assert!(
            msg.contains("line 5"),
            "the bad line is file line 5, not section line 1: {msg}"
        );
    }

    #[test]
    fn a_qualified_call_that_resolves_elsewhere_does_not_excuse_an_embedded_request() {
        // `folder/ping` names an external request exactly, so it is not a use
        // of the embedded `ping`, which never runs and should be reported.
        let diags = diags_embedded(
            "# collection: c\n\nREPORT REQUEST folder/ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n",
            &[capturing_entry("folder/ping", &[])],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("ping")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_bare_call_still_reaches_an_embedded_request_by_its_leaf_name() {
        // The other half of the same rule: with nothing declaring the exact
        // path, a leaf match is how the call resolves, so it is a use.
        let diags = diags_embedded(
            "# name: solo\n\nREPORT REQUEST folder/ping\n\nREQUESTS\n\n# ping\nGET https://x/ping\n",
            &[],
        );
        assert!(
            !diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("never called")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_is_a_step_and_may_not_share_another_steps_name() {
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST a AS same\nCLEANUP b AS same\n",
            &[capturing_entry("a", &[]), capturing_entry("b", &[])],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("same")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_may_name_a_step_written_below_it() {
        // It runs at the end of its block, so the ordinary shape — a teardown
        // written beside the thing it tears down, above the rest of the setup —
        // must not be rejected.
        let diags = diags_with_entries(
            "# collection: c\n\nCLEANUP teardown USING(url = \"{{create.sid}}\")\nREQUEST create\n",
            &[
                capturing_entry("create", &["sid"]),
                capturing_entry("teardown", &[]),
            ],
        );
        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_depending_on_nothing_that_exists_is_refused() {
        // Unchecked, the missing name reads as "it didn't succeed" and the
        // teardown is quietly skipped — a typo that leaves things behind and
        // says nothing about it.
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST a\nCLEANUP teardown DEPENDS ghost\n",
            &[capturing_entry("a", &[]), capturing_entry("teardown", &[])],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("ghost")),
            "{diags:?}"
        );
    }

    #[test]
    fn two_cleanups_that_depend_on_each_other_are_refused() {
        // A ring has no honest execution: each member waits on another that has
        // not run, so each in turn reads its prerequisite as unsuccessful and
        // skips itself. Every resource the ring covers leaks, silently — and
        // ordering cannot break the tie, so it has to be refused up front.
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST setup\n\
             CLEANUP purge_a DEPENDS setup, purge_b\n\
             CLEANUP purge_b DEPENDS setup, purge_a\n",
            &[
                capturing_entry("setup", &[]),
                capturing_entry("purge_a", &[]),
                capturing_entry("purge_b", &[]),
            ],
        );
        assert!(
            diags.iter().any(|d| d.severity == Severity::Error
                && d.message.contains("purge_a")
                && d.message.contains("purge_b")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_may_not_depend_on_one_in_an_enclosing_block() {
        // The enclosing block unwinds after the inner one, so the outer cleanup
        // has not run when the inner one is asked whether it may. Accepted, it
        // was skipped on every iteration of every run, saying only "didn't
        // succeed" — the quietly-skipped teardown this check exists to prevent.
        let diags = diags_with_entries(
            "# collection: c\n\nCLEANUP outer\n\
             FOR X IN [\"a\"]\n    REQUEST create\n    CLEANUP inner DEPENDS outer\nEND\n",
            &[
                capturing_entry("outer", &[]),
                capturing_entry("create", &[]),
                capturing_entry("inner", &[]),
            ],
        );
        assert!(
            diags.iter().any(|d| d.severity == Severity::Error
                && d.message.contains("inner")
                && d.message.contains("outer")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_may_not_read_a_capture_from_one_in_an_enclosing_block() {
        // The same mistake written as a value instead of a clause. It made no
        // edge at run time, was not skipped, and put the literal
        // `{{outer.token}}` on the wire without a word said.
        let diags = diags_with_entries(
            "# collection: c\n\nCLEANUP outer\n\
             FOR X IN [\"a\"]\n    REQUEST create\n    CLEANUP inner USING(query.t = \"{{outer.token}}\")\nEND\n",
            &[
                capturing_entry("outer", &["token"]),
                capturing_entry("create", &[]),
                capturing_entry("inner", &[]),
            ],
        );
        assert!(
            diags.iter().any(|d| d.severity == Severity::Error
                && d.message.contains("inner")
                && d.message.contains("outer")),
            "{diags:?}"
        );
    }

    #[test]
    fn an_ordinary_step_may_not_read_a_cleanups_capture() {
        // Teardown runs after every step in its block, so the value does not
        // exist yet when the step is sent — there is no ordering that would
        // make this work, whichever way round the two are written.
        let diags = diags_with_entries(
            "# collection: c\n\nCLEANUP purge\nREQUEST use USING(query.t = \"{{purge.token}}\")\n",
            &[
                capturing_entry("purge", &["token"]),
                capturing_entry("use", &[]),
            ],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("purge.token")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_may_read_a_sibling_cleanups_capture() {
        // The boundary of the rule above: same block, and the runner orders the
        // two on exactly this reference.
        let diags = diags_with_entries(
            "# collection: c\n\nCLEANUP make\nCLEANUP purge USING(query.t = \"{{make.token}}\")\n",
            &[
                capturing_entry("make", &["token"]),
                capturing_entry("purge", &[]),
            ],
        );
        assert!(
            !diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("make")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_snapshot_path_is_checked_for_step_references_like_any_other() {
        // A FILE(…) role is resolved like a producer path, against the same
        // dotted-capable map — so it is an interpolation site, and a reference
        // to a step that does not exist has to be caught before the run.
        let diags = diags_with_entries(
            "# collection: c\n\nFOR T IN ENVS BASELINE(FILE(\"{{nosuch.sid}}.baseline\")), COMPARISON(\"eu\")\n    REPORT T AS S\nEND\n",
            &[capturing_entry("create", &["sid"])],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("nosuch")),
            "{diags:?}"
        );
    }

    #[test]
    fn a_cleanup_may_depend_on_one_in_its_own_block() {
        // The boundary: same block, same unwinding, so the ordering is real and
        // the edge is exactly what DEPENDS between cleanups is for.
        let diags = diags_with_entries(
            "# collection: c\n\nFOR X IN [\"a\"]\n    REQUEST create\n\
             CLEANUP first\n    CLEANUP second DEPENDS first\nEND\n",
            &[
                capturing_entry("create", &[]),
                capturing_entry("first", &[]),
                capturing_entry("second", &[]),
            ],
        );
        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
    }

    #[test]
    fn cleanups_in_a_chain_are_not_a_cycle() {
        // The boundary of the rule above: a chain is exactly what `DEPENDS`
        // between cleanups is for, and rejecting it would take the feature away.
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST setup\n\
             CLEANUP purge_a DEPENDS setup\n\
             CLEANUP purge_b DEPENDS purge_a\n",
            &[
                capturing_entry("setup", &[]),
                capturing_entry("purge_a", &[]),
                capturing_entry("purge_b", &[]),
            ],
        );
        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
    }

    #[test]
    fn a_qualified_name_in_a_requests_own_hurl_is_refused() {
        // PaperTrail resolves `{{step.var}}` in its own source and never hands
        // a dotted name to Hurl, which has no dotted path — so left in the
        // request it fails at run time on an undefined variable, with nothing
        // to say why.
        let mut consumer = capturing_entry("consumer", &[]);
        consumer.url = "http://x/{{login.token}}".into();
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST auth AS login\nREQUEST consumer\n",
            &[capturing_entry("auth", &["token"]), consumer],
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("login.token")),
            "{diags:?}"
        );
    }

    /// A request declaring the parameter, for the `USING` checks.
    fn upload_entry(declares: &[&str], fields: &[&str]) -> crate::hurl::HurlEntry {
        crate::hurl::HurlEntry {
            title: "upload".into(),
            method: "POST".into(),
            url: "http://x".into(),
            options: declares
                .iter()
                .map(|n| crate::hurl::KvRow::new("variable", format!("{n}=./sample.pdf")))
                .collect(),
            form_fields: fields
                .iter()
                .map(|k| crate::hurl::FormField {
                    key: (*k).to_string(),
                    enabled: true,
                    ..Default::default()
                })
                .collect(),
            ..Default::default()
        }
    }

    /// The whole point of the clause: the same flow text that works against a
    /// parameterised collection fails *loudly* against one that isn't, instead
    /// of silently sending the request's own hardcoded value.
    #[test]
    fn a_required_parameter_the_request_does_not_declare_is_an_error() {
        let src = "# collection: c\n\nREQUEST upload USING(FILE)\n";

        let ok = diags_with_entries(src, &[upload_entry(&["FILE"], &[])]);
        assert!(
            !ok.iter().any(|d| d.severity == Severity::Error),
            "declared: {ok:?}"
        );

        let bad = diags_with_entries(src, &[upload_entry(&[], &[])]);
        let msg = bad
            .iter()
            .find(|d| d.severity == Severity::Error)
            .map(|d| d.message.clone())
            .unwrap_or_default();
        assert!(
            msg.contains("does not declare a parameter 'FILE'") && msg.contains("declares: none"),
            "the error names the fix: {bad:?}"
        );
    }

    /// The nudge that moves people onto the clause: a request built to be
    /// driven, driven without saying so, is the copy-paste hazard. A warning,
    /// not an error — the flow is correct here, it just won't stay correct.
    #[test]
    fn driving_a_parameterised_request_without_using_is_a_warning() {
        let diags = diags_with_entries(
            "# collection: c\n\nREPORT REQUEST upload\n",
            &[upload_entry(&["FILE"], &[])],
        );

        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("USING")),
            "{diags:?}"
        );
    }

    /// A request that declares nothing is not nagged — the warning only fires
    /// where there is something to require.
    #[test]
    fn an_ordinary_request_is_not_nudged() {
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST upload\n",
            &[upload_entry(&[], &[])],
        );

        assert!(
            !diags.iter().any(|d| d.message.contains("USING")),
            "{diags:?}"
        );
    }

    /// A mistyped `multipart` field is caught before the run: applied, it would
    /// invent a field and send a body the request's author never designed.
    #[test]
    fn an_override_of_a_field_the_request_lacks_is_an_error() {
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST upload USING(multipart.fil = \"x\")\n",
            &[upload_entry(&[], &["file"])],
        );

        assert!(
            diags.iter().any(|d| d.severity == Severity::Error
                && d.message.contains("no multipart field 'fil'")
                && d.message.contains("it has: file")),
            "{diags:?}"
        );
    }

    /// Adding a header the request never had is normal and unremarkable, so an
    /// upserting target is never flagged.
    #[test]
    fn an_override_of_an_absent_header_is_fine() {
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST upload USING(header.X-Run = \"7\")\n",
            &[upload_entry(&[], &["file"])],
        );

        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
    }

    /// Overriding the body of a form request would produce the one shape Hurl
    /// cannot send (body + form on the same handle), so it is caught here
    /// rather than at the send.
    #[test]
    fn overriding_the_body_of_a_form_request_is_an_error() {
        let diags = diags_with_entries(
            "# collection: c\n\nREQUEST upload USING(body = \"{}\")\n",
            &[upload_entry(&[], &["file"])],
        );

        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Error
                    && d.message.contains("cannot be sent together")),
            "{diags:?}"
        );
    }

    /// The clause that motivated parameters in the first place: which two
    /// stacks to compare, chosen per run. The names are references, so the
    /// "not loaded" check has to look at what they mean rather than at what
    /// they say.
    #[test]
    fn an_environment_named_by_a_parameter_is_not_an_unloaded_environment() {
        let src = "# collection: c\nPARAM COMPARE_ENV = \"api_dev\"\nPARAM BASELINE_ENV = \"api_staging\"\n\
                   PARALLEL(2) FOR TARGET IN ENVS BASELINE(\"{{BASELINE_ENV}}\") SHOW(TimeWait), COMPARISON(\"{{COMPARE_ENV}}\")\n\
                       REPORT REQUEST r\nEND\n";
        let envs = ["api_dev".to_string(), "api_staging".to_string()];
        let msgs: Vec<String> = diags_for(src, None, Some(&envs))
            .into_iter()
            .map(|d| d.message)
            .collect();
        assert!(
            !msgs.iter().any(|m| m.contains("is not loaded")),
            "the parameters resolve to loaded environments: {msgs:?}"
        );
    }

    /// What the defaults currently mean is still checked — but only as a
    /// warning, because being changed per run is the entire point.
    #[test]
    fn a_parameter_pointing_at_an_unloaded_environment_is_only_a_warning() {
        let src = "# collection: c\nPARAM TARGET_ENV = \"gone\"\n\
                   FOR T IN ENVS \"{{TARGET_ENV}}\"\n    REPORT REQUEST r\nEND\n";
        let envs = ["here".to_string()];
        let diags = diags_for(src, None, Some(&envs));
        assert!(
            !diags
                .iter()
                .any(|d| d.severity == Severity::Error && d.message.contains("gone")),
            "not an error: {diags:?}"
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("gone")),
            "but it does say so: {diags:?}"
        );
    }

    /// An `ENVS` clause is resolved when the run reaches it, against everything
    /// then in scope — so an assignment above it names an environment perfectly
    /// well. Refusing anything but a parameter put every role target written
    /// through a loop variable out of reach, which is most of what roles are
    /// for.
    #[test]
    fn an_environment_named_by_something_in_scope_is_accepted() {
        let errs = errors_for(
            "# collection: c\nTARGET_ENV = \"staging\"\n\
             FOR T IN ENVS \"{{TARGET_ENV}}\"\n    REPORT REQUEST r\nEND\n",
        );
        assert!(
            !errs.iter().any(|e| e.contains("TARGET_ENV")),
            "an assignment binds it: {errs:?}"
        );

        let errs = errors_for(
            "# collection: c\nFOR R IN [\"eu\", \"us\"]\n    \
             FOR T IN ENVS BASELINE(\"prod-{{R}}\"), COMPARISON(\"stg-{{R}}\")\n        \
             REPORT REQUEST r\n    END\nEND\n",
        );
        assert!(errs.is_empty(), "a loop variable binds it too: {errs:?}");
    }

    /// It is still worth saying when nothing at all could answer the reference
    /// — but as a warning, and only where the scope is fully known, because an
    /// environment may supply the name itself.
    #[test]
    fn an_environment_named_by_nothing_in_scope_is_a_warning() {
        let entries = [test_entry("r", &[], &[])];
        let warns: Vec<String> = {
            let flow = parse_flow(
                "# collection: c\nFOR T IN ENVS \"{{TARGET_ENV}}\"\n    REPORT REQUEST r\nEND\n",
            )
            .expect("test source should parse");
            let titles = ["r".to_string()];
            let ctx = Context {
                request_titles: Some(&titles),
                base_var_names: Some(&[]),
                all_env_var_names: Some(&[]),
                request_entries: Some(&entries),
                ..Default::default()
            };
            validate(&flow, &ctx)
                .into_iter()
                .filter(|d| d.severity == Severity::Warning)
                .map(|d| d.message)
                .collect()
        };
        assert!(
            warns.iter().any(|w| w.contains("TARGET_ENV")),
            "says which name: {warns:?}"
        );
    }

    /// A required parameter has nothing to check against yet: what it will name
    /// is decided in the run settings, so validation stays quiet rather than
    /// guessing.
    #[test]
    fn an_environment_named_by_an_unanswered_parameter_is_left_alone() {
        let src = "# collection: c\nPARAM ENV TARGET_ENV\n\
                   FOR T IN ENVS \"{{TARGET_ENV}}\"\n    REPORT REQUEST r\nEND\n";
        let envs = ["here".to_string()];
        let diags = diags_for(src, None, Some(&envs));
        assert!(
            !diags.iter().any(|d| d.message.contains("TARGET_ENV")),
            "nothing to say yet: {diags:?}"
        );
    }

    fn errors_for(src: &str) -> Vec<String> {
        diags_for(src, None, None)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    /// A parameter is only useful if it can be offered *before* the run, which
    /// means it has to be findable without executing the flow. One written
    /// after the first real step — or buried in a loop, where it would run
    /// many times — is an ordinary assignment wearing a parameter's clothes.
    #[test]
    fn a_parameter_past_the_prelude_is_refused() {
        let ok = errors_for(
            "# collection: c\n# a comment\nPRELUDE_MAX_PARALLEL=2\nPARAM ENV TARGET = \"s\"\nREPORT REQUEST r\n",
        );
        assert!(ok.is_empty(), "prelude parameter should be fine: {ok:?}");

        let late = errors_for("# collection: c\nREPORT REQUEST r\nPARAM ENV TARGET = \"s\"\n");
        assert_eq!(late.len(), 1, "{late:?}");
        assert!(late[0].contains("TARGET"), "{late:?}");

        let nested = errors_for(
            "# collection: c\nFOR F IN FILES \"x\"\n    PARAM TEXT NOTE = \"n\"\n    REPORT REQUEST r\nEND\n",
        );
        assert_eq!(nested.len(), 1, "{nested:?}");
        assert!(nested[0].contains("NOTE"), "{nested:?}");
    }

    #[test]
    fn a_parameter_must_agree_with_its_own_declared_type() {
        let choice = errors_for(
            "# collection: c\nPARAM CHOICE(\"a\", \"b\") PICK = \"c\"\nREPORT REQUEST r\n",
        );
        assert_eq!(choice.len(), 1, "{choice:?}");
        assert!(
            choice[0].contains("PICK") && choice[0].contains("a, b"),
            "{choice:?}"
        );

        let empty = errors_for("# collection: c\nPARAM CHOICE() PICK\nREPORT REQUEST r\n");
        assert_eq!(empty.len(), 1, "{empty:?}");

        let number =
            errors_for("# collection: c\nPARAM NUMBER TRIES = \"many\"\nREPORT REQUEST r\n");
        assert_eq!(number.len(), 1, "{number:?}");
        assert!(number[0].contains("TRIES"), "{number:?}");

        // A default that has to be interpolated can't be judged until there is
        // something to interpolate, so it must not be rejected here.
        let deferred =
            errors_for("# collection: c\nPARAM NUMBER TRIES = \"{{RETRIES}}\"\nREPORT REQUEST r\n");
        assert!(deferred.is_empty(), "{deferred:?}");

        let dupes = errors_for(
            "# collection: c\nPARAM TEXT A = \"1\"\nPARAM NUMBER A = \"2\"\nREPORT REQUEST r\n",
        );
        assert_eq!(dupes.len(), 1, "{dupes:?}");
        assert!(dupes[0].contains('A'), "{dupes:?}");
    }

    /// Distinct names can still land on the same prompt once they are made
    /// readable, which produces a form with two identical fields.
    #[test]
    fn two_parameters_asking_the_same_question_are_flagged() {
        let diags = diags_for(
            "# collection: c\nPARAM TEXT TICKET_REF\nPARAM TEXT ticket_ref LABEL \"Ticket ref\"\nREPORT REQUEST r\n",
            None,
            None,
        );
        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "distinct names, so the report still runs: {diags:?}"
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("Ticket ref")),
            "{diags:?}"
        );
    }

    /// An environment parameter exists precisely so the environment can be
    /// changed per run, so a default naming one that isn't loaded right now
    /// must not block the report the way the fixed `# environment:` directive
    /// does.
    #[test]
    fn an_unloaded_environment_default_is_only_a_warning() {
        let loaded = ["staging".to_string()];
        let diags = diags_for(
            "# collection: c\nPARAM ENV TARGET = \"prod\"\nREPORT REQUEST r\n",
            None,
            Some(&loaded),
        );
        assert!(
            !diags.iter().any(|d| d.severity == Severity::Error),
            "{diags:?}"
        );
        assert!(
            diags
                .iter()
                .any(|d| d.severity == Severity::Warning && d.message.contains("prod")),
            "{diags:?}"
        );
    }

    /// The variable-availability warnings come out of a `HashSet`, whose
    /// iteration order differs between instances. Emitting them in that order
    /// meant the validation panel — which is rebuilt whenever its inputs change
    /// — reshuffled its contents each time, so a request with several unset
    /// variables flickered. They must come out sorted, every time.
    #[test]
    fn variable_warnings_come_out_in_a_stable_order() {
        use crate::hurl::HurlEntry;
        let entry = HurlEntry {
            title: "req".into(),
            method: "GET".into(),
            url: "http://x/{{alpha}}/{{bravo}}?q={{charlie}}".into(),
            body_src: Some("{\"d\":\"{{delta}}\",\"e\":\"{{echo}}\",\"f\":\"{{foxtrot}}\"}".into()),
            ..Default::default()
        };
        let entries = [entry];
        let titles = vec!["req".to_string()];
        let flow = parse_flow("# collection: c\nREQUEST req\n").expect("parses");
        let run = || {
            let ctx = Context {
                request_titles: Some(&titles),
                request_entries: Some(&entries),
                base_var_names: Some(&[]),
                ..Default::default()
            };
            validate(&flow, &ctx)
                .into_iter()
                .filter(|d| d.severity == Severity::Warning)
                .map(|d| d.message)
                // The flow emits no columns, which earns a warning of its own -
                // not what this test is about.
                .filter(|m| m.contains("{{"))
                .collect::<Vec<_>>()
        };
        let first = run();
        assert_eq!(first.len(), 6, "one warning per variable: {first:?}");
        // The order is not merely repeatable, it is alphabetical - so it also
        // stays put as unrelated variables are added and removed.
        let order: Vec<&str> = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot"].into();
        for (msg, name) in first.iter().zip(&order) {
            assert!(msg.contains(name), "expected {name} in {msg}");
        }
        // A fresh `HashSet` is built on every call, so repeating the walk is
        // what would shake out an order that depends on it.
        for i in 0..50 {
            assert_eq!(first, run(), "run {i} produced a different order");
        }
    }

    fn errors(src: &str, titles: Option<&[String]>, envs: Option<&[String]>) -> Vec<String> {
        diags_for(src, titles, envs)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    fn has_err(
        src: &str,
        titles: Option<&[String]>,
        envs: Option<&[String]>,
        needle: &str,
    ) -> bool {
        errors(src, titles, envs)
            .iter()
            .any(|m| m.to_lowercase().contains(&needle.to_lowercase()))
    }

    fn titles() -> Vec<String> {
        vec![
            "Oauth".into(),
            "CreateSession".into(),
            "upload/process_file".into(),
            "finalise_session".into(),
        ]
    }

    /// Warnings from validating `src` with a bound collection whose entries
    /// expose the given `[Reports]` field names (title → fields).
    fn warnings_with_fields(src: &str, fields: &[(&str, &[&str])]) -> Vec<String> {
        let flow = parse_flow(src).expect("test source should parse");
        let titles: Vec<String> = fields.iter().map(|(t, _)| t.to_string()).collect();
        let field_map: Vec<(String, Vec<String>)> = fields
            .iter()
            .map(|(t, fs)| (t.to_string(), fs.iter().map(|s| s.to_string()).collect()))
            .collect();
        let ctx = Context {
            request_titles: Some(&titles),
            request_fields: Some(&field_map),
            ..Default::default()
        };
        validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect()
    }

    #[test]
    fn duplicate_column_headers_are_rejected() {
        let titles = titles();
        // `FILE AS X` and `Oauth.status AS X` both resolve to header `X`, which
        // would collide in JSON output — one error, reported once.
        let errs = errors(
            "# collection: c\n# columns: FILE AS X, Oauth.status AS X, Oauth AS X\nREPORT REQUEST Oauth\n",
            Some(&titles),
            None,
        );
        let dup: Vec<_> = errs.iter().filter(|m| m.contains("Two columns")).collect();
        assert_eq!(dup.len(), 1, "one duplicate-header error: {errs:?}");
        assert!(dup[0].contains('X'));

        // Distinct headers are fine.
        assert!(!has_err(
            "# collection: c\n# columns: FILE AS Name, Oauth.status AS Status\nREPORT REQUEST Oauth\n",
            Some(&titles),
            None,
            "Two columns",
        ));
    }

    #[test]
    fn show_unknown_field_warns_but_known_fields_do_not() {
        // `Response`/`Time` are intrinsics; `status` is a [Reports] field —
        // all fine. `bogus` is none of those → one warning.
        let warns = warnings_with_fields(
            "REPORT REQUEST process SHOW(Response, Time, status, bogus)\n",
            &[("process", &["status", "overall"])],
        );
        assert_eq!(warns.len(), 1, "only 'bogus' should warn: {warns:?}");
        assert!(warns[0].contains("bogus"));
    }

    #[test]
    fn show_with_field_counts_as_known() {
        // A field provided only by this statement's WITH block is known.
        let warns = warnings_with_fields(
            "REPORT REQUEST process SHOW(extra) WITH\n    extra: jsonpath \"$.x\"\nEND\n",
            &[("process", &[])],
        );
        assert!(
            warns.iter().all(|w| !w.contains("extra")),
            "WITH field should not warn: {warns:?}"
        );
    }

    #[test]
    fn show_is_not_validated_without_a_bound_collection() {
        // No request_fields context → the field set is unknown, so no warning
        // (never false-warn on a real [Reports] field we can't see).
        let flow = parse_flow("REPORT REQUEST process SHOW(bogus)\n").unwrap();
        let ctx = Context::default();
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("SHOW"))
            .collect();
        assert!(warns.is_empty(), "unbound flow shouldn't warn: {warns:?}");
    }

    /// The header-directive diagnostics, grouped: each line is one "this source
    /// does / does not raise that message" case, which is all these families
    /// ever were. Grouped rather than one test apiece so the cases can be read
    /// against each other; a failure names the source and the message it wanted.
    #[test]
    fn collection_and_output_header_diagnostics() {
        let t = titles();
        // No collection at all, and a directive present but empty, are the same
        // error: nothing to resolve request names against.
        assert!(has_err(
            "REQUEST Oauth\n",
            None,
            None,
            "No collection chosen"
        ));
        let empty_directive = "# collection:\nREQUEST Oauth\n";
        assert!(has_err(empty_directive, None, None, "No collection chosen"));

        let docx = "# collection: ./c.hurl\n# output: docx\nREQUEST Oauth\n";
        assert!(has_err(docx, Some(&t), None, "unsupported output format"));
        let csv = "# collection: ./c.hurl\n# output: csv\nREQUEST Oauth\n";
        assert!(!has_err(csv, Some(&t), None, "unsupported"));
    }
    #[test]
    fn valid_header_with_bound_collection_has_no_errors() {
        let t = titles();
        let errs = errors("# collection: ./c.hurl\nREQUEST Oauth\n", Some(&t), None);
        assert!(errs.is_empty(), "unexpected errors: {errs:?}");
    }

    #[test]
    fn xlsx_json_html_outputs_are_accepted() {
        let t = titles();
        for fmt in ["xlsx", "json", "html"] {
            assert!(
                !has_err(
                    &format!("# collection: ./c.hurl\n# output: {fmt}\nREQUEST Oauth\n"),
                    Some(&t),
                    None,
                    "unsupported"
                ),
                "format {fmt} should be accepted"
            );
        }
    }

    /// Ground truth never blocks a run — a report that scores nothing still
    /// produces its table — but every silent no-op is pointed out.
    #[test]
    fn ground_truth_mistakes_warn_without_blocking_the_run() {
        let t = titles();
        let warn = |src: &str| -> Vec<String> {
            diags_for(src, Some(&t), None)
                .into_iter()
                .filter(|d| d.severity == Severity::Warning)
                .map(|d| d.message)
                .collect()
        };
        let said = |ws: &[String], needle: &str| {
            ws.iter()
                .any(|m| m.to_lowercase().contains(&needle.to_lowercase()))
        };

        let ws = warn("# collection: ./c.hurl\n# labels: nonsense\nREQUEST Oauth\n");
        assert!(said(&ws, "declares nothing"), "{ws:?}");

        let ws = warn(
            "# collection: ./c.hurl\n# labels: Pass = ok, maybe\n# labels: Fail = maybe\nREQUEST Oauth\n",
        );
        assert!(said(&ws, "claimed by both"), "{ws:?}");

        let ws = warn("# collection: ./c.hurl\nREPORT \"a\" AS V TRUTH \"\"\n");
        assert!(said(&ws, "empty ground truth"), "{ws:?}");

        let ws =
            warn("# collection: ./c.hurl\nREPORT \"a\" AS V IMAGE(HEIGHT 40) TRUTH \"{{ e }}\"\n");
        assert!(said(&ws, "shown as a picture"), "{ws:?}");

        // None of them is an error, and a well-formed one says nothing at all.
        let src = "# collection: ./c.hurl\n# labels: Pass = ok, real\nREPORT \"a\" AS V TRUTH \"{{ e }}\"\n";
        assert!(errors(src, Some(&t), None).is_empty());
        let ws = warn(src);
        assert!(
            !said(&ws, "ground truth") && !said(&ws, "label"),
            "a correct ground truth is silent: {ws:?}"
        );
    }

    /// The `# environment:` directive's diagnostics, grouped.
    #[test]
    fn environment_header_diagnostics() {
        let t = titles();
        let named_staging = "# collection: ./c.hurl\n# environment: staging\nREQUEST Oauth\n";
        let only_au = ["au".to_string()];
        let au_and_staging = ["au".to_string(), "staging".to_string()];

        let unloaded = "environment 'staging' is not loaded";
        assert!(has_err(named_staging, Some(&t), Some(&only_au), unloaded));
        let loaded = Some(&au_and_staging[..]);
        assert!(!has_err(named_staging, Some(&t), loaded, "is not loaded"));

        let empty = "# collection: ./c.hurl\n# environment:\nREQUEST Oauth\n";
        assert!(has_err(
            empty,
            Some(&t),
            None,
            "environment setting is empty"
        ));

        // With no loaded-env context, a named environment can't be verified —
        // it must not spuriously error (mirrors how ENVS names are skipped).
        assert!(!has_err(named_staging, Some(&t), None, "is not loaded"));
    }
    #[test]
    fn unbound_collection_warns_but_does_not_error_on_names() {
        let diags = diags_for("# collection: ./c.hurl\nREQUEST Whatever\n", None, None);
        assert!(
            diags.iter().any(|d| d.severity == Severity::Warning
                && d.message.contains("collection isn't loaded"))
        );
        // No name-resolution error while unbound.
        assert!(!diags.iter().any(|d| d.message.contains("not found")));
    }

    /// How a `REQUEST` name is matched against the bound collection's titles.
    #[test]
    fn request_name_resolution_diagnostics() {
        let t = titles();
        let full = "# collection: ./c.hurl\nREQUEST upload/process_file\n";
        assert!(!has_err(full, Some(&t), None, "not found"));

        // "process_file" is the leaf of "upload/process_file".
        let leaf = "# collection: ./c.hurl\nREPORT REQUEST process_file\n";
        assert!(!has_err(leaf, Some(&t), None, "not found"));

        let unknown = "# collection: ./c.hurl\nREQUEST nope\n";
        assert!(has_err(unknown, Some(&t), None, "not found"));

        // A leaf shared by two requests can't be resolved.
        let dups = vec!["a/dup".to_string(), "b/dup".to_string()];
        let ambiguous = "# collection: ./c.hurl\nREQUEST dup\n";
        assert!(has_err(ambiguous, Some(&dups), None, "ambiguous"));
    }
    /// The `ENVS` loop-source diagnostics: role clauses and unloaded names.
    #[test]
    fn envs_clause_diagnostics() {
        let t = titles();
        // An ENVS clause with no names can't be produced by the parser directly,
        // so drive check_env_clause via a role clause missing comparisons.
        let no_comparison =
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(\"prod\")\n  REQUEST Oauth\nEND\n";
        assert!(has_err(
            no_comparison,
            Some(&t),
            None,
            "at least one COMPARISON"
        ));

        let two_baselines = "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(\"a\", \"b\"), COMPARISON(\"c\")\n  REQUEST Oauth\nEND\n";
        assert!(has_err(
            two_baselines,
            Some(&t),
            None,
            "at most one BASELINE"
        ));

        let named = "# collection: ./c.hurl\nFOR T IN ENVS \"prod-au\", \"staging-au\"\n  REQUEST Oauth\nEND\n";
        let only_prod = vec!["prod-au".to_string()];
        let both = vec!["prod-au".to_string(), "staging-au".to_string()];
        let missing = "'staging-au' is not loaded";
        assert!(has_err(named, Some(&t), Some(&only_prod), missing));
        assert!(!has_err(named, Some(&t), Some(&both), "not loaded"));
    }
    #[test]
    fn baseline_directive_with_envs_comparison_warns_it_is_ignored() {
        // Both a `# baseline:` snapshot diff and a live ENVS comparison target
        // the `Result` column; the live comparison wins, so the directive is
        // flagged as ignored rather than silently doing nothing.
        let t = titles();
        let warns: Vec<String> = diags_for(
            "# collection: ./c.hurl\n# baseline: prev.baseline\nFOR T IN ENVS BASELINE(\"a\"), COMPARISON(\"b\")\n  REQUEST Oauth\nEND\n",
            Some(&t),
            None,
        )
        .into_iter()
        .filter(|d| d.severity == Severity::Warning)
        .map(|d| d.message)
        .collect();
        assert!(
            warns
                .iter()
                .any(|m| m.contains("baseline setting is ignored")),
            "expected the ignored-baseline warning: {warns:?}"
        );
    }

    #[test]
    fn baseline_directive_without_envs_comparison_does_not_warn() {
        // A plain snapshot diff (no ENVS roles) is the normal Source-B path — no
        // warning.
        let t = titles();
        let warns: Vec<String> = diags_for(
            "# collection: ./c.hurl\n# baseline: prev.baseline\nREPORT REQUEST Oauth\n",
            Some(&t),
            None,
        )
        .into_iter()
        .filter(|d| d.severity == Severity::Warning)
        .map(|d| d.message)
        .collect();
        assert!(
            !warns.iter().any(|m| m.contains("'# baseline:'")),
            "a plain baseline diff should not warn: {warns:?}"
        );
    }

    #[test]
    fn missing_baseline_snapshot_warns_when_anchored() {
        // With a known base directory, a `# baseline:` naming a file that isn't
        // there is surfaced as a warning up front (not silently at run time).
        let dir = std::env::temp_dir().join(format!("pb-vbl-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let flow = parse_flow(
            "# collection: ./c.hurl\n# baseline: missing.baseline\nREPORT REQUEST Oauth\n",
        )
        .unwrap();
        let t = titles();
        let ctx = Context {
            request_titles: Some(&t),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            warns.iter().any(|m| m.contains("was not found")),
            "expected a missing-snapshot warning: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A `BASELINE(FILE(…))` role whose snapshot isn't on disk was the one
    /// baseline reference with no preflight at all: unlike the `# baseline:`
    /// directive it was skipped entirely, so a typo only showed up as an
    /// unmatched comparison after a full run had already been paid for.
    #[test]
    fn missing_baseline_file_role_warns_when_anchored() {
        let dir = std::env::temp_dir().join(format!("pb-vrole-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let flow = parse_flow(
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(FILE(\"missing.baseline\")), COMPARISON(\"prod\")\n    REPORT REQUEST Oauth\nEND\n",
        )
        .unwrap();
        let t = titles();
        let envs = vec!["prod".to_string()];
        let ctx = Context {
            request_titles: Some(&t),
            env_names: Some(&envs),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            warns
                .iter()
                .any(|m| m.contains("was not found") && m.contains("missing.baseline")),
            "expected a missing-snapshot warning: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_comparison_file_role_is_checked_too_and_a_present_one_stays_quiet() {
        let dir = std::env::temp_dir().join(format!("pb-vrole-ok-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("prev.baseline"), "{}").unwrap();
        let flow = parse_flow(
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(FILE(\"prev.baseline\")), COMPARISON(FILE(\"gone.baseline\"))\n    REPORT REQUEST Oauth\nEND\n",
        )
        .unwrap();
        let t = titles();
        let ctx = Context {
            request_titles: Some(&t),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            warns.iter().any(|m| m.contains("gone.baseline")),
            "a comparison role's snapshot is checked as well: {warns:?}"
        );
        assert!(
            !warns.iter().any(|m| m.contains("prev.baseline")),
            "an existing snapshot must stay quiet: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// A `FILE(…)` role is a path, not an environment, so it must never be
    /// reported as "not loaded" — the check that protects live env names.
    #[test]
    fn a_file_role_is_never_mistaken_for_an_unloaded_environment() {
        let flow = parse_flow(
            "# collection: ./c.hurl\nFOR T IN ENVS BASELINE(FILE(\"snap.baseline\")), COMPARISON(\"prod\")\n    REPORT REQUEST Oauth\nEND\n",
        )
        .unwrap();
        let t = titles();
        let envs = vec!["prod".to_string()];
        // No `root`, so the filesystem check is skipped entirely: an unsaved
        // report has nothing to resolve a relative path against.
        let ctx = Context {
            request_titles: Some(&t),
            env_names: Some(&envs),
            ..Default::default()
        };
        let msgs: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .map(|d| d.message)
            .collect();
        assert!(
            !msgs.iter().any(|m| m.contains("snap.baseline")),
            "an unanchored report must not report on the snapshot at all: {msgs:?}"
        );
    }

    #[test]
    fn present_baseline_snapshot_does_not_warn() {
        let dir = std::env::temp_dir().join(format!("pb-vbl-ok-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("prev.baseline"), "{}").unwrap();
        let flow =
            parse_flow("# collection: ./c.hurl\n# baseline: prev.baseline\nREPORT REQUEST Oauth\n")
                .unwrap();
        let t = titles();
        let ctx = Context {
            request_titles: Some(&t),
            root: Some(dir.as_path()),
            ..Default::default()
        };
        let warns: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .map(|d| d.message)
            .collect();
        assert!(
            !warns.iter().any(|m| m.contains("was not found")),
            "an existing snapshot should not warn: {warns:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// How many names a loop pattern binds versus how wide its source is, and
    /// whether the list it names was ever declared.
    #[test]
    fn loop_arity_and_list_reference_diagnostics() {
        let t = titles();
        let c = "# collection: ./c.hurl\n";
        let check = |src: String, needle: &str| has_err(&src, Some(&t), None, needle);

        let two_from_one = format!("{c}FOR (A, B) IN FILES \"d\"\n  REQUEST Oauth\nEND\n");
        assert!(check(two_from_one, "binds 2 name"));
        let zip = format!("{c}FOR (A, B) IN ZIP(FILES \"x\", FILES \"y\")\n  REQUEST Oauth\nEND\n");
        assert!(!check(zip, "binds"));

        let concat_ok = format!(
            "{c}FOR F IN CONCAT(FILES \"x\", FILES \"y\", FOLDERS \"z\")\n  REQUEST Oauth\nEND\n"
        );
        assert!(!check(concat_ok, "arity"));
        let concat_bad = format!(
            "{c}FOR F IN CONCAT(FILES \"x\", ZIP(FILES \"a\", FILES \"b\"))\n  REQUEST Oauth\nEND\n"
        );
        assert!(check(concat_bad, "inconsistent arity"));

        let ragged =
            format!("{c}LIST L = [(\"a\", \"b\"), \"c\"]\nFOR (X, Y) IN L\n  REQUEST Oauth\nEND\n");
        assert!(check(ragged, "inconsistent arity"));
        // A rest pattern absorbs whatever extra positions a row carries.
        let rest = format!(
            "{c}LIST L = [(\"a\", \"b\", \"c\")]\nFOR (X, ...) IN L\n  REQUEST Oauth\nEND\n"
        );
        assert!(!check(rest, "binds"));

        let undeclared = format!("{c}FOR X IN MISSING\n  REQUEST Oauth\nEND\n");
        assert!(check(undeclared, "unknown list"));
        let declared = format!("{c}LIST DOCS = FILES \"d\"\nFOR X IN DOCS\n  REQUEST Oauth\nEND\n");
        assert!(!check(declared, "unknown list"));
    }
    #[test]
    fn show_and_hide_overlap_is_an_error() {
        // A field in both SHOW and HIDE is contradictory → validation error.
        let t = titles();
        let errs = errors(
            "# collection: c\nREPORT REQUEST Oauth SHOW(HttpStatus, Time) HIDE(Time)\n",
            Some(&t),
            None,
        );
        let overlap: Vec<_> = errs.iter().filter(|m| m.contains("Time")).collect();
        assert_eq!(overlap.len(), 1, "one overlap error for Time: {errs:?}");
        assert!(
            overlap[0].contains("conflict")
                || overlap[0].contains("SHOW")
                || overlap[0].contains("HIDE")
        );
    }

    #[test]
    fn hide_unknown_field_warns_but_known_fields_do_not() {
        // Same semantics as the SHOW unknown-field warning, but for HIDE.
        let warns = warnings_with_fields(
            "REPORT REQUEST process HIDE(Response, Time, status, ghost)\n",
            &[("process", &["status", "overall"])],
        );
        assert_eq!(warns.len(), 1, "only 'ghost' should warn: {warns:?}");
        assert!(warns[0].contains("ghost"));
    }

    #[test]
    fn hide_is_not_validated_without_a_bound_collection() {
        let flow = parse_flow("REPORT REQUEST process HIDE(bogus)\n").unwrap();
        let ctx = Context::default();
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .filter(|d| d.message.contains("HIDE"))
            .collect();
        assert!(
            warns.is_empty(),
            "unbound flow shouldn't warn on HIDE: {warns:?}"
        );
    }

    // -----------------------------------------------------------------------
    // Variable-availability analysis tests
    // -----------------------------------------------------------------------

    /// Make a minimal `HurlEntry` for testing: `title` as the name,
    /// `{{VAR}}` references baked into the URL, and named captures.
    fn test_entry(title: &str, url_vars: &[&str], captures: &[&str]) -> crate::hurl::HurlEntry {
        use crate::hurl::HurlEntry;
        let url: String = url_vars
            .iter()
            .map(|v| format!("{{{{{}}}}} ", v))
            .collect::<String>();
        HurlEntry {
            title: title.to_string(),
            method: "GET".to_string(),
            url: format!("http://example/{}x", url),
            captures: captures
                .iter()
                .map(|c| ((*c).to_string(), "jsonpath \"$.v\"".to_string()))
                .collect(),
            ..Default::default()
        }
    }

    /// Validate `src` with a given context and return only the variable-
    /// availability warning messages.
    fn var_warns(
        src: &str,
        base_vars: &[&str],
        all_env_vars: &[&str],
        entries: &[crate::hurl::HurlEntry],
    ) -> Vec<String> {
        let flow = parse_flow(src).expect("test source should parse");
        let base: Vec<String> = base_vars.iter().map(|s| s.to_string()).collect();
        let all_env: Vec<String> = all_env_vars.iter().map(|s| s.to_string()).collect();
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let ctx = Context {
            request_titles: Some(&titles),
            base_var_names: Some(&base),
            all_env_var_names: Some(&all_env),
            request_entries: Some(entries),
            ..Default::default()
        };
        validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning && d.message.contains("may not be set"))
            .map(|d| d.message)
            .collect()
    }

    /// A `# [Gen]` row defines its name. Warning that a signature "may not be
    /// set" on every request that computes one is a warning nobody can act on,
    /// and a panel full of those is a panel nobody reads.
    #[test]
    fn a_computed_value_is_not_reported_as_possibly_unset() {
        let mut entry = test_entry("sign", &["sig"], &[]);
        entry
            .generators
            .push(("sig".to_string(), "hmac_sha256(k, m)".to_string()));
        let warns = var_warns("REQUEST sign\n", &["k", "m"], &[], &[entry]);
        assert!(
            warns.is_empty(),
            "the request computes sig itself: {warns:?}"
        );
    }

    /// A computed value is bound for its own request onwards, exactly like a
    /// capture, so a later request may read one an earlier request made.
    #[test]
    fn a_later_request_may_read_an_earlier_requests_computed_value() {
        let mut first = test_entry("submit", &[], &[]);
        first
            .generators
            .push(("transaction_id".to_string(), "uuid".to_string()));
        let second = test_entry("result", &["transaction_id"], &[]);
        let warns = var_warns(
            "REQUEST submit\nREQUEST result\n",
            &[],
            &[],
            &[first, second],
        );
        assert!(warns.is_empty(), "submit defines it first: {warns:?}");
    }

    /// A request that declares its own parameter supplies a value for it, so
    /// the reference is never unset. Warning about it punished the collection
    /// for being properly parameterised — and buried the warnings that matter
    /// under one per parameter per call site.
    #[test]
    fn a_declared_parameter_is_not_reported_as_possibly_unset() {
        let mut entry = test_entry("upload", &["FILE"], &[]);
        entry.options.push(crate::hurl::KvRow::new(
            "variable".to_string(),
            "FILE=./samples/front.jpg".to_string(),
        ));
        let warns = var_warns("REQUEST upload\n", &[], &[], &[entry]);
        assert!(
            warns.is_empty(),
            "the request declares FILE itself: {warns:?}"
        );
    }

    /// The other side of it: an undeclared name is still reported, so removing
    /// the noise hasn't removed the check.
    #[test]
    fn an_undeclared_var_is_still_reported_beside_a_declared_one() {
        let mut entry = test_entry("upload", &["FILE", "SESSION"], &[]);
        entry.options.push(crate::hurl::KvRow::new(
            "variable".to_string(),
            "FILE=./samples/front.jpg".to_string(),
        ));
        let warns = var_warns("REQUEST upload\n", &[], &[], &[entry]);
        assert_eq!(warns.len(), 1, "only the undeclared one: {warns:?}");
        assert!(warns[0].contains("SESSION"), "{warns:?}");
    }

    #[test]
    fn missing_var_in_request_url_produces_a_warning() {
        // Oauth's URL references {{TOKEN}} which isn't in the env or in scope.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nREPORT REQUEST Oauth\n",
            &[], // no env vars
            &[],
            &entries,
        );
        assert!(
            warns.iter().any(|w| w.contains("TOKEN")),
            "{{TOKEN}} should warn as undefined: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_base_env_does_not_warn() {
        // When BASE_URL is in the base environment, no warning.
        let entries = vec![test_entry("Oauth", &["BASE_URL"], &[])];
        let warns = var_warns(
            "# collection: c\nREPORT REQUEST Oauth\n",
            &["BASE_URL"], // provided by env
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "BASE_URL is in the base env — no warning expected: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_explicit_assignment_does_not_warn() {
        // An explicit `KEY=value` assignment before the request defines it.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nTOKEN=abc\nREPORT REQUEST Oauth\n",
            &[], // not in env
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is assigned before the request — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_for_loop_binder_does_not_warn() {
        // TOKEN is the loop binder inside a FOR loop.
        let entries = vec![test_entry("Oauth", &["TOKEN"], &[])];
        let warns = var_warns(
            "# collection: c\nFOR TOKEN IN [\"x\", \"y\"]\n    REPORT REQUEST Oauth\nEND\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is a FOR loop binder — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_prior_capture_does_not_warn() {
        // Auth request captures TOKEN; then Api uses it.
        let auth = test_entry("Auth", &[], &["TOKEN"]);
        let api = test_entry("Api", &["TOKEN"], &[]);
        let entries = vec![auth, api];
        let warns = var_warns(
            "# collection: c\nREQUEST Auth\nREPORT REQUEST Api\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns.is_empty(),
            "TOKEN is captured by Auth before Api runs — no warning: {warns:?}"
        );
    }

    #[test]
    fn var_defined_by_envs_loop_does_not_warn() {
        // Inside a FOR … IN ENVS loop, any env variable is potentially in scope.
        let entries = vec![test_entry("Api", &["REGION"], &[])];
        // REGION is in one of the loaded envs (all_env_vars).
        let warns = var_warns(
            "# collection: c\nFOR ENV IN ENVS \"prod\", \"staging\"\n    REPORT REQUEST Api\nEND\n",
            &[],         // not in base env
            &["REGION"], // but one of the envs provides it
            &entries,
        );
        assert!(
            warns.is_empty(),
            "REGION comes from the ENVS loop env — no warning: {warns:?}"
        );
    }

    #[test]
    fn no_warning_without_base_var_names_context() {
        // When base_var_names is None the check is skipped entirely
        // (conservative: we can't know what the env provides).
        let entries = vec![test_entry("Oauth", &["MISSING"], &[])];
        let titles: Vec<String> = entries.iter().map(|e| e.title.clone()).collect();
        let flow = parse_flow("# collection: c\nREPORT REQUEST Oauth\n").unwrap();
        let ctx = Context {
            request_titles: Some(&titles),
            base_var_names: None, // unknown
            request_entries: Some(&entries),
            ..Default::default()
        };
        let warns: Vec<_> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Warning && d.message.contains("may not be defined"))
            .collect();
        assert!(
            warns.is_empty(),
            "without base_var_names the check must be skipped: {warns:?}"
        );
    }

    #[test]
    fn capture_is_only_available_after_the_capturing_request() {
        // TOKEN is captured by Auth, but if a request runs before Auth and uses
        // TOKEN, it should warn. After Auth the warning is gone.
        let auth = test_entry("Auth", &[], &["TOKEN"]);
        let before = test_entry("Before", &["TOKEN"], &[]);
        let after = test_entry("After", &["TOKEN"], &[]);
        let entries = vec![auth.clone(), before.clone(), after.clone()];
        // Flow: Before (uses TOKEN — not yet captured), then Auth (captures TOKEN),
        // then After (uses TOKEN — OK, captured by Auth).
        let warns_before = var_warns(
            "# collection: c\nREPORT REQUEST Before\nREQUEST Auth\nREPORT REQUEST After\n",
            &[],
            &[],
            &entries,
        );
        assert!(
            warns_before
                .iter()
                .any(|w| w.contains("TOKEN") && w.contains("Before")),
            "TOKEN is not yet captured when Before runs: {warns_before:?}"
        );
        assert!(
            !warns_before
                .iter()
                .any(|w| w.contains("TOKEN") && w.contains("After")),
            "TOKEN IS captured by the time After runs: {warns_before:?}"
        );
    }
    // ---- Step identity -----------------------------------------------------

    /// Only the errors, as text — step-name checks need no collection context.
    fn step_errors(src: &str) -> Vec<String> {
        diags_for(src, None, None)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    #[test]
    fn as_names_a_plain_request_step() {
        let src = "# collection: c\n\nREQUEST auth/session AS sess\n";
        let flow = parse_flow(src).expect("parses");
        assert!(matches!(
            &flow.nodes[0],
            FlowNode::Request { name, alias: Some(a), .. }
                if name == "auth/session" && a == "sess"
        ));
        // And it round-trips, so naming a step survives an editor save.
        assert_eq!(flow.to_text(), src);
    }

    #[test]
    fn as_and_using_are_accepted_in_either_order_on_a_plain_request() {
        // The clause belongs to the send and the name to the step, so neither
        // order is obviously wrong to reach for; both normalise on save.
        let a = parse_flow("# collection: c\n\nREQUEST up AS u USING(FILE)\n").expect("parses");
        let b = parse_flow("# collection: c\n\nREQUEST up USING(FILE) AS u\n").expect("parses");
        assert_eq!(a.to_text(), b.to_text());
    }

    #[test]
    fn two_steps_in_one_body_may_not_share_a_name() {
        // The defect this whole rule exists for: two sends collapsing into one
        // node, so a reference to `up` cannot say which one it meant.
        let errs = step_errors("# collection: c\n\nREQUEST up AS u\nREQUEST up AS u\n");
        assert!(
            errs.iter().any(|e| e.contains("'u'") && e.contains("own")),
            "{errs:?}"
        );
    }

    #[test]
    fn running_one_request_twice_without_as_is_ambiguous() {
        let errs = step_errors("# collection: c\n\nREQUEST up\nREQUEST up\n");
        assert!(
            errs.iter().any(|e| e.contains("'up'") && e.contains("AS")),
            "{errs:?}"
        );
        // Naming them resolves it.
        assert!(step_errors("# collection: c\n\nREQUEST up AS a\nREQUEST up AS b\n").is_empty());
    }

    #[test]
    fn sibling_blocks_may_reuse_a_step_name() {
        // `liveness.trail` does exactly this: two sibling loops each create a
        // session and each report `AS Liveness`, deliberately, so both halves
        // pour into one set of columns. Nothing in either block can refer to
        // the other, so neither name is ambiguous and a flow-global uniqueness
        // rule would reject a working, readable flow.
        let src = concat!(
            "# collection: c\n\n",
            "FOR A IN FILES \"x\"\n",
            "    REQUEST CreateSession\n",
            "    REPORT REQUEST result AS Liveness\n",
            "END\n",
            "FOR B IN FILES \"y\"\n",
            "    REQUEST CreateSession\n",
            "    REPORT REQUEST result AS Liveness\n",
            "END\n",
        );
        assert_eq!(step_errors(src), Vec::<String>::new());
    }

    #[test]
    fn a_nested_block_may_not_shadow_an_enclosing_step_name() {
        // Unlike siblings, a body *can* see its ancestors, so reusing the name
        // there really would be ambiguous.
        let src = concat!(
            "# collection: c\n\n",
            "REQUEST setup AS s\n",
            "FOR A IN FILES \"x\"\n",
            "    REQUEST other AS s\n",
            "END\n",
        );
        assert!(!step_errors(src).is_empty());
    }

    #[test]
    fn a_step_name_must_be_an_identifier() {
        let errs = step_errors("# collection: c\n\nREQUEST up AS \"43_result\"\n");
        assert!(errs.iter().any(|e| e.contains("43_result")), "{errs:?}");
    }

    #[test]
    fn a_request_whose_leaf_is_not_an_identifier_must_be_named() {
        // Imported names routinely start with a digit; PaperTrail identifiers
        // may not, so such a request cannot name its own step.
        let errs = step_errors("# collection: c\n\nREQUEST \"folder/43_result\"\n");
        assert!(errs.iter().any(|e| e.contains("43_result")), "{errs:?}");
        // Naming it is the fix.
        assert!(step_errors("# collection: c\n\nREQUEST \"folder/43_result\" AS v43\n").is_empty());
    }

    #[test]
    fn a_path_like_request_names_its_step_from_the_leaf() {
        // The leaf is an identifier even though the full name is not, so no
        // `AS` is needed — and a second, differently-pathed request with the
        // same leaf is then the ambiguous case.
        assert!(step_errors("# collection: c\n\nREQUEST \"a/b/session\"\n").is_empty());
        assert!(
            !step_errors("# collection: c\n\nREQUEST \"a/session\"\nREQUEST \"b/session\"\n")
                .is_empty()
        );
    }

    // ---- Qualified capture references --------------------------------------

    /// A request that captures `captures` under `title`.
    fn capturing_entry(title: &str, captures: &[&str]) -> crate::hurl::HurlEntry {
        crate::hurl::HurlEntry {
            title: title.into(),
            method: "POST".into(),
            url: "http://x".into(),
            captures: captures
                .iter()
                .map(|c| ((*c).to_string(), "jsonpath \"$.t\"".to_string()))
                .collect(),
            ..Default::default()
        }
    }

    fn ref_errors(src: &str, entries: &[crate::hurl::HurlEntry]) -> Vec<String> {
        diags_with_entries(src, entries)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    #[test]
    fn a_qualified_reference_resolves_to_the_named_step() {
        // The motivating case: two steps both capture `token`, and the flat
        // name would silently mean whichever ran last. Qualifying says which.
        let entries = [capturing_entry("login", &["token"]), {
            let mut e = capturing_entry("api", &[]);
            e.title = "api".into();
            e
        }];
        let src = concat!(
            "# collection: c\n\n",
            "REQUEST login AS first\n",
            "REQUEST login AS second\n",
            "REQUEST api USING(header.Authorization = \"{{second.token}}\")\n",
        );
        assert_eq!(ref_errors(src, &entries), Vec::<String>::new());
    }

    #[test]
    fn a_qualified_reference_to_an_unknown_step_is_an_error() {
        let entries = [capturing_entry("login", &["token"])];
        let src = "# collection: c\n\nREQUEST login USING(header.X = \"{{nope.token}}\")\n";
        let errs = ref_errors(src, &entries);
        assert!(errs.iter().any(|e| e.contains("nope")), "{errs:?}");
    }

    #[test]
    fn a_step_cannot_reference_its_own_captures() {
        // They don't exist until it has run, so this is always a mistake —
        // and it reads plausibly enough to be worth catching.
        let entries = [capturing_entry("login", &["token"])];
        let src = "# collection: c\n\nREQUEST login AS me USING(header.X = \"{{me.token}}\")\n";
        let errs = ref_errors(src, &entries);
        assert!(errs.iter().any(|e| e.contains("me")), "{errs:?}");
    }

    #[test]
    fn a_qualified_reference_to_a_value_the_step_does_not_capture_is_an_error() {
        let entries = [
            capturing_entry("login", &["token"]),
            capturing_entry("api", &[]),
        ];
        let src = concat!(
            "# collection: c\n\n",
            "REQUEST login AS first\n",
            "REQUEST api USING(header.X = \"{{first.session}}\")\n",
        );
        let errs = ref_errors(src, &entries);
        assert!(
            errs.iter()
                .any(|e| e.contains("session") && e.contains("first")),
            "{errs:?}"
        );
    }

    #[test]
    fn a_qualified_reference_cannot_reach_sideways_into_a_sibling_block() {
        // Sibling scopes are exactly why uniqueness is lexical; the same rule
        // has to govern what a reference can see, or the two disagree.
        let entries = [
            capturing_entry("login", &["token"]),
            capturing_entry("api", &[]),
        ];
        let src = concat!(
            "# collection: c\n\n",
            "FOR A IN FILES \"x\"\n",
            "    REQUEST login AS first\n",
            "END\n",
            "FOR B IN FILES \"y\"\n",
            "    REQUEST api USING(header.X = \"{{first.token}}\")\n",
            "END\n",
        );
        let errs = ref_errors(src, &entries);
        assert!(errs.iter().any(|e| e.contains("first")), "{errs:?}");
    }

    #[test]
    fn an_enclosing_step_is_visible_from_inside_a_block() {
        let entries = [
            capturing_entry("login", &["token"]),
            capturing_entry("api", &[]),
        ];
        let src = concat!(
            "# collection: c\n\n",
            "REQUEST login AS first\n",
            "FOR A IN FILES \"x\"\n",
            "    REQUEST api USING(header.X = \"{{first.token}}\")\n",
            "END\n",
        );
        assert_eq!(ref_errors(src, &entries), Vec::<String>::new());
    }

    #[test]
    fn an_undotted_reference_is_not_treated_as_a_step_reference() {
        // Ordinary variables outnumber qualified ones by a long way; the check
        // must not fire on them.
        let entries = [capturing_entry("api", &[])];
        let src =
            "# collection: c\n\nBASE = \"http://x\"\nREQUEST api USING(header.X = \"{{BASE}}\")\n";
        assert_eq!(ref_errors(src, &entries), Vec::<String>::new());
    }

    // ---- GRAPH regions -----------------------------------------------------

    #[test]
    fn a_region_may_hold_only_requests_and_comments() {
        let errs = step_errors(concat!(
            "# collection: c\n\n",
            "GRAPH\n",
            "    # a note\n",
            "    REQUEST a\n",
            "    REPORT REQUEST b\n",
            "END\n",
        ));
        assert_eq!(errs, Vec::<String>::new());

        // An assignment inside a region has no place in the order: later steps
        // read it, but it is not a step, so nothing can depend on it.
        let errs = step_errors("# collection: c\n\nGRAPH\n    X = \"1\"\n    REQUEST a\nEND\n");
        assert!(errs.iter().any(|e| e.contains("GRAPH")), "{errs:?}");
    }

    #[test]
    fn a_region_and_a_loop_may_not_contain_one_another() {
        let in_loop = step_errors(concat!(
            "# collection: c\n\n",
            "FOR F IN FILES \"x\"\n",
            "    GRAPH\n",
            "        REQUEST a\n",
            "    END\n",
            "END\n",
        ));
        assert!(!in_loop.is_empty(), "a region inside a loop");
        let loop_in = step_errors(concat!(
            "# collection: c\n\n",
            "GRAPH\n",
            "    FOR F IN FILES \"x\"\n",
            "        REQUEST a\n",
            "    END\n",
            "END\n",
        ));
        assert!(!loop_in.is_empty(), "a loop inside a region");
    }

    #[test]
    fn a_region_may_not_contain_another_region() {
        let errs = step_errors(concat!(
            "# collection: c\n\n",
            "GRAPH\n",
            "    GRAPH\n",
            "        REQUEST a\n",
            "    END\n",
            "END\n",
        ));
        assert!(!errs.is_empty(), "{errs:?}");
    }

    #[test]
    fn a_reference_inside_a_region_may_point_forward() {
        // Outside a region this is an unknown step, because nothing below has
        // run yet. Inside one, order is computed, so it is ordinary.
        let entries = [
            capturing_entry("login", &["token"]),
            capturing_entry("api", &[]),
        ];
        let forward = concat!(
            "# collection: c\n\n",
            "GRAPH\n",
            "    REQUEST api USING(header.X = \"{{login.token}}\")\n",
            "    REQUEST login\n",
            "END\n",
        );
        assert_eq!(ref_errors(forward, &entries), Vec::<String>::new());
        // The same two statements outside a region are not reorderable, so the
        // reference really is to something that hasn't happened.
        let flat = concat!(
            "# collection: c\n\n",
            "REQUEST api USING(header.X = \"{{login.token}}\")\n",
            "REQUEST login\n",
        );
        assert!(!ref_errors(flat, &entries).is_empty());
    }

    #[test]
    fn a_step_in_a_region_still_cannot_reference_itself() {
        let entries = [capturing_entry("login", &["token"])];
        let errs = ref_errors(
            "# collection: c\n\nGRAPH\n    REQUEST login AS me USING(header.X = \"{{me.token}}\")\nEND\n",
            &entries,
        );
        assert!(errs.iter().any(|e| e.contains("me")), "{errs:?}");
    }

    #[test]
    fn a_cycle_in_a_region_is_reported_when_the_report_is_opened() {
        // Not partway through a run that has already sent requests.
        let mut a = capturing_entry("a", &["x"]);
        a.url = "http://x/{{y}}".into();
        let mut b = capturing_entry("b", &["y"]);
        b.url = "http://x/{{x}}".into();
        let errs = ref_errors(
            "# collection: c\n\nGRAPH\n    REQUEST a\n    REQUEST b\nEND\n",
            &[a, b],
        );
        assert!(errs.iter().any(|e| e.contains("cycle")), "{errs:?}");
    }

    #[test]
    fn depends_on_a_name_no_step_carries_is_an_error() {
        let errs = ref_errors(
            "# collection: c\n\nGRAPH\n    REQUEST a\n    REQUEST b DEPENDS nope\nEND\n",
            &[capturing_entry("a", &[]), capturing_entry("b", &[])],
        );
        assert!(errs.iter().any(|e| e.contains("nope")), "{errs:?}");
    }

    #[test]
    fn a_step_may_not_depend_on_itself() {
        let errs = ref_errors(
            "# collection: c\n\nGRAPH\n    REQUEST a AS one DEPENDS one\nEND\n",
            &[capturing_entry("a", &[])],
        );
        assert!(!errs.is_empty(), "a self-dependency must be rejected");
    }

    #[test]
    fn depends_outside_a_region_is_an_error() {
        // Outside a GRAPH the written order *is* the order, so a dependency
        // has nothing to reorder and would quietly mean nothing.
        let errs = ref_errors(
            "# collection: c\n\nREQUEST a AS one\nREQUEST b DEPENDS one\n",
            &[capturing_entry("a", &[]), capturing_entry("b", &[])],
        );
        assert!(
            !errs.is_empty(),
            "DEPENDS outside a region must be rejected"
        );
    }

    #[test]
    fn a_cleanup_may_not_live_inside_a_region() {
        let errs = ref_errors(
            "# collection: c\n\nGRAPH\n    REQUEST a\n    CLEANUP b\nEND\n",
            &[capturing_entry("a", &[]), capturing_entry("b", &[])],
        );
        assert!(
            !errs.is_empty(),
            "a CLEANUP inside a GRAPH must be rejected"
        );
    }

    #[test]
    fn a_cleanup_outside_a_region_may_declare_dependencies() {
        let errs = ref_errors(
            "# collection: c\n\nREQUEST a AS one\nCLEANUP b DEPENDS one\n",
            &[capturing_entry("a", &[]), capturing_entry("b", &[])],
        );
        assert!(errs.is_empty(), "{errs:?}");
    }

    #[test]
    fn a_step_name_survives_the_report_toggle_both_ways() {
        // `AS` is identity, not a reporting option, so upgrading a REQUEST to a
        // REPORT REQUEST (and back) must not silently rename the step.
        use crate::report::edit::{DetachWhich, Modifier, attach_to_node, detach_from_node};
        let mut node = FlowNode::Request {
            name: "up".into(),
            alias: Some("u".into()),
            depends: Vec::new(),
            using: Vec::new(),
        };
        assert!(attach_to_node(&mut node, Modifier::Report));
        assert!(
            matches!(&node, FlowNode::Report(ReportStmt::Request { alias: Some(a), .. }) if a == "u"),
            "{node:?}"
        );
        detach_from_node(&mut node, DetachWhich::Report);
        assert!(
            matches!(&node, FlowNode::Request { alias: Some(a), .. } if a == "u"),
            "{node:?}"
        );
    }
}

#[cfg(test)]
mod helper_collection_validation_tests {
    use super::*;
    use crate::hurl::HurlEntry;
    use crate::report::parser::parse_flow;
    use crate::report::run::HelperCollection;

    fn entry(title: &str) -> HurlEntry {
        HurlEntry {
            title: title.to_string(),
            method: "GET".into(),
            url: "http://x".into(),
            ..Default::default()
        }
    }

    fn check(src: &str, titles: &[&str], helpers: &[HelperCollection]) -> Vec<String> {
        let flow = parse_flow(src).expect("parses");
        let titles: Vec<String> = titles.iter().map(|t| t.to_string()).collect();
        let ctx = Context {
            request_titles: Some(&titles),
            helpers,
            ..Default::default()
        };
        validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect()
    }

    fn helper(alias: &str, titles: &[&str]) -> HelperCollection {
        HelperCollection {
            alias: alias.into(),
            entries: titles.iter().map(|t| entry(t)).collect(),
        }
    }

    /// The point of the feature: a request that deliberately isn't in the
    /// collection under test still validates when addressed through its alias.
    #[test]
    fn a_helper_request_validates_through_its_alias() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./h.hurl AS h\n\nREQUEST h/fetch_frame\n",
            &["upload"],
            &[helper("h", &["fetch_frame"])],
        );
        assert!(errs.is_empty(), "{errs:?}");
    }

    /// …and validation agrees with `resolve_qualified`: a helper request named
    /// without its alias is an error here, because it would fail at run time.
    #[test]
    fn a_helper_request_without_its_alias_is_an_error() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./h.hurl AS h\n\nREQUEST fetch_frame\n",
            &["upload"],
            &[helper("h", &["fetch_frame"])],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("fetch_frame"));
    }

    #[test]
    fn a_missing_name_inside_a_helper_is_reported_with_the_alias() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./h.hurl AS h\n\nREQUEST h/nope\n",
            &["upload"],
            &[helper("h", &["fetch_frame"])],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("h/nope"), "{errs:?}");
    }

    #[test]
    fn the_primary_collection_takes_no_alias() {
        let errs = check(
            "# collection: ./api.hurl AS main\n\nREQUEST upload\n",
            &["upload"],
            &[],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
    }

    #[test]
    fn a_helper_must_be_aliased() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./h.hurl\n\nREQUEST upload\n",
            &["upload"],
            &[],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("./h.hurl"), "{errs:?}");
    }

    #[test]
    fn two_helpers_cannot_share_an_alias() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./a.hurl AS h\n# collection: ./b.hurl AS h\n\nREQUEST upload\n",
            &["upload"],
            &[helper("h", &["x"])],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
    }

    /// An alias that is also a top-level folder makes `folder/request`
    /// ambiguous, and PaperTrail never picks silently between two readings.
    #[test]
    fn an_alias_may_not_shadow_a_virtual_folder() {
        let errs = check(
            "# collection: ./api.hurl\n# collection: ./h.hurl AS auth\n\nREQUEST upload\n",
            &["auth/login", "upload"],
            &[helper("auth", &["x"])],
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("auth"), "{errs:?}");
    }

    #[test]
    fn an_unreadable_helper_is_an_error_on_the_directive() {
        let flow = parse_flow(
            "# collection: ./api.hurl\n# collection: ./gone.hurl AS h\n\nREQUEST upload\n",
        )
        .expect("parses");
        let titles = vec!["upload".to_string()];
        let errors = vec![("./gone.hurl".to_string(), "no such file".to_string())];
        let ctx = Context {
            request_titles: Some(&titles),
            helper_errors: &errors,
            ..Default::default()
        };
        let errs: Vec<String> = validate(&flow, &ctx)
            .into_iter()
            .filter(|d| d.severity == Severity::Error)
            .map(|d| d.message)
            .collect();
        assert!(
            errs.iter()
                .any(|e| e.contains("./gone.hurl") && e.contains("no such file")),
            "{errs:?}"
        );
    }
}