paperboy 0.5.1

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
//! Parse Hurl text into the app's [`HurlEntry`] model using `hurl_core`'s
//! parser, so we don't maintain a hand-written Hurl parser. `HurlEntry` stays
//! the editable/persistable model; this maps the parsed AST onto it. Fields that
//! must preserve their exact source text (URL, headers, body, captures, asserts)
//! are taken via `ToSource`/`Display` or by slicing the original source lines.

use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use hurl_core::ast::{
    Body, Bytes, Capture, Entry, KeyValue, MultipartParam, SectionValue, StatusValue, VersionValue,
};
use hurl_core::parser::parse_hurl_file;
use hurl_core::types::ToSource;

use std::ops::Range;

use super::entry::{
    BASE64_FILE_CT_MARKER, CommentAnchor, EntryComment, FormField, FormFieldKind, HurlEntry, KvRow,
    RunStatus, decode_body_line, parse_body_marker,
};
use super::json_comments;

/// Parse a Hurl-format string into a list of [`HurlEntry`] values.
///
/// Text that does not parse as a whole is not thrown away: see
/// [`recover_entries`]. The result is empty only for input with nothing in it
/// that looks like a request at all, which is how callers still recognise "this
/// file isn't a collection".
pub fn parse_hurl(content: &str) -> Vec<HurlEntry> {
    let Ok(file) = parse_hurl_file(content) else {
        return recover_entries(content);
    };
    let lines: Vec<&str> = content.lines().collect();
    // Each entry's `# [Reports]` comment block is recovered by scanning the raw
    // source within that entry's line window; the window ends at the next
    // entry's method line (or end-of-file for the last entry). We deliberately
    // use the next entry's *method* line, not its `source_info.start.line`:
    // `hurl_core` attaches an inter-entry comment block (which includes our
    // `# [Reports]` block) to the *following* entry's start, so a start-based
    // window would cut the block off from the entry it belongs to.
    let method_lines: Vec<usize> = file
        .entries
        .iter()
        .map(|e| first_method_line(&lines, e.request.source_info.start.line))
        .collect();
    file.entries
        .iter()
        .enumerate()
        .map(|(i, e)| {
            let end = method_lines.get(i + 1).copied().unwrap_or(lines.len() + 1);
            map_entry(e, &lines, method_lines[i], end, i == 0)
        })
        .collect()
}

/// Salvage what can be read from a file that does not parse.
///
/// A `.hurl` file is parsed as a whole, so one damaged request used to cost the
/// user every other request in the file: the load failed, the collection opened
/// as nothing, and the only way back in was a text editor. The damage is often
/// PaperBoy's own — a bad merge, a half-finished hand-edit, an escaping bug —
/// which makes "all or nothing" a poor trade.
///
/// So the file is cut into pieces at the lines that look like the start of a
/// request, and the pieces are parsed on their own. What parses becomes real
/// requests; what doesn't is kept verbatim as an unreadable one (see
/// [`HurlEntry::unreadable`]) so it is still visible, still saved unchanged,
/// and still repairable in Raw Mode.
///
/// The cut is a guess — a request body may contain a line that reads like a
/// method — so it is never trusted on its own. A piece that fails to parse is
/// retried with the piece after it joined on, and again with the one after
/// that, which is exactly what heals a body that was cut in half. Only when no
/// amount of joining helps is the piece declared unreadable, and even then only
/// the first piece is: the rest go back into the queue, so one broken request
/// cannot swallow the good ones behind it.
///
/// Every byte of `content` ends up in exactly one entry, in order. Nothing is
/// invented and nothing is dropped.
fn recover_entries(content: &str) -> Vec<HurlEntry> {
    let lines: Vec<&str> = content.split_inclusive('\n').collect();
    let starts = request_starts(&lines);
    if starts.is_empty() {
        return Vec::new();
    }
    // Anything above the first request start is a preamble — a banner comment,
    // or leading junk. It has no request to belong to, so it rides with the
    // first piece rather than becoming an unreadable entry of its own.
    let mut bounds: Vec<usize> = starts;
    bounds[0] = 0;
    bounds.push(lines.len());

    // How many pieces may be joined on while trying to heal one that was cut
    // off part-way. Small on purpose: joining is the fallback for a cut made in
    // the wrong place, and the cuts themselves are now chosen carefully enough
    // that it is rarely needed.
    const JOIN_LIMIT: usize = 8;

    let mut out: Vec<HurlEntry> = Vec::new();
    let mut i = 0;
    while i + 1 < bounds.len() {
        let alone = lines[bounds[i]..bounds[i + 1]].concat();
        let mut healed = None;
        match parse_hurl_file(&alone) {
            // A piece is cut so that it holds one whole request — response
            // line, sections and body included — so a piece that parses on its
            // own is taken as it stands.
            Ok(_) => {
                let entries = parse_hurl(&alone);
                if !entries.is_empty() {
                    healed = Some((entries, i + 1));
                }
            }
            // Joining the next piece on can only help a piece that was cut off
            // before it finished. An error anywhere but the last line is a
            // fault in the text itself, and no amount of text after it will
            // repair that — trying anyway is what made opening a large damaged
            // file take minutes rather than moments.
            Err(e) if e.pos.line >= alone.lines().count() => {
                // Longest first, so a body cut in several places is put back
                // together in one piece rather than in the first two.
                let far = bounds.len().min(i + 1 + JOIN_LIMIT);
                for j in (i + 2..far).rev() {
                    let text = lines[bounds[i]..bounds[j]].concat();
                    // Reparsing through `parse_hurl` (rather than using the
                    // AST here) is what recovers the `# [Reports]` and
                    // `# [Body]` blocks, which are read from the raw source and
                    // so need line numbers belonging to the piece being parsed
                    // rather than to the whole file.
                    if parse_hurl_file(&text).is_ok() {
                        let entries = parse_hurl(&text);
                        if !entries.is_empty() {
                            healed = Some((entries, j));
                            break;
                        }
                    }
                }
            }
            Err(_) => {}
        }
        match healed {
            Some((entries, j)) => {
                out.extend(entries);
                i = j;
            }
            None => {
                out.push(HurlEntry::unreadable(&alone));
                i += 1;
            }
        }
    }
    out
}

/// The line indices where a request looks like it begins: the contiguous
/// comment block above an HTTP method in capitals at the very start of a line,
/// followed by a URL.
///
/// Deliberately shallow. This decides only where to *try* cutting; whether the
/// cut was right is settled by parsing the result, so the rule can afford to be
/// generous. It does insist on column zero and on capitals, which is what keeps
/// it from firing on the indented `"GET /x"` inside a JSON body.
///
/// The cut is made above the comment block rather than at the method line
/// because that block is the request's name. Cutting below it would hand every
/// request's title to the request before it, and — where the cut lands next to
/// a piece that could not be read — bury it in text the user is being asked to
/// repair by hand.
fn request_starts(lines: &[&str]) -> Vec<usize> {
    let mut starts: Vec<usize> = Vec::new();
    let mut in_body = false;
    for (i, l) in lines.iter().enumerate() {
        // Inside a multiline body every line is data, and some data reads
        // exactly like a request: an HTTP log, a fixture, a list of routes.
        // Cutting there tears a healthy request's body apart, and — far worse —
        // leaves the fragments looking like requests in their own right, which
        // a "Run All" would then dutifully send to the server. A multiline body
        // is the only place in Hurl where arbitrary text can begin at column
        // zero, so tracking its fences is enough to rule that out.
        if l.trim_start().starts_with("```") {
            in_body = !in_body;
            continue;
        }
        if in_body || !looks_like_a_request_line(l) {
            continue;
        }
        let floor = starts.last().map(|&p| p + 1).unwrap_or(0);
        starts.push(title_block_top(lines, i, floor));
    }
    starts
}

/// Walk up from a method line over the comment block that names it, stopping at
/// a blank line, at the previous request, or at either of PaperBoy's own
/// comment-encoded blocks.
///
/// The blocks are the reason this is not a plain walk: `# [Reports]` and
/// `# [Body]` rows belong to the request *above*, and in a file laid out by
/// hand they can sit directly against the next method line with no blank
/// between. Taking them would move them into the following request, where they
/// would be read as its reports or its body. Where that is even a risk the
/// whole walk is abandoned and the cut stays at the method line: a misplaced
/// title is a cosmetic loss, a stolen block is a real one.
fn title_block_top(lines: &[&str], method: usize, floor: usize) -> usize {
    let mut top = method;
    while top > floor {
        let prev = lines[top - 1].trim();
        if !prev.starts_with('#') {
            break;
        }
        if is_reports_marker(prev) || parse_body_marker(prev).is_some() {
            return method;
        }
        top -= 1;
    }
    top
}

fn looks_like_a_request_line(line: &str) -> bool {
    let line = line.trim_end_matches(['\n', '\r']);
    if line.starts_with(char::is_whitespace) {
        return false;
    }
    let Some((method, rest)) = line.split_once(' ') else {
        return false;
    };
    // A response line is never the start of a request, however much it looks
    // like one — cutting there would separate every request from its own
    // response.
    if method == "HTTP" || method.starts_with("HTTP/") {
        return false;
    }
    // Hurl accepts any all-caps token as a method, so no fixed list is used —
    // a WebDAV or custom verb has to be able to start a request too.
    !method.is_empty()
        && method
            .chars()
            .all(|c| c.is_ascii_uppercase() || c == '-' || c == '_')
        && !rest.trim().is_empty()
}

/// The 1-based line number of an entry's HTTP-method line: the first
/// non-comment, non-blank line at or after `start_line` (which may itself be a
/// leading comment). Used to bound each entry's raw-source scan window.
fn first_method_line(lines: &[&str], start_line: usize) -> usize {
    (start_line.saturating_sub(1)..lines.len())
        .find(|&i| {
            let l = lines[i].trim();
            !l.is_empty() && !l.starts_with('#')
        })
        .map(|i| i + 1)
        .unwrap_or(lines.len() + 1)
}

/// Explain, in one short line, *why* `content` isn't valid Hurl — for the Raw
/// editor's "couldn't save" status, which is otherwise the unhelpfully generic
/// "expected exactly one request". Returns `None` when the text parses cleanly
/// (so any "wrong number of requests" problem is left to the caller).
///
/// The most common trip-up is putting `[Captures]`/`[Asserts]` on a request
/// with no `HTTP` response line: those are *response* sections, so `hurl_core`
/// rejects them as unknown *request* sections. We surface that case with a
/// concrete fix (`HTTP *` matches any status) rather than the raw parser jargon.
pub fn parse_hurl_error(content: &str) -> Option<String> {
    use hurl_core::error::DisplaySourceError;
    use hurl_core::parser::ParseErrorKind;
    let err = parse_hurl_file(content).err()?;
    let line = err.pos.line;
    let reason = match &err.kind {
        ParseErrorKind::RequestSectionName { name }
            if matches!(name.as_str(), "Captures" | "Asserts") =>
        {
            format!(
                "line {line}: [{name}] is a response section — add an 'HTTP' status line \
                 above it (use 'HTTP *' to accept any status)"
            )
        }
        ParseErrorKind::RequestSectionName { name } => {
            format!("line {line}: [{name}] is not a valid request section")
        }
        ParseErrorKind::Method { .. } => {
            format!("line {line}: expected an HTTP method (e.g. GET, POST)")
        }
        ParseErrorKind::Version => {
            format!("line {line}: a response line must be 'HTTP <status>' (e.g. 'HTTP 200')")
        }
        ParseErrorKind::Status => format!("line {line}: invalid status code"),
        ParseErrorKind::UrlInvalidStart | ParseErrorKind::UrlIllegalCharacter(_) => {
            format!("line {line}: invalid URL")
        }
        _ => format!("line {line}: {}", err.description().to_lowercase()),
    };
    Some(reason)
}

fn map_entry(
    e: &Entry,
    lines: &[&str],
    scan_start: usize,
    scan_end: usize,
    is_first: bool,
) -> HurlEntry {
    let req = &e.request;

    // Structural anchors that terminate the inline header block and bound each
    // request `[Section]`'s rows: the request body, any `[Section]` header, and
    // the response's `HTTP` status line. Each is strictly inside this entry and
    // *after* the headers, so a source scan bounded by the first anchor below a
    // block can never spill into the body, a later section, the response, or —
    // crucially — the following request. (We can't use `req.source_info.end`:
    // `hurl_core` excludes trailing comment lines from it, which would drop a
    // block's own trailing/all-disabled `# key: value` rows.)
    let mut anchors: Vec<usize> = req
        .sections
        .iter()
        .map(|s| s.source_info.start.line)
        .collect();
    if let Some(b) = &req.body {
        anchors.push(body_start_line(b));
    }
    if let Some(resp) = &e.response {
        anchors.push(resp.status.source_info.start.line);
    }

    // The same anchors, tagged with the block they open, drive prose-comment
    // recovery: a comment is attributed to the first block that begins below it
    // (see `scan_comments`).
    let mut landmarks: Vec<(usize, CommentAnchor)> = Vec::new();
    for section in &req.sections {
        let anchor = match &section.value {
            SectionValue::BasicAuth(_) => CommentAnchor::BasicAuth,
            SectionValue::Cookies(_) => CommentAnchor::Cookies,
            SectionValue::QueryParams(..) => CommentAnchor::Query,
            SectionValue::FormParams(..) | SectionValue::MultipartFormData(..) => {
                CommentAnchor::Form
            }
            SectionValue::Options(_) => CommentAnchor::Options,
            _ => continue,
        };
        landmarks.push((section.source_info.start.line, anchor));
    }
    if let Some(b) = &req.body {
        landmarks.push((body_start_line(b), CommentAnchor::Body));
    }
    if let Some(resp) = &e.response {
        let status_line = resp.status.source_info.start.line;
        landmarks.push((status_line, CommentAnchor::Response));
        // Response headers sit between the `HTTP <status>` line and the first
        // response block; anchor comments among them to `ResponseHeaders` when
        // there are any (enabled rows, or disabled ones recovered from source).
        if !resp.headers.is_empty()
            || scan_kv_rows(lines, status_line + 1, first_response_anchor(resp))
                .iter()
                .any(|r| !r.enabled)
        {
            landmarks.push((status_line + 1, CommentAnchor::ResponseHeaders));
        }
        for section in &resp.sections {
            let anchor = match &section.value {
                SectionValue::Asserts(_) => CommentAnchor::Asserts,
                SectionValue::Captures(_) => CommentAnchor::Captures,
                _ => continue,
            };
            landmarks.push((section.source_info.start.line, anchor));
        }
        if let Some(b) = &resp.body {
            landmarks.push((body_start_line(b), CommentAnchor::ResponseBody));
        }
    }
    landmarks.sort_by_key(|(line, _)| *line);

    // Each body's source line span keeps its multiline `#` lines out of
    // prose-comment recovery (both the request body and the expected response
    // body).
    let mut body_ranges: Vec<(usize, usize)> = Vec::new();
    if let Some(b) = &req.body {
        body_ranges.push(body_line_span(b));
    }
    if let Some(b) = e.response.as_ref().and_then(|r| r.body.as_ref()) {
        body_ranges.push(body_line_span(b));
    }

    let mut basic_auth = None;
    let mut form_fields = Vec::new();
    let mut query_params = Vec::new();
    let mut cookies = Vec::new();
    let mut options = Vec::new();
    for section in &req.sections {
        // Rows start on the line after the `[Section]` header and run up to the
        // next structural anchor below it (the following section / body /
        // response), or — for a trailing section with nothing after it — to the
        // end of the contiguous rows (see `scan_kv_rows`).
        let rows_start = section.source_info.start.line + 1;
        let rows_end = first_anchor_after(&anchors, section.source_info.start.line);
        match &section.value {
            SectionValue::BasicAuth(Some(kv)) => basic_auth = Some(kv_pair(kv)),
            SectionValue::FormParams(kvs, _) => {
                form_fields = form_fields_from_section(kvs, None, lines, rows_start, rows_end);
            }
            SectionValue::MultipartFormData(parts, _) => {
                form_fields =
                    form_fields_from_section(&[], Some(parts), lines, rows_start, rows_end);
            }
            // Headers live inline; Cookies/Query are `[Section]`s. All three are
            // scanned straight from source so a disabled row (kept as a
            // `# key: value` comment, invisible to `hurl_core`) round-trips.
            SectionValue::QueryParams(..) => {
                query_params = scan_kv_rows(lines, rows_start, rows_end)
            }
            SectionValue::Cookies(_) => cookies = scan_kv_rows(lines, rows_start, rows_end),
            // `[Options]` rows are `name: value` too (retry, insecure, …), so
            // the same scan recovers them — including disabled ones — verbatim.
            SectionValue::Options(_) => options = scan_kv_rows(lines, rows_start, rows_end),
            _ => {}
        }
    }

    let mut expected_status = None;
    let mut captures = Vec::new();
    let mut asserts = Vec::new();
    let mut response_version = None;
    let mut response_headers = Vec::new();
    let mut response_body = None;
    if let Some(resp) = &e.response {
        if let StatusValue::Specific(n) = resp.status.value {
            expected_status = Some(n as u16);
        }
        // The version-agnostic `HTTP` keyword (`VersionAny`) carries no explicit
        // version; anything else (`HTTP/1.1`, `HTTP/2`, …) is preserved verbatim.
        response_version = match resp.version.value {
            VersionValue::VersionAny => None,
            v => Some(v.to_string()),
        };
        // Response headers occupy the lines between the `HTTP <status>` line and
        // the first response block; scanning them (like request headers)
        // recovers disabled `# key: value` rows the AST drops as comments.
        response_headers = scan_kv_rows(
            lines,
            resp.status.source_info.start.line + 1,
            first_response_anchor(resp),
        );
        response_body = resp.body.as_ref().and_then(|b| body_source(b, lines));
        for section in &resp.sections {
            match &section.value {
                SectionValue::Captures(caps) => {
                    captures = caps.iter().filter_map(|c| capture_pair(c, lines)).collect();
                }
                SectionValue::Asserts(asrts) => {
                    asserts = asrts
                        .iter()
                        .filter_map(|a| source_line(a.query.source_info.start.line, lines))
                        .collect();
                }
                _ => {}
            }
        }
    }

    let is_multipart = form_fields
        .iter()
        .any(|f| f.enabled && f.kind.is_multipart());

    // The body as the file carries it, and the `# [Body]` block that still
    // describes it (if one does). A claimed block replaces the body with the
    // text it was authored from — comments and all — and its lines are then
    // spoken for, so neither the header scan below nor the prose-comment scan
    // may read them again.
    let file_body = req.body.as_ref().and_then(|b| body_source(b, lines));
    let claimed = claim_body_block(lines, scan_start, scan_end, file_body.as_deref());
    let claimed_range = claimed.as_ref().map(|(r, _)| r.clone());

    // A claimed block sits between the headers and the body, inside the window
    // the header scan would otherwise cover. Its lines can't currently be
    // mistaken for disabled `# key: value` rows — JSON keys are quoted, and a
    // quote is not a legal key start — but that is a property of another
    // module's validation, not of this one, so bound the scan explicitly rather
    // than rely on it.
    let url_line = req.url.source_info.start.line;
    let header_end = match (
        first_anchor_after(&anchors, url_line),
        claimed_range.as_ref().map(|r| r.start),
    ) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    };

    HurlEntry {
        // Stamped when the collection adopts these entries as its baseline.
        uid: 0,
        unparsed: None,
        title: title_from_span(req.source_info.start.line, lines),
        method: req.method.to_string(),
        url: req.url.to_source().to_string(),
        // Headers occupy the lines between the request line and the first
        // structural anchor (body / section / response). Scanning them (instead
        // of reading the AST) recovers disabled rows kept as `# key: value`
        // comments; the anchor bound keeps the scan inside this request.
        headers: scan_kv_rows(lines, url_line + 1, header_end),
        basic_auth,
        form_fields,
        is_multipart,
        queries: query_params,
        cookies,
        options,
        body_src: claimed.map(|(_, text)| text).or(file_body),
        expected_status,
        response_version,
        response_headers,
        response_body,
        captures,
        asserts,
        reports: reports_from_span(lines, scan_start, scan_end),
        comments: scan_comments(
            lines,
            &landmarks,
            &body_ranges,
            claimed_range,
            scan_start,
            scan_end,
            is_first,
        ),
        user_added: false,
        modified: false,
        last_run: RunStatus::default(),
        last_response: None,
    }
}

/// The first structural anchor inside a response strictly below its `HTTP`
/// status line — the earliest response `[Section]` header or the response
/// body's start — bounding the response-header scan. `None` (open mode) when a
/// response has no sections or body, so the header scan stops at the blank line
/// separating this entry from the next (see [`scan_kv_rows`]).
fn first_response_anchor(resp: &hurl_core::ast::Response) -> Option<usize> {
    resp.sections
        .iter()
        .map(|s| s.source_info.start.line)
        .chain(resp.body.as_ref().map(body_start_line))
        .min()
}

fn kv_pair(kv: &KeyValue) -> (String, String) {
    (
        kv.key.to_source().to_string(),
        kv.value.to_source().to_string(),
    )
}

/// The smallest structural anchor line strictly below `after` — i.e. the
/// exclusive upper bound of the source block that begins just under `after`
/// (the request line, for headers, or a `[Section]` header, for its rows).
/// `None` means "no anchor below here": a request with no body, sections or
/// response, or its final trailing section — in which case the block is scanned
/// in the bounded-open mode described on [`scan_kv_rows`].
fn first_anchor_after(anchors: &[usize], after: usize) -> Option<usize> {
    anchors.iter().copied().filter(|&a| a > after).min()
}

/// The 1-based line a request body starts on (its value, past any leading blank
/// lines) — the header block's lower boundary when a body is present.
fn body_start_line(b: &Body) -> usize {
    b.space0.source_info.start.line
}

/// The half-open 1-based line range `[start, end)` a request body occupies in
/// source. Used to keep body content out of prose-comment recovery: a
/// multiline-string body can contain lines that begin with `#`, which are body
/// text — not comments — and must not be captured (or duplicated) as such.
fn body_line_span(b: &Body) -> (usize, usize) {
    let start = body_start_line(b);
    // `line_terminator0` is the terminator right after the body value, so its
    // newline sits on the body's last source line.
    let end = b.line_terminator0.newline.source_info.start.line.max(start);
    (start, end + 1)
}

/// Recover prose comments from an entry's raw source so they aren't silently
/// dropped on load. `hurl_core` melts every comment into an opaque `Comment`
/// node, so — as with disabled rows and the `# [Reports]` block — we scan the
/// source lines ourselves. A comment line is captured unless it's already
/// represented elsewhere: this entry's own title block, the next entry's title
/// block, a disabled `# key: value` row inside a scanned rows region, the
/// `# [Reports]` block, or body content. Each captured comment is anchored to
/// the block it precedes (the first structural line below it — see
/// [`CommentAnchor`]) so it re-emits near its original place even as
/// surrounding lines change. `Lead` collects file-leading comments above the
/// first entry; `Trailing` collects comments below the last block.
fn scan_comments(
    lines: &[&str],
    landmarks: &[(usize, CommentAnchor)],
    body_ranges: &[(usize, usize)],
    body_block: Option<Range<usize>>,
    method_line: usize,
    scan_end: usize,
    is_first: bool,
) -> Vec<EntryComment> {
    #[derive(Clone, Copy)]
    enum RowKind {
        Kv,
        Form,
    }
    // Rows regions where a `# key: value` comment is a captured *disabled* row
    // (recovered by `scan_kv_rows`/`scan_disabled_form_rows`), not prose. These
    // mirror the row scans in `map_entry`: the inline header block, then each
    // Cookies/Query/Form/Options section's rows and the response-header block,
    // each bounded by the next landmark.
    let first_landmark = landmarks.first().map(|(l, _)| *l);
    let mut regions: Vec<(usize, usize, RowKind)> = vec![(
        method_line + 1,
        first_landmark.unwrap_or(scan_end),
        RowKind::Kv,
    )];
    for (k, (line, anchor)) in landmarks.iter().enumerate() {
        // Section landmarks point at the `[Section]` header line, so their rows
        // start one line below; the response-header landmark already points at
        // the first header row (there's no `[Header]` line above it).
        let (kind, rows_start) = match anchor {
            CommentAnchor::Cookies | CommentAnchor::Query | CommentAnchor::Options => {
                (RowKind::Kv, line + 1)
            }
            CommentAnchor::Form => (RowKind::Form, line + 1),
            CommentAnchor::ResponseHeaders => (RowKind::Kv, *line),
            _ => continue,
        };
        let end = landmarks.get(k + 1).map(|(l, _)| *l).unwrap_or(scan_end);
        regions.push((rows_start, end, kind));
    }

    let in_body = |line_no: usize| {
        body_ranges
            .iter()
            .any(|&(s, e)| line_no >= s && line_no < e)
    };

    // A comment line that the row scans already recover — either as a disabled
    // row (round-tripping via `headers`/`queries`/etc.) or as a row's `# @desc`
    // description — and so must not *also* be captured as prose, which would
    // duplicate it on the next save. Only meaningful for `#`-comment lines.
    let is_disabled_row = |line_no: usize| {
        let Some(&line) = lines.get(line_no.wrapping_sub(1)) else {
            return false;
        };
        regions.iter().any(|&(s, e, kind)| {
            line_no >= s
                && line_no < e
                && (desc_line(line).is_some()
                    || match kind {
                        RowKind::Kv => parse_kv_row(line).is_some(),
                        RowKind::Form => parse_form_field_line(uncomment(line).1, true).is_some(),
                    })
        })
    };

    // A "structural" line marks a block position for anchoring: body content, an
    // enabled row/section/response line, or a disabled row (which sits in its
    // block's rows). Prose comments, the reports block and title comments are
    // *not* structural — they float and take their anchor from the next
    // structural line below them.
    let is_structural = |line_no: usize| {
        if in_body(line_no) {
            return true;
        }
        let Some(&line) = lines.get(line_no.wrapping_sub(1)) else {
            return false;
        };
        let t = line.trim();
        if t.is_empty() {
            return false;
        }
        if !t.starts_with('#') {
            return true;
        }
        is_disabled_row(line_no)
    };

    // The anchor for a structural line at `l2`: the block it belongs to — the
    // greatest landmark at/above it, or `Headers` when it's in the inline header
    // block (above the first landmark).
    let anchor_of_line = |l2: usize| match first_landmark {
        Some(fl) if l2 >= fl => landmarks
            .iter()
            .rev()
            .find(|(l, _)| *l <= l2)
            .map_or(CommentAnchor::Headers, |(_, a)| *a),
        _ => CommentAnchor::Headers,
    };

    // A prose comment is anchored to the first structural line below it (so it
    // precedes that block), or `Trailing` when nothing structural follows.
    let anchor_for_comment = |line_no: usize| {
        (line_no + 1..scan_end)
            .find(|&l2| is_structural(l2))
            .map_or(CommentAnchor::Trailing, anchor_of_line)
    };

    // Lines already claimed elsewhere: the `# [Reports]` block …
    let reports_block = {
        let to = scan_end.min(lines.len() + 1);
        let marker =
            (method_line..to).find(|&i| lines.get(i - 1).is_some_and(|l| is_reports_marker(l)));
        marker.map_or(0..0, |m| {
            let mut j = m + 1;
            while j < to && lines.get(j - 1).and_then(|l| parse_report_row(l)).is_some() {
                j += 1;
            }
            m..j
        })
    };
    // … and the next entry's title block (the contiguous comment lines directly
    // above the next entry's method line, which `title_from_span` will claim as
    // that entry's title). Only when there *is* a next entry in the window.
    let next_title = if scan_end <= lines.len() {
        let mut top = scan_end;
        let mut idx = scan_end - 1;
        while idx >= method_line
            && lines
                .get(idx - 1)
                .is_some_and(|l| l.trim().starts_with('#'))
        {
            top = idx;
            idx -= 1;
        }
        top..scan_end
    } else {
        0..0
    };

    let mut out = Vec::new();

    // File-leading comments above the very first entry (everything above this
    // entry's own title block), kept as `Lead`.
    if is_first {
        let mut title_top = method_line;
        let mut idx = method_line.wrapping_sub(1);
        while idx >= 1
            && lines
                .get(idx - 1)
                .is_some_and(|l| l.trim().starts_with('#'))
        {
            title_top = idx;
            idx -= 1;
        }
        for ln in 1..title_top {
            if let Some(t) = lines
                .get(ln - 1)
                .map(|l| l.trim())
                .filter(|t| t.starts_with('#'))
            {
                out.push(EntryComment {
                    anchor: CommentAnchor::Lead,
                    text: t.to_string(),
                });
            }
        }
    }

    for line_no in method_line..scan_end.min(lines.len() + 1) {
        let Some(t) = lines.get(line_no - 1).map(|l| l.trim()) else {
            break;
        };
        if !t.starts_with('#')
            || in_body(line_no)
            || is_disabled_row(line_no)
            || reports_block.contains(&line_no)
            || body_block.as_ref().is_some_and(|r| r.contains(&line_no))
            || next_title.contains(&line_no)
        {
            continue;
        }
        out.push(EntryComment {
            anchor: anchor_for_comment(line_no),
            text: t.to_string(),
        });
    }
    out
}

/// Scan a block of `key: value` request-section rows starting at 1-based line
/// `start`, returning each as a `(key, value, enabled)` triple. A row commented
/// out with a leading `#` comes back as a disabled entry — this is how
/// [`to_hurl`](super::entry::HurlEntry::to_hurl) round-trips disabled Header,
/// Cookies and Query rows, which `hurl_core` drops as comments before they ever
/// reach the AST.
///
/// A `# @desc …` line immediately above a row becomes that row's
/// [`KvRow::desc`] rather than a row of its own; consecutive marker lines are
/// the successive lines of one note.
///
/// `end` is the block's exclusive upper bound — the next structural anchor
/// below it (body / section / response), from [`first_anchor_after`]. It drives
/// two scan modes that together match `hurl_core` without ever reading rows
/// from the *next* request:
///
/// * **Bounded** (`Some(end)`): scan the half-open window `[start, end)`,
///   collecting every `key: value` row and *skipping* blank lines and prose
///   comments in between (including any leading ones, right after the request
///   or section header). This mirrors `hurl_core`, which tolerates blank and
///   comment lines interspersed among headers/section rows. Because `end` is an
///   anchor strictly inside this entry, the window can't reach the next one.
///
/// * **Open** (`None`): a request with no body, section or response (or its
///   last trailing section) has no anchor below it, so there's nothing bounding
///   the window from the following entry. Here the scan stops at the *first*
///   non-row line — including a leading blank line — so it halts at the blank
///   that separates this entry from the next rather than skipping across it and
///   absorbing that entry's leading comments/title as stray rows.
fn scan_kv_rows(lines: &[&str], start: usize, end: Option<usize>) -> Vec<KvRow> {
    let mut rows: Vec<KvRow> = Vec::new();
    // Description lines accumulated since the last row: a `# @desc …` block
    // belongs to the row *below* it, and several of them are the successive
    // lines of one multi-line note.
    let mut pending_desc: Vec<String> = Vec::new();
    let mut i = start.saturating_sub(1);
    let limit = end.map(|e| e.saturating_sub(1)).unwrap_or(lines.len());
    while i < limit {
        let Some(&line) = lines.get(i) else { break };
        if let Some(text) = desc_line(line) {
            pending_desc.push(text.to_string());
            i += 1;
            continue;
        }
        match parse_kv_row(line) {
            Some(mut row) => {
                row.desc = std::mem::take(&mut pending_desc).join("\n");
                rows.push(row);
            }
            // Bounded: skip a blank/prose line (leading or interior) and keep
            // scanning — the anchor keeps us inside this entry. Open: stop, so
            // we never cross into the next request's leading comments.
            None if end.is_some() => {
                // A note followed by prose rather than a row describes nothing;
                // drop it so it can't leap onto an unrelated later row.
                pending_desc.clear();
            }
            None => break,
        }
        i += 1;
    }
    rows
}

/// The text of a `# @desc …` description line, or `None` for anything else.
/// Whitespace before the `#` is tolerated so an indented note still reads.
pub(crate) fn desc_line(line: &str) -> Option<&str> {
    let trimmed = line.trim_start();
    let rest = trimmed.strip_prefix(crate::hurl::entry::DESC_MARKER.trim_end())?;
    // Require the marker to be followed by a separator (or nothing), so a
    // comment like `# @description of the API` isn't mistaken for one.
    match rest.strip_prefix(' ') {
        Some(text) => Some(text.trim_end()),
        None if rest.is_empty() => Some(""),
        None => None,
    }
}

/// Parse a single Header/Cookies/Query row into a [`KvRow`] (without its
/// description, which the caller attaches from the `# @desc` lines above it).
/// `enabled` is `false` when the line is commented out (`# key: value`). The
/// key must start with an alphanumeric and contain only token characters, so a
/// JSON body line, a `[Section]` header, an `HTTP` status line or a prose
/// comment all fail to parse (ending a scan) instead of being mistaken for a
/// row.
fn parse_kv_row(line: &str) -> Option<KvRow> {
    let (enabled, rest) = uncomment(line);
    let (key, value) = split_kv(rest)?;
    Some(KvRow::toggled(key, value, enabled))
}

/// Strip a leading `#` (marking a disabled/commented request row) and the
/// surrounding whitespace, returning `(enabled, remaining_text)`.
fn uncomment(line: &str) -> (bool, &str) {
    let trimmed = line.trim();
    match trimmed.strip_prefix('#') {
        Some(rest) => (false, rest.trim_start()),
        None => (true, trimmed),
    }
}

/// Split a `key: value` line into its trimmed key and value, requiring the key
/// to be a name Hurl can carry. The test is
/// [`key_problem`](crate::hurl::key_problem) — the *same* one the writer
/// enforces, so a row that can be written can always be read back. Returns
/// `None` for anything else, which is also what keeps an ordinary prose comment
/// (`# see also: the docs`) from being mistaken for a disabled row.
fn split_kv(text: &str) -> Option<(&str, &str)> {
    let colon = text.find(':')?;
    let key = text[..colon].trim();
    if crate::hurl::key_problem(key).is_some() {
        return None;
    }
    Some((key, text[colon + 1..].trim()))
}

/// Build the ordered `form_fields` for a `[Form]` (pass `kvs`) or `[Multipart]`
/// (pass `parts`) section. Enabled rows are taken from the parsed AST, which
/// decodes filename escapes and the Base64File marker robustly; disabled rows
/// (kept as `# …` comments, invisible to `hurl_core`) are recovered by
/// scanning the section's source lines. The two are merged by line number so
/// the user's original row order is preserved.
fn form_fields_from_section(
    kvs: &[KeyValue],
    parts: Option<&[MultipartParam]>,
    lines: &[&str],
    rows_start: usize,
    rows_end: Option<usize>,
) -> Vec<FormField> {
    let mut rows: Vec<(usize, FormField)> = Vec::new();
    if let Some(parts) = parts {
        for p in parts {
            rows.push((multipart_param_line(p), multipart_field(p)));
        }
    } else {
        for kv in kvs {
            rows.push((
                kv.key.source_info.start.line,
                FormField {
                    key: kv.key.to_source().to_string(),
                    value: kv.value.to_source().to_string(),
                    kind: FormFieldKind::Text,
                    content_type: None,
                    base64_prefix: None,
                    enabled: true,
                    desc: String::new(),
                },
            ));
        }
    }
    rows.extend(scan_disabled_form_rows(lines, rows_start, rows_end));
    rows.sort_by_key(|(line, _)| *line);
    // Descriptions are matched to rows by line: unlike the kv sections, form
    // rows come from two sources (the AST for enabled rows, a source scan for
    // disabled ones), so a single scan of the `# @desc` lines and the line each
    // one sits above is what joins them back up.
    let descs = scan_row_descriptions(lines, rows_start, rows_end);
    rows.into_iter()
        .map(|(line, mut f)| {
            if let Some(desc) = descs.get(&line) {
                f.desc = desc.clone();
            }
            f
        })
        .collect()
}

/// Map each row line in `[start, end)` to the description written on the
/// `# @desc …` line(s) directly above it. Lines with no note aren't in the map.
fn scan_row_descriptions(
    lines: &[&str],
    start: usize,
    end: Option<usize>,
) -> std::collections::HashMap<usize, String> {
    let mut out = std::collections::HashMap::new();
    let mut pending: Vec<String> = Vec::new();
    let mut i = start.saturating_sub(1);
    let limit = end.map(|e| e.saturating_sub(1)).unwrap_or(lines.len());
    while i < limit {
        let Some(&line) = lines.get(i) else { break };
        match desc_line(line) {
            Some(text) => pending.push(text.to_string()),
            None if !pending.is_empty() => {
                out.insert(i + 1, std::mem::take(&mut pending).join("\n"));
            }
            None => {}
        }
        i += 1;
    }
    out
}

/// The 1-based source line a `[Multipart]` row starts on.
fn multipart_param_line(p: &MultipartParam) -> usize {
    match p {
        MultipartParam::Param(kv) => kv.key.source_info.start.line,
        MultipartParam::FilenameParam(fp) => fp.key.source_info.start.line,
    }
}

/// Walk a `[Form]`/`[Multipart]` section from `start`, collecting the
/// `(line, field)` for each **disabled** (`# …`) row. Enabled rows are stepped
/// over (they come from the AST). `end` is the section's exclusive upper bound
/// (the next structural anchor, from [`first_anchor_after`]) and drives the same
/// two scan modes as [`scan_kv_rows`]: **bounded** (`Some`) skips interior
/// blanks and prose within `[start, end)`; **open** (`None`, a trailing section
/// with nothing below it) skips only leading blanks and then stops at the first
/// non-row line, so the walk never runs into the following request.
///
/// Disabled rows are parsed as file-capable regardless of the section type:
/// a disabled `File`/`Base64File` field is always serialized with the
/// `file,…` syntax (even inside an otherwise text-only `[Form]`, since the
/// section type is chosen from the enabled fields alone), so parsing it back
/// as a file is what restores its original kind.
fn scan_disabled_form_rows(
    lines: &[&str],
    start: usize,
    end: Option<usize>,
) -> Vec<(usize, FormField)> {
    let mut out = Vec::new();
    let mut i = start.saturating_sub(1);
    let limit = end.map(|e| e.saturating_sub(1)).unwrap_or(lines.len());
    while i < limit {
        let Some(&line) = lines.get(i) else { break };
        // A description line is an annotation on the row below, not a row (and
        // not prose that should stop an open-mode scan).
        if desc_line(line).is_some() {
            i += 1;
            continue;
        }
        let (enabled, rest) = uncomment(line);
        match parse_form_field_line(rest, true) {
            Some(mut field) if !enabled => {
                field.enabled = false;
                out.push((i + 1, field));
            }
            // An enabled row (already captured from the AST): step over it.
            Some(_) => {}
            // Bounded: skip a blank/prose line (leading or interior) and keep
            // scanning. Open: stop, so the walk can't reach the next request.
            None if end.is_some() => {}
            None => break,
        }
        i += 1;
    }
    out
}

/// Parse one `[Form]`/`[Multipart]` field line body (the text after any
/// disabled-row `# `). In a `[Multipart]` section a `file,PATH;CT` value is a
/// file upload (a PaperBoy marker restores a Base64File); every other value,
/// and every `[Form]` value, is plain text. Returns `None` when the line isn't
/// a field row (so a scan can tell where the section ends).
fn parse_form_field_line(body: &str, multipart: bool) -> Option<FormField> {
    let (key, value) = split_kv(body)?;
    if multipart && let Some(spec) = value.strip_prefix("file,") {
        return Some(parse_file_form_value(key, spec));
    }
    Some(FormField {
        key: key.to_string(),
        value: value.to_string(),
        kind: FormFieldKind::Text,
        content_type: None,
        base64_prefix: None,
        enabled: true,
        desc: String::new(),
    })
}

/// Parse the `PATH; CONTENT-TYPE` part of a `[Multipart]` `file,…` value into a
/// `File`/`Base64File` field, reversing [`escape_form_file_path`] on the path.
///
/// Also reachable from a report's `USING(multipart.x = …)` override, which has
/// to read the same spelling for the same reason a `.hurl` file does.
pub(crate) fn parse_file_form_value(key: &str, spec: &str) -> FormField {
    let (escaped_path, ct) = split_unescaped_semicolon(spec);
    let path = unescape_form_file_path(escaped_path);
    let ct = ct.trim();
    if let Some(encoded) = ct.strip_prefix(BASE64_FILE_CT_MARKER) {
        let prefix = URL_SAFE_NO_PAD
            .decode(encoded)
            .ok()
            .and_then(|bytes| String::from_utf8(bytes).ok())
            .unwrap_or_default();
        return FormField {
            key: key.to_string(),
            value: path,
            kind: FormFieldKind::Base64File,
            content_type: None,
            base64_prefix: Some(prefix),
            enabled: true,
            desc: String::new(),
        };
    }
    FormField {
        key: key.to_string(),
        value: path,
        kind: FormFieldKind::File,
        content_type: (!ct.is_empty()).then(|| ct.to_string()),
        base64_prefix: None,
        enabled: true,
        desc: String::new(),
    }
}

/// Split at the first non-escaped `;` (the separator between a file path and
/// its content-type), returning `(path, rest)`; the whole string as `path`
/// when there's no separator.
fn split_unescaped_semicolon(spec: &str) -> (&str, &str) {
    let bytes = spec.as_bytes();
    let mut escaped = false;
    for (i, &b) in bytes.iter().enumerate() {
        if escaped {
            escaped = false;
        } else if b == b'\\' {
            escaped = true;
        } else if b == b';' {
            return (&spec[..i], &spec[i + 1..]);
        }
    }
    (spec, "")
}

/// Reverse [`escape_form_file_path`]: turn a Hurl filename token back into a
/// real filesystem path (`\ ` → space, `\n`/`\r` → newlines, `\x` → `x`).
fn unescape_form_file_path(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('n') => out.push('\n'),
                Some('r') => out.push('\r'),
                Some(other) => out.push(other),
                None => out.push('\\'),
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// A `[Multipart]` row: a plain text field, or a file field (`key:
/// file,path;content-type`, content-type optional).
fn multipart_field(p: &MultipartParam) -> FormField {
    match p {
        MultipartParam::Param(kv) => FormField {
            key: kv.key.to_source().to_string(),
            value: kv.value.to_source().to_string(),
            kind: FormFieldKind::Text,
            content_type: None,
            base64_prefix: None,
            enabled: true,
            desc: String::new(),
        },
        MultipartParam::FilenameParam(fp) => {
            let content_type = fp
                .value
                .content_type
                .as_ref()
                .map(|t| t.to_source().to_string());
            // A PaperBoy-marked content-type means this was a Base64File on
            // save (Hurl has no native base64-file concept). Restore the
            // Base64File kind and decode its URL-safe-base64 prefix; a bad
            // encoding degrades gracefully to an empty prefix.
            if let Some(encoded) = content_type
                .as_deref()
                .and_then(|ct| ct.strip_prefix(BASE64_FILE_CT_MARKER))
            {
                let prefix = URL_SAFE_NO_PAD
                    .decode(encoded)
                    .ok()
                    .and_then(|bytes| String::from_utf8(bytes).ok())
                    .unwrap_or_default();
                return FormField {
                    key: fp.key.to_source().to_string(),
                    value: fp.value.filename.to_string(),
                    kind: FormFieldKind::Base64File,
                    content_type: None,
                    base64_prefix: Some(prefix),
                    enabled: true,
                    desc: String::new(),
                };
            }
            FormField {
                key: fp.key.to_source().to_string(),
                // The decoded filename (spaces and other escapes resolved), so it
                // matches a real filesystem path — the same form the file picker
                // stores. Re-escaping happens on the way back out (see
                // `entry.rs`'s `escape_form_file_path`).
                value: fp.value.filename.to_string(),
                kind: FormFieldKind::File,
                content_type,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            }
        }
    }
}

/// Render a request or response body back to its Hurl source form.
///
/// `file,…;` and `base64,…;` bodies have no textual value to render, so they
/// are recovered from the source line itself. Returning `None` for them (as
/// this did) is indistinguishable from "this request has no body", and since
/// [`collection_to_hurl`](super::entry::collection_to_hurl) rewrites *every*
/// entry on every save — not just the edited one — a single save anywhere in
/// the collection silently deleted the body line of every such request, with
/// no parse error and no change in entry count to hint at it.
///
/// Both forms are a single line and carry a source span, so `source_line`
/// gives them back verbatim and the round trip is byte-stable.
fn body_source(b: &Body, lines: &[&str]) -> Option<String> {
    let s = match &b.value {
        Bytes::Json(v) => v.to_source().to_string(),
        Bytes::Xml(x) => x.clone(),
        Bytes::OnelineString(t) => t.to_source().to_string(),
        Bytes::MultilineString(m) => m.to_source().to_string(),
        Bytes::Hex(h) => h.to_string(),
        Bytes::Base64(x) => source_line(x.space0.source_info.start.line, lines)?,
        Bytes::File(x) => source_line(x.space0.source_info.start.line, lines)?,
    };
    let s = s.trim().to_string();
    (!s.is_empty()).then_some(s)
}

/// The trimmed source line at 1-based `line`, if non-empty.
fn source_line(line: usize, lines: &[&str]) -> Option<String> {
    let idx = line.checked_sub(1)?;
    lines
        .get(idx)
        .map(|l| l.trim().to_string())
        .filter(|l| !l.is_empty())
}

/// A `[Captures]` line "name: query …" split into (name, expression).
fn capture_pair(c: &Capture, lines: &[&str]) -> Option<(String, String)> {
    let line = source_line(c.query.source_info.start.line, lines)?;
    let (name, expr) = line.split_once(':')?;
    Some((name.trim().to_string(), expr.trim().to_string()))
}

/// Recover a request's PaperBoy `# [Reports]` block from raw source, within the
/// entry's 1-based line window `[start, end)`. A real `[Reports]` response
/// section is a non-recoverable `hurl_core` parse error, so report-field
/// definitions are round-tripped as comments (see [`HurlEntry::to_hurl`]): the
/// `# [Reports]` marker followed by contiguous `# name: query` rows. Scanning
/// stops at the first line that isn't such a row (a blank line, a real section,
/// or a prose comment), mirroring the disabled-row scan.
fn reports_from_span(lines: &[&str], start: usize, end: usize) -> Vec<(String, String)> {
    let from = start.saturating_sub(1);
    let to = end.saturating_sub(1).min(lines.len());
    let mut reports = Vec::new();
    let mut i = from;
    // Locate the marker.
    while i < to {
        if is_reports_marker(lines[i]) {
            i += 1;
            break;
        }
        i += 1;
    }
    // Collect the contiguous `# name: query` rows that follow it.
    while i < to {
        match parse_report_row(lines[i]) {
            Some(row) => reports.push(row),
            None => break,
        }
        i += 1;
    }
    reports
}

/// Find every `# [Body]` block candidate in an entry's source window, as
/// `(claimed line range, decoded body text)`.
///
/// Every candidate is offered, including ones nested inside another, and the
/// cursor advances a line at a time rather than jumping past a block it just
/// matched. Being *well-formed* only means the count matches the lines below
/// it; whether a block is the real one is decided later, by reconciling it
/// against the body. A stale block whose count happens to span the good block
/// underneath it would otherwise hide it completely — the good block would
/// never be offered, and a request whose notes were perfectly correct would
/// quietly stop carrying them.
///
/// A block whose count doesn't describe the lines below it is not a candidate
/// at all. Its lines fall to the ordinary prose-comment scan, which round-trips
/// them verbatim — so a damaged block degrades to exactly what a `.hurl` file
/// did before this feature existed, and the user's notes survive even when we
/// can no longer tell what they described.
fn body_blocks(lines: &[&str], from: usize, to: usize) -> Vec<(Range<usize>, String)> {
    let hi = to.min(lines.len() + 1);
    let mut out = Vec::new();
    for i in from..hi {
        let Some(n) = lines
            .get(i.wrapping_sub(1))
            .and_then(|l| parse_body_marker(l))
        else {
            continue;
        };
        // The count comes out of a file that may have been hand-edited or
        // badly merged, so the arithmetic is checked. Left to wrap, a count
        // near `usize::MAX` produces a range ending before it starts, which
        // reads as well-formed and claims nothing.
        let Some(end) = i.checked_add(1).and_then(|e| e.checked_add(n)) else {
            continue;
        };
        let well_formed = end <= hi
            && (i + 1..end).all(|j| {
                lines
                    .get(j - 1)
                    .is_some_and(|l| l.trim_start().starts_with('#'))
            });
        if well_formed {
            let text = (i + 1..end)
                .map(|j| decode_body_line(lines[j - 1]))
                .collect::<Vec<_>>()
                .join("\n");
            out.push((i..end, text));
        }
    }
    out
}

/// The `# [Body]` block that still describes `body`, if any.
///
/// A block is only believed when stripping its comments yields the body the
/// file actually carries. Anything else means something other than PaperBoy
/// edited one of the two and they no longer agree — in which case the body in
/// the file wins (it is what runs, and what every other tool sees) and the
/// block is left unclaimed, surviving as prose comments rather than being
/// deleted on the user's behalf.
///
/// The comparison asks the writer's own question — "does this block derive the
/// body in the file?" — by running the same `wire_body` the file was written
/// with, rather than a stripped approximation of it. Anything less and a block
/// that legitimately produced the body (one that commented out a last field,
/// say, and so shed a trailing comma) would fail to reconcile and orphan every
/// comment in it.
///
/// The comparison is semantic rather than byte-for-byte so that a reformat, or
/// a re-ordering of keys, doesn't orphan every comment in the request over
/// whitespace that changes nothing about what gets sent.
fn claim_body_block(
    lines: &[&str],
    from: usize,
    to: usize,
    body: Option<&str>,
) -> Option<(Range<usize>, String)> {
    let body = body?;
    body_blocks(lines, from, to)
        .into_iter()
        .find(|(_, text)| json_comments::bodies_equivalent(&json_comments::wire_body(text), body))
}

/// `true` when `line` is the `# [Reports]` block marker (leading whitespace and
/// the comment `#` allowed, case-insensitive on the section name).
fn is_reports_marker(line: &str) -> bool {
    line.trim_start()
        .strip_prefix('#')
        .map(str::trim)
        .is_some_and(|rest| rest.eq_ignore_ascii_case("[Reports]"))
}

/// Parse one `# name: query` report row into `(name, query)`. `name` must be a
/// single identifier-like token (alphanumeric / `_` / `-`) so a prose comment
/// (which may contain a colon) doesn't get mistaken for a report field.
fn parse_report_row(line: &str) -> Option<(String, String)> {
    let rest = line.trim_start().strip_prefix('#')?.trim_start();
    if rest.starts_with('[') {
        return None;
    }
    let (name, query) = rest.split_once(':')?;
    let name = name.trim();
    let query = query.trim();
    if name.is_empty()
        || query.is_empty()
        || !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    {
        return None;
    }
    Some((name.to_string(), query.to_string()))
}

/// Title = the `#` comment lines immediately above the request's method line
/// (reset by a blank line), with `#` and surrounding `-`/`=` decoration
/// stripped — `# ---- Login ----` is titled "Login". Only the leading and
/// trailing runs go: a hyphen or `=` *inside* the text is part of the name
/// ("Get user-profile"), and stripping those made our own output unreadable
/// by our own parser, permanently corrupting the name on the next save. The
/// entry's `source_info.start` is sometimes the leading comment and sometimes
/// the method line (depending on how `hurl_core` attaches inter-entry
/// comments), so we first locate the method line, then scan back for its block.
fn title_from_span(start_line: usize, lines: &[&str]) -> String {
    // The method line: first non-comment, non-blank line at/after the start.
    let method = (start_line.saturating_sub(1)..lines.len())
        .find(|&i| {
            let l = lines[i].trim();
            !l.is_empty() && !l.starts_with('#')
        })
        .unwrap_or(lines.len());
    // The contiguous comment block directly above it (bounded below by the
    // last blank or content line, which ends the block).
    let block_start = lines[..method]
        .iter()
        .rposition(|l| !l.trim().starts_with('#'))
        .map_or(0, |i| i + 1);
    lines[block_start..method]
        .iter()
        .map(|l| {
            l.trim_start_matches('#')
                .trim()
                .trim_matches(|c| matches!(c, '-' | '='))
                .trim()
                .to_string()
        })
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::super::entry::collection_to_hurl;
    use super::*;

    #[test]
    fn parse_error_explains_captures_needing_a_response_line() {
        // `[Captures]` on a request with no `HTTP` line is the classic trip-up:
        // it's a *response* section, so hurl_core rejects it as an unknown
        // request section. The message must name the section and the fix.
        let content =
            "# Get token\nPOST http://h/oauth2\n[Captures]\naccess_token: jsonpath \"$.token\"\n";
        // Unparseable, so recovery carries it as text rather than as a
        // request — the reason below is what tells the user why.
        let recovered = parse_hurl(content);
        assert!(recovered.iter().all(|e| e.is_unreadable()));
        let why = parse_hurl_error(content).expect("a reason is produced");
        assert!(
            why.contains("Captures"),
            "names the offending section: {why}"
        );
        assert!(
            why.contains("HTTP"),
            "points at the missing response line: {why}"
        );
        assert!(why.contains("line 3"), "cites the line: {why}");
    }

    #[test]
    fn parse_error_is_none_for_valid_hurl() {
        let content = "GET http://h/x\nHTTP 200\n[Captures]\ntok: jsonpath \"$.t\"\n";
        assert_eq!(parse_hurl(content).len(), 1);
        assert!(parse_hurl_error(content).is_none());
    }

    #[test]
    fn body_terminates_at_http_so_later_entries_parse() {
        let content = "# First\nPOST http://x/a\nContent-Type: application/json\n{\n  \"k\": \"v\"\n}\nHTTP 200\n\n# Second\nGET http://x/b\nAccept: application/json\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 2, "the body must not swallow the second entry");
        assert_eq!(e[0].body_src.as_deref(), Some("{\n  \"k\": \"v\"\n}"));
        assert_eq!(e[1].method, "GET");
        assert!(e[1].body_src.is_none());
    }

    #[test]
    fn blank_line_before_headers_does_not_drop_them() {
        // Hurl allows a blank line between the request line and the header
        // block; hurl_core parses the headers, but PaperBoy's source-scan used
        // to read that first blank line as "no headers". The scan must skip the
        // leading blank line(s) and still recover every header.
        let content = "# Get token\nPOST {{ URL }}/oauth2\n\nContent-Length: 0\nUser-Agent: crabman/0.1.0\nAccept: */*\nclient_id: {{ CLIENT_ID }}\n\nHTTP 200\n[Captures]\naccess_token: jsonpath \"$.token\"\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(
            e[0].headers,
            vec![
                ("Content-Length".into(), "0".into(), true),
                ("User-Agent".into(), "crabman/0.1.0".into(), true),
                ("Accept".into(), "*/*".into(), true),
                ("client_id".into(), "{{ CLIENT_ID }}".into(), true),
            ],
            "a blank line after the request line must not drop the headers"
        );
    }

    #[test]
    fn blank_line_before_headers_without_body_leaves_headers_intact() {
        // The no-body variant: skipping the leading blank must not run off into
        // the response line and invent rows either.
        let content = "GET http://h/x\n\nAccept: application/json\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(
            e[0].headers,
            vec![("Accept".into(), "application/json".into(), true)]
        );
        assert!(e[0].body_src.is_none());
    }

    #[test]
    fn blank_line_before_json_body_with_no_headers_stays_empty() {
        // No headers, a blank line, then a JSON body: skipping the leading blank
        // must not misread the body's first line as a header row.
        let content = "POST http://h/x\n\n{\n  \"k\": \"v\"\n}\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert!(e[0].headers.is_empty(), "the JSON body is not a header");
        assert_eq!(e[0].body_src.as_deref(), Some("{\n  \"k\": \"v\"\n}"));
    }

    #[test]
    fn blank_line_after_section_header_keeps_rows() {
        // The same blank-line tolerance must apply to the `[Cookies]` and
        // `[QueryStringParams]` sections, which share the source-scan helper.
        let content = "GET http://h/x\n[QueryStringParams]\n\npage: 1\nsize: 20\n[Cookies]\n\ntheme: dark\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(
            e[0].queries,
            vec![
                ("page".into(), "1".into(), true),
                ("size".into(), "20".into(), true),
            ]
        );
        assert_eq!(e[0].cookies, vec![("theme".into(), "dark".into(), true)]);
    }

    #[test]
    fn blank_and_comment_lines_between_headers_are_tolerated() {
        // hurl_core keeps headers separated by interior blank lines and prose
        // comments; the bounded scan (up to the HTTP line) must match it.
        let content = "GET http://h/x\nAccept: 1\n\n# a prose note\nContent-Type: 2\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(
            e[0].headers,
            vec![
                ("Accept".into(), "1".into(), true),
                ("Content-Type".into(), "2".into(), true),
            ],
            "an interior blank + prose comment must not truncate the header block"
        );
    }

    #[test]
    fn comment_before_first_header_is_skipped() {
        let content = "GET http://h/x\n# leading note\nAccept: 1\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(e[0].headers, vec![("Accept".into(), "1".into(), true)]);
    }

    #[test]
    fn trailing_and_all_disabled_headers_before_http_are_recovered() {
        // Disabled rows kept as `# key: value` comments sit between the enabled
        // headers and the HTTP line. hurl_core excludes them from the request's
        // source span, so the scan must bound the block by the HTTP line, not by
        // that span, or these rows would be silently dropped.
        let trailing = "GET http://h/x\nAccept: 1\n# X-Debug: on\nHTTP 200\n";
        let e = parse_hurl(trailing);
        assert_eq!(
            e[0].headers,
            vec![
                ("Accept".into(), "1".into(), true),
                ("X-Debug".into(), "on".into(), false),
            ]
        );

        let all_disabled = "GET http://h/x\n# A: 1\n# B: 2\nHTTP 200\n";
        let e = parse_hurl(all_disabled);
        assert_eq!(
            e[0].headers,
            vec![
                ("A".into(), "1".into(), false),
                ("B".into(), "2".into(), false),
            ]
        );
    }

    #[test]
    fn a_blank_line_header_scan_never_bleeds_into_the_next_request() {
        // A request with no body/section/response has no structural anchor below
        // its headers, so the scan runs in "open" mode: it must stop at the
        // blank line separating it from the next entry and must NOT absorb that
        // entry's banner as a disabled header of the first one.
        let content = "GET http://h/a\nAccept: 1\n\n# X-Not-Mine: v\nGET http://h/b\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 2);
        assert_eq!(
            e[0].headers,
            vec![("Accept".into(), "1".into(), true)],
            "the second entry's banner must not leak into the first entry's headers"
        );
    }

    #[test]
    fn open_mode_zero_header_request_does_not_absorb_next_entrys_comment() {
        // Regression: an entry with NO headers, body, section or response scans
        // in open mode starting at the blank separator line. It must stop at
        // that blank rather than skipping it and reading the following entry's
        // leading `# key: value`-shaped comment as a disabled header of its own.
        let content =
            "GET http://api/health\n\n# TODO: fix auth below\nPOST http://api/login\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 2);
        assert!(
            e[0].headers.is_empty(),
            "a zero-header request must not absorb the next entry's comment: {:?}",
            e[0].headers
        );
    }

    #[test]
    fn all_disabled_and_trailing_section_rows_before_http_are_recovered() {
        // The same anchor-bounded recovery must hold for `[QueryStringParams]`
        // and `[Cookies]`: rows (including all-disabled ones) between the
        // section header and the HTTP line survive.
        let content = "GET http://h/x\n[QueryStringParams]\n# a: 1\n# b: 2\n[Cookies]\ntheme: dark\n# hidden: y\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        assert_eq!(
            e[0].queries,
            vec![
                ("a".into(), "1".into(), false),
                ("b".into(), "2".into(), false),
            ]
        );
        assert_eq!(
            e[0].cookies,
            vec![
                ("theme".into(), "dark".into(), true),
                ("hidden".into(), "y".into(), false),
            ]
        );
    }

    #[test]
    fn blank_line_after_form_header_keeps_disabled_rows() {
        // A `[Form]` with an enabled row (from the AST) and a disabled row
        // recovered by scanning, separated from the header by a blank line.
        let content = "POST http://h/x\n[Form]\n\nname: alice\n# nickname: al\nHTTP 200\n";
        let e = parse_hurl(content);
        assert_eq!(e.len(), 1);
        let fields: Vec<(String, bool)> = e[0]
            .form_fields
            .iter()
            .map(|f| (f.key.clone(), f.enabled))
            .collect();
        assert_eq!(
            fields,
            vec![("name".into(), true), ("nickname".into(), false)]
        );
    }

    #[test]
    fn hurl_round_trips_through_serialize_and_parse() {
        let original = vec![
            HurlEntry::from_fields(
                "Create post",
                "POST",
                "{{ BASE_URL }}/posts",
                vec![KvRow::toggled("Content-Type", "application/json", true)],
                "{\n  \"title\": \"hi\"\n}",
            ),
            HurlEntry::from_fields(
                "Health",
                "GET",
                "{{ BASE_URL }}/health",
                vec![KvRow::toggled("Accept", "application/json", true)],
                "",
            ),
        ];

        let text = collection_to_hurl(&original);
        let reparsed = parse_hurl(&text);

        assert_eq!(reparsed.len(), original.len());
        for (a, b) in original.iter().zip(&reparsed) {
            assert_eq!(a.title, b.title);
            assert_eq!(a.method, b.method);
            assert_eq!(a.url, b.url);
            assert_eq!(a.headers, b.headers);
            assert_eq!(a.body_src, b.body_src);
        }
    }

    #[test]
    fn sections_and_captures_round_trip() {
        let src = "# Auth\nGET {{ BASE_URL }}/users/1\n[BasicAuth]\n{{ USER }}: {{ PASS }}\nHTTP 200\n[Captures]\ntoken: jsonpath \"$.token\"\n";
        let parsed = parse_hurl(src);
        assert_eq!(parsed.len(), 1);
        let reparsed = parse_hurl(&collection_to_hurl(&parsed));
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].basic_auth, parsed[0].basic_auth);
        assert_eq!(reparsed[0].expected_status, parsed[0].expected_status);
        assert_eq!(reparsed[0].captures, parsed[0].captures);
    }

    #[test]
    fn asserts_and_captures_without_explicit_status_still_round_trip() {
        // An entry built by hand (e.g. from the request wizard) with asserts or
        // captures but no expected_status must still emit a response section
        // (`HTTP *`, the Hurl wildcard) so those sections survive a save/reload
        // instead of being silently dropped.
        let mut entry =
            HurlEntry::from_fields("Health", "GET", "{{ BASE_URL }}/health", vec![], "");
        entry.asserts = vec!["jsonpath \"$.status\" == \"ok\"".to_string()];
        entry.captures = vec![("id".to_string(), "jsonpath \"$.id\"".to_string())];
        assert!(entry.expected_status.is_none());

        let text = entry.to_hurl();
        assert!(
            text.contains("HTTP *"),
            "wildcard status line expected:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].asserts, entry.asserts);
        assert_eq!(reparsed[0].captures, entry.captures);
        assert!(reparsed[0].expected_status.is_none());
    }

    #[test]
    fn asserts_are_parsed_and_round_trip() {
        let src = "# Health\nGET {{ BASE_URL }}/health\nHTTP 200\n[Asserts]\njsonpath \"$.status\" == \"ok\"\njsonpath \"$.count\" >= 1\n[Captures]\nid: jsonpath \"$.id\"\n";
        let parsed = parse_hurl(src);
        assert_eq!(parsed.len(), 1);
        assert_eq!(
            parsed[0].asserts,
            vec![
                "jsonpath \"$.status\" == \"ok\"".to_string(),
                "jsonpath \"$.count\" >= 1".to_string(),
            ],
        );
        let reparsed = parse_hurl(&collection_to_hurl(&parsed));
        assert_eq!(reparsed[0].asserts, parsed[0].asserts);
        assert_eq!(reparsed[0].captures, parsed[0].captures);
    }

    #[test]
    fn cookies_round_trip() {
        let mut entry = HurlEntry::from_fields("Login", "GET", "{{ BASE_URL }}/me", vec![], "");
        entry.cookies = vec![
            KvRow::toggled("session", "abc123", true),
            KvRow::toggled("theme", "dark", true),
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("[Cookies]"),
            "expected a Cookies section:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].cookies, entry.cookies);
    }

    #[test]
    fn reports_block_round_trips_through_serialize_and_parse() {
        let mut entry = HurlEntry::from_fields("Process", "POST", "{{ URL }}/process", vec![], "");
        entry.reports = vec![
            ("status".to_string(), "jsonpath \"$.status\"".to_string()),
            (
                "overall".to_string(),
                "jsonpath \"$.overall_result\"".to_string(),
            ),
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("# [Reports]"),
            "expected a commented Reports marker:\n{text}"
        );
        // The block must survive re-parsing.
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].reports, entry.reports);
    }

    #[test]
    fn reports_block_is_ignored_by_hurl_core_so_the_file_still_parses() {
        // The whole point of comment-encoding: `hurl_core` must still parse a
        // request that carries a `# [Reports]` block (a literal `[Reports]`
        // response section would be a non-recoverable parse error).
        let mut entry = HurlEntry::from_fields("Process", "POST", "http://h/process", vec![], "");
        entry.captures = vec![("token".to_string(), "jsonpath \"$.token\"".to_string())];
        entry.reports = vec![("status".to_string(), "jsonpath \"$.status\"".to_string())];
        let text = entry.to_hurl();
        assert!(
            parse_hurl_file(&text).is_ok(),
            "hurl_core should still parse a file with a # [Reports] block:\n{text}"
        );
        // And the real [Captures] section alongside it is unaffected.
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed[0].captures, entry.captures);
        assert_eq!(reparsed[0].reports, entry.reports);
    }

    #[test]
    fn reports_block_scan_does_not_bleed_across_entries() {
        // Two entries; only the first has a Reports block. The scan window must
        // stop at the next entry so the block isn't attributed to the wrong one.
        let mut a = HurlEntry::from_fields("First", "GET", "http://h/a", vec![], "");
        a.reports = vec![("s".to_string(), "jsonpath \"$.s\"".to_string())];
        let b = HurlEntry::from_fields("Second", "GET", "http://h/b", vec![], "");
        let doc = collection_to_hurl(&[a.clone(), b.clone()]);
        let parsed = parse_hurl(&doc);
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].reports, a.reports);
        assert!(
            parsed[1].reports.is_empty(),
            "second entry must not inherit the first's Reports block"
        );
    }

    #[test]
    fn text_only_form_fields_round_trip_as_form_section() {
        let mut entry = HurlEntry::from_fields("Login", "POST", "{{ BASE_URL }}/login", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "user".to_string(),
                value: "bob".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "pass".to_string(),
                value: "secret".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("[Form]"),
            "all-Text fields should serialize as [Form]:\n{text}"
        );
        assert!(!text.contains("[Multipart]"));
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    #[test]
    fn file_form_fields_round_trip_as_multipart_section() {
        // A single File field switches the whole section to [Multipart], even
        // when mixed with plain Text fields; content-type is optional.
        let mut entry =
            HurlEntry::from_fields("Upload", "POST", "{{ BASE_URL }}/upload", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "field1".to_string(),
                value: "value1".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "field2".to_string(),
                value: "example.txt".to_string(),
                kind: FormFieldKind::File,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "field3".to_string(),
                value: "example.zip".to_string(),
                kind: FormFieldKind::File,
                content_type: Some("application/zip".to_string()),
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("[Multipart]"),
            "a File field should switch to [Multipart]:\n{text}"
        );
        assert!(!text.contains("[Form]\n"));
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    #[test]
    fn file_form_field_path_with_spaces_round_trips_as_a_real_path() {
        let mut entry =
            HurlEntry::from_fields("Upload", "POST", "{{ BASE_URL }}/upload", vec![], "");
        entry.form_fields = vec![FormField {
            key: "doc".to_string(),
            // A real filesystem path containing spaces (as the file picker
            // would store it) — no backslash escaping in the model.
            value: "/tmp/my report final.pdf".to_string(),
            kind: FormFieldKind::File,
            content_type: None,
            base64_prefix: None,
            enabled: true,
            desc: String::new(),
        }];

        let text = entry.to_hurl();
        assert!(
            text.contains(r"file,/tmp/my\ report\ final.pdf;"),
            "the emitted Hurl escapes spaces in the path:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(
            reparsed[0].form_fields, entry.form_fields,
            "and it parses back to the same unescaped real path"
        );
    }

    #[test]
    fn loading_a_multipart_file_with_escaped_spaces_yields_a_real_path() {
        let src = "POST http://x/upload\n[Multipart]\ndoc: file,my\\ report.pdf;\n";
        let parsed = parse_hurl(src);
        assert_eq!(parsed[0].form_fields.len(), 1);
        assert_eq!(
            parsed[0].form_fields[0].value, "my report.pdf",
            "the stored path is the decoded real path, not the escaped source"
        );
    }

    #[test]
    fn base64_file_field_round_trips_with_its_prefix() {
        // A Base64File keeps its file path + prefix across a save/reload cycle
        // via the PaperBoy content-type marker (Hurl has no native concept of
        // it). It serializes as a [Multipart] file line and comes back as a
        // Base64File, not a plain File.
        let mut entry =
            HurlEntry::from_fields("Upload", "POST", "{{ BASE_URL }}/upload", vec![], "");
        entry.form_fields = vec![FormField {
            key: "avatar".to_string(),
            value: "/tmp/pic.png".to_string(),
            kind: FormFieldKind::Base64File,
            content_type: None,
            base64_prefix: Some("data:image/png;base64,".to_string()),
            enabled: true,
            desc: String::new(),
        }];

        let text = entry.to_hurl();
        assert!(
            text.contains("[Multipart]"),
            "a Base64File field serializes under [Multipart]:\n{text}"
        );
        assert!(
            text.contains("x-paperboy-base64;"),
            "the emitted Hurl carries the PaperBoy marker:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(
            reparsed[0].form_fields, entry.form_fields,
            "the Base64File kind and its prefix survive the round trip"
        );
    }

    #[test]
    fn base64_file_field_with_empty_prefix_round_trips() {
        let mut entry =
            HurlEntry::from_fields("Upload", "POST", "{{ BASE_URL }}/upload", vec![], "");
        entry.form_fields = vec![FormField {
            key: "blob".to_string(),
            value: "/tmp/data.bin".to_string(),
            kind: FormFieldKind::Base64File,
            content_type: None,
            base64_prefix: Some(String::new()),
            enabled: true,
            desc: String::new(),
        }];

        let reparsed = parse_hurl(&entry.to_hurl());
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    #[test]
    fn disabled_header_round_trips_as_a_comment() {
        let mut entry = HurlEntry::from_fields("Get", "GET", "http://x/y", vec![], "");
        entry.headers = vec![
            KvRow::toggled("Accept", "application/json", true),
            KvRow::toggled("X-Off", "no", false),
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("\n# X-Off: no\n"),
            "the disabled header is written as a comment:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed.len(), 1);
        assert_eq!(reparsed[0].headers, entry.headers);
    }

    #[test]
    fn disabled_cookie_and_query_rows_round_trip() {
        let mut entry = HurlEntry::from_fields("Get", "GET", "http://x/y", vec![], "");
        entry.cookies = vec![
            KvRow::toggled("session", "abc", true),
            KvRow::toggled("stale", "1", false),
        ];
        entry.queries = vec![
            KvRow::toggled("page", "2", false),
            KvRow::toggled("q", "hi", true),
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("# stale: 1"),
            "disabled cookie commented:\n{text}"
        );
        assert!(
            text.contains("# page: 2"),
            "disabled query commented:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed[0].cookies, entry.cookies);
        assert_eq!(reparsed[0].queries, entry.queries);
    }

    #[test]
    fn a_hand_written_commented_request_line_parses_as_disabled() {
        // A user commenting out a header/query row by hand (not via the app)
        // should be understood as a disabled entry, while a prose comment is
        // left alone.
        let src = "GET http://x/y\nAccept: text/plain\n# X-Debug: 1\n# just a note\n[Query]\npage: 2\n# limit: 10\n";
        let parsed = parse_hurl(src);
        assert_eq!(
            parsed[0].headers,
            vec![
                ("Accept".to_string(), "text/plain".to_string(), true),
                ("X-Debug".to_string(), "1".to_string(), false),
            ],
            "the commented header line is a disabled entry; the prose note is ignored"
        );
        assert_eq!(
            parsed[0].queries,
            vec![
                ("page".to_string(), "2".to_string(), true),
                ("limit".to_string(), "10".to_string(), false),
            ]
        );
    }

    #[test]
    fn disabled_rows_keep_their_position_relative_to_enabled_ones() {
        let mut entry = HurlEntry::from_fields("Get", "GET", "http://x/y", vec![], "");
        entry.headers = vec![
            KvRow::toggled("A", "1", false),
            KvRow::toggled("B", "2", true),
            KvRow::toggled("C", "3", false),
        ];
        let reparsed = parse_hurl(&entry.to_hurl());
        assert_eq!(reparsed[0].headers, entry.headers, "order is preserved");
    }

    #[test]
    fn disabled_text_form_field_round_trips_as_a_comment() {
        let mut entry = HurlEntry::from_fields("Post", "POST", "http://x/y", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "on".to_string(),
                value: "yes".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "off".to_string(),
                value: "no".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: false,
                desc: String::new(),
            },
        ];

        let text = entry.to_hurl();
        assert!(text.contains("[Form]"), "text-only stays [Form]:\n{text}");
        assert!(
            text.contains("# off: no"),
            "disabled field commented:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    #[test]
    fn a_disabled_file_field_does_not_flip_a_form_section_to_multipart() {
        // The section type is chosen from the *enabled* fields only: a disabled
        // File row is a comment and never runs, so an otherwise text-only
        // request must stay `[Form]` (and the disabled row still round-trips).
        let mut entry = HurlEntry::from_fields("Post", "POST", "http://x/y", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "name".to_string(),
                value: "bob".to_string(),
                kind: FormFieldKind::Text,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "doc".to_string(),
                value: "/tmp/a b.pdf".to_string(),
                kind: FormFieldKind::File,
                content_type: Some("application/pdf".to_string()),
                base64_prefix: None,
                enabled: false,
                desc: String::new(),
            },
        ];

        let text = entry.to_hurl();
        assert!(text.contains("[Form]"), "stays [Form]:\n{text}");
        assert!(!text.contains("[Multipart]"));
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    #[test]
    fn a_disabled_multipart_file_field_round_trips() {
        let mut entry = HurlEntry::from_fields("Post", "POST", "http://x/y", vec![], "");
        entry.form_fields = vec![
            FormField {
                key: "upload".to_string(),
                value: "/tmp/on.bin".to_string(),
                kind: FormFieldKind::File,
                content_type: None,
                base64_prefix: None,
                enabled: true,
                desc: String::new(),
            },
            FormField {
                key: "avatar".to_string(),
                value: "/tmp/off.png".to_string(),
                kind: FormFieldKind::Base64File,
                content_type: None,
                base64_prefix: Some("data:image/png;base64,".to_string()),
                enabled: false,
                desc: String::new(),
            },
        ];

        let text = entry.to_hurl();
        assert!(
            text.contains("[Multipart]"),
            "an enabled File stays [Multipart]:\n{text}"
        );
        let reparsed = parse_hurl(&text);
        assert_eq!(reparsed[0].form_fields, entry.form_fields);
    }

    // A parse → serialize → parse cycle that must reproduce the same comments.
    fn assert_comments_round_trip(src: &str) -> Vec<HurlEntry> {
        let first = parse_hurl(src);
        let text = collection_to_hurl(&first);
        let second = parse_hurl(&text);
        let c1: Vec<_> = first.iter().map(|e| e.comments.clone()).collect();
        let c2: Vec<_> = second.iter().map(|e| e.comments.clone()).collect();
        assert_eq!(
            c1, c2,
            "comments must be stable across a round trip\n--- serialized ---\n{text}"
        );
        second
    }

    #[test]
    fn a_comment_before_asserts_round_trips_before_asserts() {
        let src = "GET http://h/a\nHTTP 200\n# validate the token\n[Asserts]\njsonpath \"$.token\" exists\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Asserts,
                text: "# validate the token".into(),
            }]
        );
        let text = e[0].to_hurl();
        assert!(
            text.contains("# validate the token\n[Asserts]"),
            "the comment must stay directly before [Asserts]:\n{text}"
        );
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_prose_comment_in_the_header_region_is_kept_and_anchored_to_headers() {
        let src = "POST http://h/a\n# auth headers below\nAuthorization: Bearer x\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Headers,
                text: "# auth headers below".into(),
            }]
        );
        // The enabled header still loads (the comment isn't mistaken for one).
        assert_eq!(
            e[0].headers,
            vec![("Authorization".into(), "Bearer x".into(), true)]
        );
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_prose_comment_and_a_disabled_row_coexist_without_duplication() {
        // `# X-Debug: 1` is a disabled header (kv-shaped); `# just a note` is
        // prose. Neither should swallow or duplicate the other.
        let src = "GET http://h/a\n# X-Debug: 1\n# just a note\nAccept: 1\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].headers,
            vec![
                ("X-Debug".into(), "1".into(), false),
                ("Accept".into(), "1".into(), true),
            ]
        );
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Headers,
                text: "# just a note".into(),
            }]
        );
        let entries = assert_comments_round_trip(src);
        // The disabled row survives exactly once (not also captured as prose).
        let text = collection_to_hurl(&entries);
        assert_eq!(text.matches("# X-Debug: 1").count(), 1, "{text}");
        assert_eq!(text.matches("# just a note").count(), 1, "{text}");
    }

    #[test]
    fn a_reports_block_is_not_re_captured_as_prose() {
        let src = "GET http://h/a\nHTTP 200\n# [Reports]\n# total: jsonpath \"$.total\"\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].reports,
            vec![("total".into(), "jsonpath \"$.total\"".into())]
        );
        assert!(
            e[0].comments.is_empty(),
            "the reports block must not leak into prose comments: {:?}",
            e[0].comments
        );
        // And it isn't duplicated on re-emit.
        let text = e[0].to_hurl();
        assert_eq!(text.matches("# [Reports]").count(), 1, "{text}");
        assert_eq!(text.matches("# total:").count(), 1, "{text}");
    }

    #[test]
    fn a_banner_and_extra_leading_prose_round_trip() {
        // The contiguous block above the method line is the title; a separate
        // banner higher up (above the first entry) is kept as a Lead comment.
        let src = "#####\n# File header\n#####\n\n# Get token\nGET http://h/a\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].title, "Get token");
        assert_eq!(
            e[0].comments,
            vec![
                EntryComment {
                    anchor: CommentAnchor::Lead,
                    text: "#####".into()
                },
                EntryComment {
                    anchor: CommentAnchor::Lead,
                    text: "# File header".into()
                },
                EntryComment {
                    anchor: CommentAnchor::Lead,
                    text: "#####".into()
                },
            ]
        );
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_trailing_comment_round_trips_at_the_end() {
        let src = "GET http://h/a\nHTTP 200\n[Asserts]\njsonpath \"$.x\" == 1\n# checked above\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Trailing,
                text: "# checked above".into(),
            }]
        );
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_comment_between_two_entries_is_kept_and_does_not_cross_over() {
        let src = "GET http://h/a\nHTTP 200\n# note about the first request\n\n# Second\nPOST http://h/b\nHTTP 201\n";
        let e = parse_hurl(src);
        assert_eq!(e.len(), 2);
        // The note stays with entry 0 (as a trailing comment); entry 1 keeps its
        // title and gains no stray comments.
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Trailing,
                text: "# note about the first request".into(),
            }]
        );
        assert_eq!(e[1].title, "Second");
        assert!(e[1].comments.is_empty(), "{:?}", e[1].comments);
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_hash_line_inside_a_multiline_body_is_not_captured_as_a_comment() {
        let src = "POST http://h/a\n```\n# not a comment, this is body text\n```\nHTTP 200\n";
        let e = parse_hurl(src);
        assert!(
            e[0].comments.is_empty(),
            "multiline body content must not be captured as prose: {:?}",
            e[0].comments
        );
        assert!(
            e[0].body_src
                .as_deref()
                .unwrap_or_default()
                .contains("# not a comment"),
            "the body must still contain the # line: {:?}",
            e[0].body_src
        );
    }

    #[test]
    fn a_comment_only_entry_keeps_its_comment_without_bleeding_into_the_next() {
        // The reviewer's bleed case, now viewed through comment recovery: a
        // comment glued directly above the next method line (blank above it) is
        // that entry's *title* by PaperBoy's convention, so it stays with
        // entry 1 and must never be absorbed into entry 0's headers or prose.
        let src = "GET http://h/a\n\n# a floating note\nPOST http://h/b\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(e.len(), 2);
        assert!(e[0].headers.is_empty());
        assert!(e[0].comments.is_empty(), "{:?}", e[0].comments);
        assert_eq!(e[1].title, "a floating note");
        assert!(e[1].comments.is_empty(), "{:?}", e[1].comments);
        assert_comments_round_trip(src);
    }

    #[test]
    fn comments_survive_a_full_document_round_trip_unchanged() {
        // A dense mix: Lead banner, title, header-region prose, an inter-header
        // disabled row, a section comment, a response comment and a trailing
        // comment — all in one entry — must be byte-identical after two trips.
        let src = "# top of file\n\n# Login\nPOST http://h/login\n# creds below\nContent-Type: json\n[Cookies]\n# the session cookie\nsid: abc\nHTTP 200\n# then assert\n[Asserts]\njsonpath \"$.ok\" == true\n# done\n";
        let once = collection_to_hurl(&parse_hurl(src));
        let twice = collection_to_hurl(&parse_hurl(&once));
        assert_eq!(once, twice, "round trip must be idempotent:\n{once}");
        assert_comments_round_trip(src);
    }

    // ---- Request [Options] + response headers/body/version round-trip ----

    /// Parse `src`, serialize, reparse and assert the whole model is stable
    /// across the round trip for the Part 5 fields (plus that the serialized
    /// text still parses cleanly through `hurl_core`).
    fn assert_sections_round_trip(src: &str) -> Vec<HurlEntry> {
        let first = parse_hurl(src);
        let text = collection_to_hurl(&first);
        assert!(
            parse_hurl_error(&text).is_none(),
            "serialized text must parse via hurl_core:\n{text}\nerror: {:?}",
            parse_hurl_error(&text)
        );
        let second = parse_hurl(&text);
        assert_eq!(first.len(), second.len());
        for (a, b) in first.iter().zip(&second) {
            assert_eq!(a.options, b.options, "options drift:\n{text}");
            assert_eq!(
                a.response_version, b.response_version,
                "version drift:\n{text}"
            );
            assert_eq!(
                a.response_headers, b.response_headers,
                "resp headers drift:\n{text}"
            );
            assert_eq!(a.response_body, b.response_body, "resp body drift:\n{text}");
        }
        second
    }

    #[test]
    fn request_options_section_round_trips() {
        let src = "POST http://h/a\n[Options]\nretry: 3\ninsecure: true\nvariable: host=example.net\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].options,
            vec![
                ("retry".into(), "3".into(), true),
                ("insecure".into(), "true".into(), true),
                ("variable".into(), "host=example.net".into(), true),
            ]
        );
        assert_sections_round_trip(src);
    }

    #[test]
    fn a_disabled_option_row_round_trips_as_a_comment() {
        let src = "GET http://h/a\n[Options]\nretry: 3\n# insecure: true\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].options,
            vec![
                ("retry".into(), "3".into(), true),
                ("insecure".into(), "true".into(), false),
            ]
        );
        // The disabled row is an option, not captured a second time as prose.
        assert!(e[0].comments.is_empty(), "{:?}", e[0].comments);
        assert_sections_round_trip(src);
    }

    #[test]
    fn options_and_a_body_coexist_and_round_trip() {
        // The critical ordering case: `hurl_core` parses a request as
        // headers -> sections -> body and rejects a section after the body, so
        // `to_hurl` must emit `[Options]` before the body. If it didn't, the
        // serialized text wouldn't even parse.
        let src = "POST http://h/a\n[Options]\nretry: 2\n```\n{\"x\":1}\n```\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].options, vec![("retry".into(), "2".into(), true)]);
        assert_eq!(e[0].body_src.as_deref(), Some("```\n{\"x\":1}\n```"));
        let text = e[0].to_hurl();
        assert!(
            text.find("[Options]").unwrap() < text.find("```").unwrap(),
            "[Options] must be emitted before the body:\n{text}"
        );
        assert_sections_round_trip(src);
    }

    #[test]
    fn response_headers_round_trip() {
        let src = "GET http://h/a\nHTTP 200\nContent-Type: application/json\nX-Trace: abc\n[Asserts]\njsonpath \"$.ok\" == true\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].response_headers,
            vec![
                ("Content-Type".into(), "application/json".into(), true),
                ("X-Trace".into(), "abc".into(), true),
            ]
        );
        assert_eq!(e[0].asserts, vec!["jsonpath \"$.ok\" == true".to_string()]);
        assert_sections_round_trip(src);
    }

    #[test]
    fn a_disabled_response_header_round_trips_as_a_comment() {
        let src = "GET http://h/a\nHTTP 200\nContent-Type: application/json\n# X-Trace: abc\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].response_headers,
            vec![
                ("Content-Type".into(), "application/json".into(), true),
                ("X-Trace".into(), "abc".into(), false),
            ]
        );
        assert!(e[0].comments.is_empty(), "{:?}", e[0].comments);
        assert_sections_round_trip(src);
    }

    #[test]
    fn response_body_round_trips_after_sections() {
        let src =
            "GET http://h/a\nHTTP 200\n[Asserts]\njsonpath \"$.a\" == 1\n```\n{\"a\":1}\n```\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].response_body.as_deref(), Some("```\n{\"a\":1}\n```"));
        assert_eq!(e[0].asserts, vec!["jsonpath \"$.a\" == 1".to_string()]);
        let text = e[0].to_hurl();
        assert!(
            text.find("[Asserts]").unwrap() < text.rfind("```").unwrap(),
            "the response body must follow the response sections:\n{text}"
        );
        assert_sections_round_trip(src);
    }

    /// A `file,…;` body used to come back as `None` — indistinguishable from
    /// "no body at all" — so the next save dropped the line entirely. Because
    /// `collection_to_hurl` rewrites *every* entry, editing any request in the
    /// collection silently deleted the body of every file-bodied one, with no
    /// parse error to hint at it.
    #[test]
    fn a_file_body_survives_a_save() {
        let src = "POST http://h/a\nContent-Type: application/json\nfile, body.json;\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].body_src.as_deref(), Some("file, body.json;"));
        let text = collection_to_hurl(&e);
        assert!(text.contains("file, body.json;"), "\n{text}");
        assert_eq!(parse_hurl_error(&text), None, "\n{text}");
        // Idempotent: a second save must not rewrite it again.
        assert_eq!(collection_to_hurl(&parse_hurl(&text)), text);
    }

    /// The same for a `base64,…;` body, the other `Bytes` variant with no
    /// textual value to render.
    #[test]
    fn a_base64_body_survives_a_save() {
        let src = "POST http://h/a\nbase64,SGVsbG8=;\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].body_src.as_deref(), Some("base64,SGVsbG8=;"));
        let text = collection_to_hurl(&e);
        assert!(text.contains("base64,SGVsbG8=;"), "\n{text}");
        assert_eq!(parse_hurl_error(&text), None, "\n{text}");
        assert_eq!(collection_to_hurl(&parse_hurl(&text)), text);
    }

    /// Expected *response* bodies read through the same helper, so they were
    /// lost the same way.
    #[test]
    fn a_file_response_body_survives_a_save() {
        let src = "POST http://h/a\n{\"a\":1}\n\nHTTP 200\nfile,expected.json;\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].response_body.as_deref(), Some("file,expected.json;"));
        let text = collection_to_hurl(&e);
        assert!(text.contains("file,expected.json;"), "\n{text}");
        assert_eq!(parse_hurl_error(&text), None, "\n{text}");
        assert_eq!(collection_to_hurl(&parse_hurl(&text)), text);
    }

    /// The blast radius that made this severe: a save triggered by editing one
    /// request must not quietly empty the body of an untouched neighbour.
    #[test]
    fn a_file_body_is_not_lost_when_another_request_is_edited() {
        let src = "POST http://h/a\nfile, body.json;\n\nGET http://h/b\n";
        let mut e = parse_hurl(src);
        e[1].url = "http://h/c".into();
        let text = collection_to_hurl(&e);
        assert!(
            text.contains("file, body.json;"),
            "the untouched request keeps its body:\n{text}"
        );
        assert_eq!(parse_hurl(&text).len(), 2, "\n{text}");
    }

    #[test]
    fn a_hash_line_inside_a_response_body_is_not_captured_as_a_comment() {
        let src = "GET http://h/a\nHTTP 200\n```\n# not a comment\n```\n";
        let e = parse_hurl(src);
        assert!(e[0].comments.is_empty(), "{:?}", e[0].comments);
        assert!(
            e[0].response_body
                .as_deref()
                .unwrap_or_default()
                .contains("# not a comment")
        );
        assert_sections_round_trip(src);
    }

    #[test]
    fn response_http_version_round_trips() {
        let src = "GET http://h/a\nHTTP/1.1 200\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].response_version.as_deref(), Some("HTTP/1.1"));
        assert_eq!(e[0].expected_status, Some(200));
        let text = e[0].to_hurl();
        assert!(
            text.contains("HTTP/1.1 200"),
            "version must round-trip:\n{text}"
        );
        assert_sections_round_trip(src);
    }

    #[test]
    fn version_agnostic_http_keyword_stays_versionless() {
        let src = "GET http://h/a\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].response_version, None);
        assert!(e[0].to_hurl().contains("HTTP 200"));
        assert_sections_round_trip(src);
    }

    #[test]
    fn a_version_with_no_explicit_status_uses_the_wildcard() {
        let src = "GET http://h/a\nHTTP/2 *\n[Asserts]\njsonpath \"$.x\" == 1\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].response_version.as_deref(), Some("HTTP/2"));
        assert_eq!(e[0].expected_status, None);
        assert!(e[0].to_hurl().contains("HTTP/2 *"));
        assert_sections_round_trip(src);
    }

    #[test]
    fn a_comment_before_options_anchors_to_options() {
        let src = "GET http://h/a\n# tuning\n[Options]\nretry: 3\nHTTP 200\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::Options,
                text: "# tuning".into(),
            }]
        );
        assert!(e[0].to_hurl().contains("# tuning\n[Options]"));
        assert_comments_round_trip(src);
    }

    #[test]
    fn a_comment_among_response_headers_stays_in_the_response_area() {
        let src = "GET http://h/a\nHTTP 200\n# trace headers\nX-Trace: abc\n[Asserts]\njsonpath \"$.ok\" == true\n";
        let e = parse_hurl(src);
        assert_eq!(
            e[0].comments,
            vec![EntryComment {
                anchor: CommentAnchor::ResponseHeaders,
                text: "# trace headers".into(),
            }]
        );
        let text = e[0].to_hurl();
        assert!(
            text.find("HTTP 200").unwrap() < text.find("# trace headers").unwrap()
                && text.find("# trace headers").unwrap() < text.find("[Asserts]").unwrap(),
            "the comment must stay between the HTTP line and [Asserts]:\n{text}"
        );
        assert_comments_round_trip(src);
    }

    #[test]
    fn options_response_headers_body_and_comments_all_survive_one_document() {
        let src = "# Big one\nPOST http://h/a\nContent-Type: json\n[Options]\nretry: 2\n```\n{\"x\":1}\n```\nHTTP/1.1 201\nX-Trace: t\n[Asserts]\njsonpath \"$.id\" exists\n```\n{\"id\":9}\n```\n# all checked\n";
        let e = parse_hurl(src);
        assert_eq!(e[0].options, vec![("retry".into(), "2".into(), true)]);
        assert_eq!(e[0].response_version.as_deref(), Some("HTTP/1.1"));
        assert_eq!(
            e[0].response_headers,
            vec![("X-Trace".into(), "t".into(), true)]
        );
        assert_eq!(e[0].response_body.as_deref(), Some("```\n{\"id\":9}\n```"));
        assert_eq!(e[0].body_src.as_deref(), Some("```\n{\"x\":1}\n```"));
        assert_sections_round_trip(src);
        assert_comments_round_trip(src);
    }

    #[test]
    fn options_and_response_fields_do_not_bleed_into_the_next_request() {
        // Two full entries, each with a request `[Options]` section, a response
        // version, response headers and a response body. The scans for each of
        // these must be bounded to their own entry — the second request's
        // fields must not be absorbed into the first (and vice versa).
        let src = concat!(
            "GET http://h/a\n",
            "[Options]\nretry: 1\n",
            "HTTP/1.1 200\n",
            "X-A: a\n",
            "[Asserts]\njsonpath \"$.a\" == 1\n",
            "```\n{\"a\":1}\n```\n",
            "\n",
            "GET http://h/b\n",
            "[Options]\nretry: 2\n",
            "HTTP/2 201\n",
            "X-B: b\n",
            "[Asserts]\njsonpath \"$.b\" == 2\n",
            "```\n{\"b\":2}\n```\n",
        );
        let e = parse_hurl(src);
        assert_eq!(e.len(), 2, "two distinct entries");

        assert_eq!(e[0].options, vec![("retry".into(), "1".into(), true)]);
        assert_eq!(e[0].response_version.as_deref(), Some("HTTP/1.1"));
        assert_eq!(
            e[0].response_headers,
            vec![("X-A".into(), "a".into(), true)]
        );
        assert_eq!(e[0].response_body.as_deref(), Some("```\n{\"a\":1}\n```"));

        assert_eq!(e[1].options, vec![("retry".into(), "2".into(), true)]);
        assert_eq!(e[1].response_version.as_deref(), Some("HTTP/2"));
        assert_eq!(
            e[1].response_headers,
            vec![("X-B".into(), "b".into(), true)]
        );
        assert_eq!(e[1].response_body.as_deref(), Some("```\n{\"b\":2}\n```"));

        assert_sections_round_trip(src);
    }

    /// A per-row note has nowhere to live in the Hurl grammar, so it is
    /// smuggled through as a `# @desc ` comment on the line *above* the row
    /// (a trailing comment would be ambiguous — a header value may contain
    /// `#`). Both halves of that convention have to agree.
    #[test]
    fn a_header_description_survives_a_round_trip_through_the_hurl_text() {
        let mut e = HurlEntry::from_fields("Get", "GET", "http://h/x", vec![], "");
        e.headers = vec![KvRow {
            key: "X-Trace".into(),
            value: "on".into(),
            enabled: true,
            desc: "only for staging".into(),
        }];
        let text = collection_to_hurl(&[e]);
        assert!(
            text.contains("# @desc only for staging"),
            "the note should be written above its row: {text}"
        );
        let back = parse_hurl(&text);
        assert_eq!(
            back[0].headers[0].desc, "only for staging",
            "and it should come back attached to the same row"
        );
        assert_eq!(back[0].headers[0].key, "X-Trace");
    }

    #[test]
    fn a_multi_line_description_round_trips_as_several_marker_lines() {
        let mut e = HurlEntry::from_fields("Get", "GET", "http://h/x", vec![], "");
        e.headers = vec![KvRow {
            key: "X-Trace".into(),
            value: "on".into(),
            enabled: true,
            desc: "first line\nsecond line".into(),
        }];
        let text = collection_to_hurl(&[e]);
        assert_eq!(
            text.matches("# @desc ").count(),
            2,
            "one marker per line of the note: {text}"
        );
        let back = parse_hurl(&text);
        assert_eq!(back[0].headers[0].desc, "first line\nsecond line");
    }

    /// The marker lines are also plain comments, so the prose-comment scanner
    /// has to know to leave them alone — otherwise every save would keep a
    /// copy as free text *and* re-emit the row's own marker.
    #[test]
    fn a_description_is_not_also_captured_as_a_prose_comment() {
        let mut e = HurlEntry::from_fields("Get", "GET", "http://h/x", vec![], "");
        e.headers = vec![KvRow {
            key: "X-Trace".into(),
            value: "on".into(),
            enabled: true,
            desc: "only for staging".into(),
        }];
        let once = collection_to_hurl(&[e]);
        let twice = collection_to_hurl(&parse_hurl(&once));
        assert_eq!(once, twice, "a save/load cycle must be a fixed point");
        assert_eq!(
            twice.matches("only for staging").count(),
            1,
            "the note must not be duplicated as prose: {twice}"
        );
    }

    #[test]
    fn a_disabled_row_keeps_both_its_note_and_its_disabled_state() {
        let mut e = HurlEntry::from_fields("Get", "GET", "http://h/x", vec![], "");
        e.headers = vec![KvRow {
            key: "X-Trace".into(),
            value: "on".into(),
            enabled: false,
            desc: "off until the rollout".into(),
        }];
        let back = parse_hurl(&collection_to_hurl(&[e]));
        let row = &back[0].headers[0];
        assert!(!row.enabled, "the row should still be off");
        assert_eq!(row.desc, "off until the rollout");
    }

    #[test]
    fn a_form_field_description_survives_a_round_trip() {
        let mut e = HurlEntry::from_fields("Post", "POST", "http://h/x", vec![], "");
        e.form_fields = vec![crate::hurl::FormField {
            key: "region".into(),
            value: "eu-west-1".into(),
            enabled: true,
            desc: "which cluster to hit".into(),
            ..Default::default()
        }];
        let back = parse_hurl(&collection_to_hurl(&[e]));
        assert_eq!(back[0].form_fields[0].desc, "which cluster to hit");
    }

    /// `# @description` is ordinary prose that happens to start with the same
    /// letters; only the exact marker followed by a space (or end of line)
    /// counts, or a user's comment would silently become a row note.
    #[test]
    fn prose_that_merely_starts_like_the_marker_is_left_as_a_comment() {
        let text = "POST http://h/x\n# @description of the endpoint\nX-Trace: on\nHTTP 200\n";
        let back = parse_hurl(text);
        assert_eq!(
            back[0].headers[0].desc, "",
            "the row should not have adopted the comment as its note"
        );
        assert!(
            back[0]
                .comments
                .iter()
                .any(|c| c.text.contains("@description")),
            "and the line should survive as a comment: {:?}",
            back[0].comments
        );
    }

    /// The whole feature in one pass: a commented body is written as a block
    /// plus strict JSON, and comes back as the text it was authored from.
    #[test]
    fn a_commented_body_survives_a_save_and_a_reload() {
        let mut e = HurlEntry {
            title: "t".into(),
            method: "POST".into(),
            url: "http://h/a".into(),
            ..Default::default()
        };
        let authored = "{\n  // who\n  \"id\": {{user_id}} // the caller\n}";
        e.body_src = Some(authored.into());

        let text = collection_to_hurl(&[e]);
        assert!(text.contains("# [Body] 4"), "\n{text}");
        // What Hurl itself reads has no commentary in it.
        assert!(
            text.contains("{\n  \"id\": {{user_id}}\n}"),
            "the wire body is strict JSON:\n{text}"
        );

        let back = parse_hurl(&text);
        assert_eq!(back.len(), 1);
        assert_eq!(back[0].body_src.as_deref(), Some(authored));
        // And the block must not also come back as prose, or it would be
        // written twice on the next save, and again after that.
        assert!(
            !back[0].comments.iter().any(|c| c.text.contains("[Body]")),
            "{:?}",
            back[0].comments
        );
        assert_eq!(collection_to_hurl(&back), text, "a second save is stable");
    }

    /// The file's body is what runs and what every other tool sees, so when the
    /// two disagree it wins — but the notes are left in the file rather than
    /// deleted on the user's behalf.
    #[test]
    fn a_block_that_no_longer_describes_the_body_is_kept_as_comments() {
        let src = "POST http://h/a\n\
                   # [Body] 3\n\
                   # {\n\
                   #   \"id\": 1 // the caller\n\
                   # }\n\
                   {\"id\": 999}\n";
        let e = parse_hurl(src);

        assert_eq!(
            e[0].body_src.as_deref(),
            Some("{\"id\": 999}"),
            "the body in the file wins"
        );
        let text = collection_to_hurl(&e);
        assert!(
            text.contains("#   \"id\": 1 // the caller"),
            "the orphaned notes are still there:\n{text}"
        );
        assert!(text.contains("{\"id\": 999}"), "\n{text}");
    }

    /// Reformatting a body outside PaperBoy changes nothing about what is sent,
    /// so it must not orphan every comment in the request.
    #[test]
    fn reformatting_the_body_elsewhere_does_not_orphan_the_comments() {
        let src = "POST http://h/a\n\
                   # [Body] 3\n\
                   # {\n\
                   #   \"id\": 1, // the caller\n\
                   #   \"b\": 2\n\
                   # }\n\
                   {\"b\":2,\"id\":1}\n";
        // Four lines of block content, but the marker claims three — so this
        // also pins that a miscount is refused rather than half-claimed.
        assert!(parse_hurl(src)[0].body_src.as_deref() == Some("{\"b\":2,\"id\":1}"));

        let ok = src.replace("# [Body] 3", "# [Body] 4");
        let e = parse_hurl(&ok);
        assert_eq!(
            e[0].body_src.as_deref(),
            Some("{\n  \"id\": 1, // the caller\n  \"b\": 2\n}"),
            "a reordered, reformatted body still matches"
        );
    }

    /// A body may contain a line reading `[Body]`; counting lines rather than
    /// hunting for an end marker is what stops it closing its own block.
    #[test]
    fn body_content_cannot_terminate_its_own_block() {
        let mut e = HurlEntry {
            title: "t".into(),
            method: "POST".into(),
            url: "http://h/a".into(),
            ..Default::default()
        };
        let authored = "{\n  // note\n  \"a\": \"[Body] 1\"\n}";
        e.body_src = Some(authored.into());

        let text = collection_to_hurl(&[e]);
        assert_eq!(parse_hurl(&text)[0].body_src.as_deref(), Some(authored));
    }

    /// A body with no comments must be written exactly as it always was — the
    /// block is pure cost for the requests that don't need it.
    #[test]
    fn an_uncommented_body_gains_no_block() {
        let src = "POST http://h/a\n{\"id\": 1}\n";
        let e = parse_hurl(src);
        let text = collection_to_hurl(&e);
        assert!(!text.contains("[Body]"), "\n{text}");
        assert_eq!(text, src);
    }

    /// C1, the whole file at stake: commenting out a last field leaves a comma
    /// behind, and a body that isn't JSON used to be written out with its
    /// comments intact. That is invalid Hurl, and because a parse failure
    /// yields an empty collection it silently deleted every request in the
    /// file — not just the annotated one.
    #[test]
    fn commenting_out_a_last_field_does_not_empty_the_collection() {
        let mut a = HurlEntry {
            method: "POST".into(),
            url: "http://h/a".into(),
            ..Default::default()
        };
        let authored = "{\n  \"a\": 1,\n  // \"b\": 2\n}";
        a.body_src = Some(authored.into());
        let b = HurlEntry {
            method: "GET".into(),
            url: "http://h/b".into(),
            ..Default::default()
        };

        let text = collection_to_hurl(&[a, b]);
        assert!(parse_hurl_error(&text).is_none(), "invalid hurl:\n{text}");

        let back = parse_hurl(&text);
        assert_eq!(back.len(), 2, "the other request went with it:\n{text}");
        assert_eq!(back[0].body_src.as_deref(), Some(authored));
        // What is sent is strict JSON: no comment, and no stranded comma.
        assert_eq!(back[0].body_wire().as_deref(), Some("{\n  \"a\": 1\n}"));
    }

    /// C2: the count comes from the file, so it can say anything. Unchecked, a
    /// count near `usize::MAX` wrapped to a range ending before it began, which
    /// looked well-formed and never advanced the cursor — the app hung on a
    /// file stock Hurl reads as an ordinary comment.
    #[test]
    fn a_body_marker_claiming_the_whole_address_space_is_ignored() {
        let text = format!(
            "POST http://h/a\n# [Body] {}\n# {{\"a\":1}}\n{{\"a\":1}}\n",
            usize::MAX
        );
        let back = parse_hurl(&text);
        assert_eq!(back.len(), 1);
        // Degrades to prose: the note survives and the body is untouched.
        assert_eq!(back[0].body_wire().as_deref(), Some("{\"a\":1}"));
        assert!(collection_to_hurl(&back).contains("[Body]"));
    }

    /// C3: a hand-edit to a non-JSON body must win over the block describing
    /// it. Comparing loosely let the stale block be claimed, and PaperBoy then
    /// sent bytes that differed from the ones in the file.
    #[test]
    fn an_edit_to_a_non_json_body_beats_the_block_describing_it() {
        let text = "POST http://h/a\n# [Body] 1\n# <a>x y</a>\n<a>x  y</a>\n";
        let back = parse_hurl(text);
        assert_eq!(back[0].body_wire().as_deref(), Some("<a>x  y</a>"));
        // Unclaimed, but not deleted: the note is still in the file.
        assert!(collection_to_hurl(&back).contains("# <a>x y</a>"));
    }

    /// M1: the file is read line-wise, which eats a `\r`, so a block written
    /// with CRLF came back as LF and the next save wrote different bytes than
    /// the last — a file that churns in git every time it is opened.
    #[test]
    fn a_body_authored_with_windows_line_endings_settles() {
        let mut e = HurlEntry {
            method: "POST".into(),
            url: "http://h/a".into(),
            ..Default::default()
        };
        e.body_src = Some("{\r\n  // who\r\n  \"a\": 1\r\n}".into());

        let once = collection_to_hurl(&[e]);
        let twice = collection_to_hurl(&parse_hurl(&once));
        assert_eq!(once, twice, "not a fixed point");
        assert!(!once.contains('\r'), "\n{once:?}");
    }

    /// The notes left behind when a block stops describing its body are found
    /// without any stored state: a block that still reconciles is claimed by
    /// the parser and never reaches `comments`, so anything sitting there is
    /// stale by construction.
    #[test]
    fn leftover_notes_are_found_and_can_be_thrown_away() {
        let text = "POST http://h/a\n\
                    # [Body] 4\n\
                    # {\n\
                    #     //extra comment\n\
                    #     \"a\": 2 // just a test\n\
                    #\n\
                    # }\n\
                    {\n    \"a\": 2\n}\n";
        let mut back = parse_hurl(text);
        let e = &mut back[0];

        let (at, notes) = e.stale_body_notes().expect("the leftover block");
        assert_eq!(at.len(), 5, "the marker and the four lines it claims");
        assert_eq!(
            notes,
            "{\n    //extra comment\n    \"a\": 2 // just a test\n"
        );
        // The count says four, so `# }` is not part of the block: it is an
        // ordinary comment that happens to sit below it.
        assert_eq!(e.comments.len(), 6);

        assert!(e.discard_body_notes());
        assert_eq!(e.comments.len(), 1, "only the unclaimed `# }} ` is left");
        assert_eq!(e.body_wire().as_deref(), Some("{\n    \"a\": 2\n}"));
        assert!(e.stale_body_notes().is_none());
    }

    /// Adopting takes the notes back as the body, which changes what the
    /// request sends — so it is never automatic, and never offered when the
    /// notes would not survive the trip.
    #[test]
    fn leftover_notes_can_be_taken_back_as_the_body() {
        let text = "POST http://h/a\n\
                    # [Body] 3\n\
                    # {\n\
                    #   \"a\": 1 // mine\n\
                    # }\n\
                    {\n  \"b\": 2\n}\n";
        let mut back = parse_hurl(text);
        let e = &mut back[0];
        assert!(e.stale_body_notes().is_some(), "the bodies disagree");
        assert!(e.can_adopt_body_notes());
        assert!(e.adopt_body_notes());

        assert_eq!(e.body_src.as_deref(), Some("{\n  \"a\": 1 // mine\n}"));
        assert_eq!(e.body_wire().as_deref(), Some("{\n  \"a\": 1\n}"));
        assert!(
            e.comments.is_empty(),
            "the block is the body now, not prose"
        );
        // And it round-trips as a live block again.
        let out = collection_to_hurl(&back);
        assert_eq!(
            parse_hurl(&out)[0].body_src.as_deref(),
            Some("{\n  \"a\": 1 // mine\n}")
        );
    }

    /// Notes that no longer strip down to JSON cannot be adopted: writing them
    /// as a body would put comments in the file and read back as an empty
    /// collection. Discarding is still allowed — it is the body that is at
    /// risk, not the notes.
    #[test]
    fn notes_that_would_not_survive_being_a_body_cannot_be_adopted() {
        // Four claimed lines, so the closing brace falls outside the block and
        // what is left does not parse.
        let text = "POST http://h/a\n\
                    # [Body] 4\n\
                    # {\n\
                    #     //extra comment\n\
                    #     \"a\": 2 // just a test\n\
                    #\n\
                    # }\n\
                    {\n    \"a\": 2\n}\n";
        let mut back = parse_hurl(text);
        let e = &mut back[0];
        assert!(e.stale_body_notes().is_some());
        assert!(!e.can_adopt_body_notes(), "it would not be valid Hurl");
        assert!(!e.adopt_body_notes());
        assert_eq!(
            e.body_wire().as_deref(),
            Some("{\n    \"a\": 2\n}"),
            "body untouched"
        );
    }

    /// Prose that happens to carry no comments still isn't a body. Adopting it
    /// would write text Hurl cannot parse, and a file that will not parse
    /// reads back as *no requests at all* — so one adopt could take a whole
    /// collection with it. The guard is "would this survive being written",
    /// not "did the comments strip cleanly".
    #[test]
    fn notes_that_are_not_a_body_at_all_cannot_be_adopted() {
        let text = "POST http://h/a\n\
                    # [Body] 1\n\
                    # hello world\n\
                    {\n  \"real\": 1\n}\n\
                    HTTP 200\n\n\
                    GET http://h/keepme\nHTTP 200\n";
        let mut back = parse_hurl(text);
        assert_eq!(back.len(), 2);
        let e = &mut back[0];
        assert!(
            e.stale_body_notes().is_some(),
            "the notes are still offered"
        );
        assert!(!e.can_adopt_body_notes(), "prose is not a body");
        assert!(!e.adopt_body_notes());
        assert_eq!(e.body_wire().as_deref(), Some("{\n  \"real\": 1\n}"));
        // The whole file still loads, which is the thing actually at stake.
        let out = collection_to_hurl(&back);
        assert_eq!(parse_hurl(&out).len(), 2, "no request was lost");
    }

    /// A marker claiming no lines describes no body. Offering it as leftover
    /// notes would put the indicator up for nothing, and adopting it would
    /// replace a perfectly good body with emptiness.
    #[test]
    fn a_body_marker_claiming_no_lines_is_not_leftover_notes() {
        let text = "POST http://h/a\n# [Body] 0\n{\n  \"real\": 1\n}\n";
        let mut back = parse_hurl(text);
        let e = &mut back[0];
        assert!(e.stale_body_notes().is_none());
        assert!(!e.can_adopt_body_notes());
        assert!(!e.adopt_body_notes());
        assert_eq!(e.body_wire().as_deref(), Some("{\n  \"real\": 1\n}"));
    }

    /// The count is read on the draw path, so a damaged one must not be able
    /// to bring the interface down. `usize::MAX` overflowed the addition that
    /// finds the end of the block.
    #[test]
    fn a_body_marker_claiming_the_whole_address_space_is_not_leftover_notes() {
        let text = "POST http://h/a\n# [Body] 18446744073709551615\n{\n  \"a\": 1\n}\n";
        let back = parse_hurl(text);
        assert!(back[0].stale_body_notes().is_none());
    }

    /// A block whose count overruns the comments below it is a damaged marker,
    /// not the end of the search — the same mistake the parser makes when a
    /// stale block spans a good one, and just as capable of hiding notes the
    /// user could otherwise resolve.
    #[test]
    fn an_overrunning_block_does_not_hide_a_well_formed_one_below_it() {
        let text = "POST http://h/a\n\
                    # [Body] 9\n\
                    # {\n\
                    #   \"old\": 1\n\
                    # }\n\
                    # [Body] 3\n\
                    # {\n\
                    #   \"b\": 9 // note\n\
                    # }\n\
                    {\n  \"real\": 1\n}\n";
        let back = parse_hurl(text);
        let (_, notes) = back[0]
            .stale_body_notes()
            .expect("the well-formed block is still found");
        assert_eq!(notes, "{\n  \"b\": 9 // note\n}");
    }

    /// Deleting a body leaves a stale block behind as prose, and writing a new
    /// body then puts a second block in the file. The good one must still be
    /// found: when the stale count happens to span it exactly, jumping past the
    /// block we matched first hid the real one completely, and a request whose
    /// notes were perfectly correct quietly stopped carrying them.
    #[test]
    fn a_stale_block_cannot_hide_the_good_one_beneath_it() {
        let text = "POST http://h/a\n\
                    # [Body] 7\n\
                    # {\n\
                    #   \"old\": 1\n\
                    # }\n\
                    # [Body] 3\n\
                    # {\n\
                    #   \"b\": 9 // new note\n\
                    # }\n\
                    {\n  \"b\": 9\n}\n";
        let back = parse_hurl(&text);
        assert_eq!(
            back[0].body_src.as_deref(),
            Some("{\n  \"b\": 9 // new note\n}"),
            "the good block was hidden by the stale one"
        );
        assert_eq!(back[0].body_wire().as_deref(), Some("{\n  \"b\": 9\n}"));
        // The stale block is still in the file, untouched.
        assert!(collection_to_hurl(&back).contains("#   \"old\": 1"));
    }
}

#[cfg(test)]
mod recovery_tests {
    use super::*;
    use crate::hurl::collection_to_hurl;

    /// The whole point: one damaged request used to cost the user every other
    /// request in the file.
    #[test]
    fn a_broken_request_no_longer_takes_the_file_with_it() {
        let text = "# one\nGET http://h/1\nHTTP 200\n\n\
                    # two\nPOST http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n\n\
                    # three\nGET http://h/3\nHTTP 200\n";
        assert!(
            parse_hurl_file(text).is_err(),
            "this really is an unparseable file"
        );
        let es = parse_hurl(text);
        assert_eq!(es.len(), 3);
        assert_eq!(es[0].url, "http://h/1");
        assert_eq!(es[2].url, "http://h/3");
        assert!(!es[0].is_unreadable() && !es[2].is_unreadable());
        assert!(es[1].is_unreadable(), "only the damaged one is text");
        assert_eq!(es[1].title, "two", "named, so it can be found again");
    }

    /// The text of what could not be read is kept exactly, and written back
    /// out exactly. A file that opens must not be a file that has been
    /// silently rewritten.
    #[test]
    fn unreadable_text_is_kept_and_written_back_unchanged() {
        let text = "# one\nGET http://h/1\nHTTP 200\n\n\
                    # two\nPOST http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n";
        let es = parse_hurl(text);
        let raw = es[1].unparsed.as_deref().expect("kept verbatim");
        assert!(raw.contains("[Captures]") && raw.contains("x: jsonpath \"$.a\""));
        let out = collection_to_hurl(&es);
        assert!(out.contains("# two\nPOST http://h/2\n[Captures]\nx: jsonpath \"$.a\""));
        // And it survives being read back in again, still as one piece.
        let again = parse_hurl(&out);
        assert_eq!(again.len(), 2);
        assert!(again[1].is_unreadable());
        assert_eq!(collection_to_hurl(&again), out, "a second save is a no-op");
    }

    /// The corruption the JSON-comments feature could produce — comments left
    /// in a body — is exactly the shape recovery exists for.
    #[test]
    fn a_body_with_comments_left_in_it_costs_only_its_own_request() {
        let text = "GET http://h/1\nHTTP 200\n\n\
                    POST http://h/2\n{\n  \"a\": 1 // note\n}\n\n\
                    GET http://h/3\nHTTP 200\n";
        let es = parse_hurl(text);
        assert_eq!(es.len(), 3);
        assert!(es[1].is_unreadable());
        assert!(
            collection_to_hurl(&es).contains("\"a\": 1 // note"),
            "the user's own text is still there to repair"
        );
    }

    /// The cut is a guess, so it must never be trusted on its own: a body
    /// containing something that reads like a request line is still one
    /// request.
    #[test]
    fn a_method_like_line_inside_a_body_does_not_split_a_request() {
        let text = "POST http://h/1\n```\nGET /inside is data\n```\nHTTP 200\n\n\
                    GET http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n";
        let es = parse_hurl(text);
        assert_eq!(es.len(), 2, "the good request was not cut in half");
        assert_eq!(es[0].url, "http://h/1");
        assert!(!es[0].is_unreadable());
        assert!(es[0].body_wire().unwrap().contains("GET /inside is data"));
    }

    /// A response line looks exactly like a request line. Cutting there would
    /// tear every request away from its own response.
    #[test]
    fn a_response_line_is_not_a_place_to_cut() {
        let text = "GET http://h/1\nHTTP 200\n[Asserts]\njsonpath \"$.a\" == 1\n\n\
                    GET http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n";
        let es = parse_hurl(text);
        assert_eq!(es.len(), 2);
        assert_eq!(es[0].expected_status, Some(200));
        assert_eq!(es[0].asserts, vec!["jsonpath \"$.a\" == 1".to_string()]);
    }

    /// Damage at either end is recovered the same way as damage in the middle.
    #[test]
    fn the_first_and_last_requests_are_recovered_too() {
        let broken_first = "POST http://h/1\n[Captures]\nx: jsonpath \"$.a\"\n\n\
                            GET http://h/2\nHTTP 200\n";
        let es = parse_hurl(broken_first);
        assert_eq!(es.len(), 2);
        assert!(es[0].is_unreadable() && !es[1].is_unreadable());

        let broken_last = "GET http://h/1\nHTTP 200\n\n\
                           POST http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n";
        let es = parse_hurl(broken_last);
        assert_eq!(es.len(), 2);
        assert!(!es[0].is_unreadable() && es[1].is_unreadable());
    }

    /// A file with nothing request-shaped in it is still "not a collection",
    /// which is how every caller recognises a file it should not have opened.
    #[test]
    fn text_that_is_not_a_collection_at_all_still_yields_nothing() {
        assert!(parse_hurl("hello\nworld\n").is_empty());
        assert!(parse_hurl("").is_empty());
        assert!(parse_hurl("\n\n   \n").is_empty());
        assert!(parse_hurl("# just a comment\n").is_empty());
    }

    /// Recovery may regroup text but must never invent or drop any of it.
    #[test]
    fn every_line_of_a_damaged_file_survives_somewhere() {
        let text = "# banner\n\n# one\nGET http://h/1\nHTTP 200\n\n\
                    # two\nPOST http://h/2\n[Captures]\nx: jsonpath \"$.a\"\n\n\
                    # three\nPUT http://h/3\n{\n  \"b\": 2\n}\nHTTP 201\n";
        let out = collection_to_hurl(&parse_hurl(text));
        for line in text.lines().filter(|l| !l.trim().is_empty()) {
            assert!(out.contains(line), "lost {line:?} from\n{out}");
        }
    }

    /// Damage next to a `# [Reports]` block must not move the block into the
    /// following request, where it would be read as *its* report fields.
    #[test]
    fn a_reports_block_is_not_pulled_into_the_next_request() {
        let text = "GET http://h/1\nHTTP 200\n# [Reports]\n# code: status\n\
                    GET http://h/2\nHTTP 200\n\n\
                    POST http://h/3\n[Captures]\nx: jsonpath \"$.a\"\n";
        let es = parse_hurl(text);
        let with_reports: Vec<_> = es.iter().filter(|e| !e.reports.is_empty()).collect();
        assert_eq!(with_reports.len(), 1, "exactly one request has reports");
        assert_eq!(with_reports[0].url, "http://h/1");
    }
}

#[cfg(test)]
mod recovery_hardening_tests {
    use super::*;
    use crate::hurl::collection_to_hurl;

    /// The worst thing recovery could do is invent requests. A multiline body
    /// full of lines that read like requests — an HTTP log, a list of routes —
    /// must not be cut into fragments, because each fragment then looks like a
    /// request of its own and a "Run All" would send it.
    #[test]
    fn a_body_full_of_request_like_lines_is_never_cut_into_requests() {
        let mut body = String::new();
        for k in 0..40 {
            body.push_str(&format!("GET /orders/{k}\n"));
        }
        let text = format!(
            "GET http://h/broken\n[Captures]\nx: jsonpath \"$.a\"\n\n\
             POST http://h/bulk\n```\n{body}```\nHTTP 200\n"
        );
        assert!(parse_hurl_file(&text).is_err(), "the file really is broken");

        let es = parse_hurl(&text);
        assert_eq!(es.len(), 2, "one broken request and one good one: {es:#?}");
        assert!(es[0].is_unreadable());
        assert!(!es[1].is_unreadable());
        assert_eq!(es[1].url, "http://h/bulk");
        let sent = es[1].body_wire().expect("the body survived");
        for k in 0..40 {
            assert!(sent.contains(&format!("GET /orders/{k}")), "lost line {k}");
        }
        // Nothing that would be sent was invented.
        assert!(
            es.iter()
                .all(|e| e.is_unreadable() || e.url.starts_with("http"))
        );
        // And saving it does not rewrite the body.
        let once = collection_to_hurl(&es);
        assert_eq!(collection_to_hurl(&parse_hurl(&once)), once, "stable");
    }

    /// Recovery runs on the thread that is drawing the interface, so the work
    /// it does has to stay in proportion to the file. Joining pieces together
    /// only ever helps a piece that was cut off part-way through; doing it for
    /// every request in a large damaged file cost minutes.
    #[test]
    fn recovering_a_large_damaged_file_is_quick() {
        let filler: String = (0..120)
            .map(|i| format!("  \"key_{i}\": \"value {i}\",\n"))
            .collect();
        let mut text = String::new();
        for k in 0..1500 {
            text.push_str(&format!(
                "POST http://h/{k}\n[Captures]\nx: jsonpath \"$.a\"\n{filler}\n"
            ));
        }
        let started = std::time::Instant::now();
        let es = parse_hurl(&text);
        let took = started.elapsed();
        assert_eq!(es.len(), 1500);
        assert!(
            took < std::time::Duration::from_secs(8),
            "recovering a 4MB damaged file took {took:?}"
        );
    }

    /// Recovery must attribute a comment to the same request the ordinary
    /// parser would. A block directly above a method line is that request's
    /// name — that is the rule everywhere else, and recovery disagreeing with
    /// it would move names around as a file was repaired.
    #[test]
    fn a_comment_above_a_method_line_names_the_same_request_either_way() {
        let healthy = "GET http://h/1\nHTTP 200\n# note\nPOST http://h/2\nHTTP 200\n";
        let healthy = parse_hurl(healthy);
        assert_eq!(healthy[1].title, "note", "the ordinary parser's rule");

        let broken = "GET http://h/1\n[Captures]\nx: jsonpath \"$.a\"\n\
                      # note\nPOST http://h/2\nHTTP 200\n";
        let broken = parse_hurl(broken);
        assert!(broken[0].is_unreadable());
        assert_eq!(broken[1].title, "note", "recovery follows the same rule");
    }

    /// A fenced body that swallows what follows it must still be recoverable:
    /// the piece is cut off rather than faulty, so joining the next piece on is
    /// exactly the case joining exists for.
    #[test]
    fn a_body_cut_off_by_a_damaged_fence_is_still_recovered() {
        let text = "POST http://h/1\n```\nGET /a\nGET /b\n```\nHTTP 200\n\n\
                    GET http://h/2\nHTTP 200\n";
        let es = parse_hurl(text);
        assert_eq!(es.len(), 2);
        assert!(es.iter().all(|e| !e.is_unreadable()));
        assert_eq!(es[1].url, "http://h/2");
    }

    /// Regression: `-` and `=` are stripped only as surrounding decoration.
    /// Stripping them everywhere meant our own serializer wrote a name our own
    /// parser could not read back, so "Get user-profile" became "Get
    /// userprofile" on load and was written back that way on the next save.
    #[test]
    fn a_hyphen_or_equals_inside_a_title_survives_a_round_trip() {
        let entry =
            HurlEntry::from_fields("Get user-profile v2=beta", "GET", "http://h/x", vec![], "");
        let text = collection_to_hurl(&[entry]);
        let back = parse_hurl(&text);
        assert_eq!(back.len(), 1);
        assert_eq!(back[0].title, "Get user-profile v2=beta");
    }

    /// ...while a banner drawn around a name is still decoration, and goes.
    #[test]
    fn a_banner_around_a_title_is_still_stripped() {
        let entries = parse_hurl("# ==== Login ====\nGET http://h/x\n");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].title, "Login");
    }
}