zond-engine 0.16.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # Scan Reports
//!
//! The finished record of a scan: what was asked for, what came back, what went
//! wrong on the way, and under which settings.
//!
//! During a scan a caller watches [`ScanSession`](crate::scanner::session::ScanSession) -
//! a live store plus an event stream, both of which describe the present moment
//! and keep no history. A [`ScanReport`] is the other half of that pair. It is
//! produced once, when the scan is over, and it is the only thing that can
//! answer a question asked afterwards: how long the sweep took, whether a
//! strategy failed part way through, how many addresses were actually in scope,
//! which retry budget produced this particular set of hosts.
//!
//! That distinction matters because a bare list of hosts is not a result anyone
//! can act on. "Nine hosts on a /24" means one thing after a
//! [`Thorough`](crate::config::ScanEffort::Thorough) privileged
//! sweep and quite another after an unprivileged connect fallback that lost its
//! routed scanner to a permissions error. The hosts are identical in both; only
//! the report separates them.
//!
//! ## Phases
//!
//! Discovery and port scanning are separate engine calls, and a caller that
//! runs both is describing one job, not two. A report therefore holds a list of
//! [`ScanPhase`] records rather than a single set of metadata, and
//! [`ScanReport::merge`] folds the second call into the first: hosts are
//! merged by [`Host::merge`], phases are appended in the order they ran. A
//! single-phase report is simply the common case of that shape, not a different
//! type.
//!
//! ## Findings and instrumentation
//!
//! A phase carries two different kinds of record and they must not be read as
//! one. The hosts and their ports are findings *about the network*. The
//! [`ProbeStats`] a raw scanner files are measurements *about the scan* - how
//! many probes went out, how many segments came back, why the loop stopped -
//! and they exist to bound how much the findings can be trusted. A sweep that
//! stopped on [`StopReason::DeadlineExpired`] while replies were still arriving
//! found fewer hosts than the network holds, and nothing in the host list says
//! so.
//!
//! ## What is stored and what is derived
//!
//! Only measurements are stored. Every count a consumer might want - hosts up,
//! open ports, services identified - is computed by [`ScanReport::summary`] from
//! the hosts themselves, so a summary cannot drift out of step with the data it
//! describes.
//!
//! Hosts are held in a [`BTreeMap`] keyed by primary IP, so two scans of the
//! same network serialize in the same order and their outputs can be diffed.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use crate::config::DetectionEnvelope;
use crate::config::RetryConfig;
use crate::config::{IdleScan, OsDetection, ServiceDetection, ZondConfig};
use crate::evasion::EvasionProfile;
use crate::model::capture::CaptureCounts;
use crate::model::exclusion::Exclusions;
use crate::model::host::{Host, HostStatus};
use crate::model::ip::range::{IpRange, Ipv4Range, Ipv6Range};
use crate::model::ip::scoped::{ScopedIp, Zone};
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::{PortSet, PortState, Protocol};
use crate::model::target::{TargetMap, TargetSet};
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::system::privilege::Privilege;
use crate::transport::probe::SendMode;

/// The version of the engine that produced a report.
pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");

// --------------------------------------------------------------------------
// What a scan was asked to do
// --------------------------------------------------------------------------
//
// The request, as the report has to record it. A reader asks these of a result
// before they ask what it found: over what range, on which ports, under which
// technique, with how much patience.

/// Which of the two scan phases a [`ScanPhase`] records.
///
/// These are the engine's two entry points, [`discover`](crate::scanner::discover)
/// and [`scan`](crate::scanner::scan), not the individual strategies each one
/// spawns. Which strategies ran is a property of the host and its privileges;
/// see [`ScannerKind`] for the granularity at which failures are reported.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScanKind {
    /// Establishing which hosts in a target range are alive.
    Discovery,
    /// Classifying the ports of a known set of hosts.
    PortScan,
    /// Reading what a link already carries, having sent nothing.
    ///
    /// Unlike the other two, this phase covers no address. see
    /// [`TargetScope::listening_on`]. It can raise a claim and never lower one:
    /// having sent nothing, it cannot have timed anything out, so silence from
    /// an address proves nothing about it.
    Listen,
}

impl ScanKind {
    /// Every phase kind this build knows, in declaration order.
    ///
    /// Here for the reason [`Protocol::ALL`](crate::model::port::Protocol::ALL)
    /// gives: the enum is `#[non_exhaustive]`, and the export conformance suite
    /// reads this list against the published schema's own and fails unless they hold
    /// the same names. A variant added without a place in the schema is a value this
    /// engine writes and no consumer's validator accepts.
    pub const ALL: [ScanKind; 3] = [Self::Discovery, Self::PortScan, Self::Listen];
}

impl fmt::Display for ScanKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScanKind::Discovery => write!(f, "discovery"),
            ScanKind::PortScan => write!(f, "port scan"),
            ScanKind::Listen => write!(f, "listen"),
        }
    }
}

/// Which ports a phase walked, and whether it walked the same ones everywhere.
///
/// A scope records the addresses a phase covered, and for a port scan that is
/// only half the answer: an address is covered *for some ports*, and a consumer
/// asking whether one endpoint was probed needs to know which. This is that
/// second half.
///
/// The four variants are the four honest answers, and the distinctions between
/// them are the whole reason this is not a bare `Option<PortSet>`.
///
/// [`Every`](Self::Every) against [`Mixed`](Self::Mixed): a phase can be given
/// different ports for different addresses: `192.0.2.0/24:80,443` alongside
/// `198.51.100.0/24:8080` is one job with two units, and there is no single set
/// that is true of every address in it. Publishing the union as though there
/// were would have a consumer conclude that `192.0.2.5` was probed on 8080,
/// which nothing did. So the union is published as a union and labelled one.
///
/// [`NoPorts`](Self::NoPorts) against [`Unstated`](Self::Unstated): a discovery
/// sweep walked no ports, which is a fact, and a record that does not say which
/// ports were walked is an absence of one. Only the first supports concluding
/// that an endpoint was not probed. Nothing this engine builds is `Unstated`;
/// it is what a report from another tool, or from a build older than this
/// field, reads back as.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum PortScope {
    /// The record does not say which ports were walked.
    ///
    /// Nothing may be concluded about any endpoint. The default, because a
    /// scope rebuilt from a record that predates this field knows nothing about
    /// ports and must not pretend otherwise.
    #[default]
    Unstated,
    /// The phase paired no ports with its addresses, which is what a discovery
    /// sweep does. Its probes are the strategy's choice rather than the
    /// caller's, and no endpoint was probed.
    NoPorts,
    /// Every address the phase walked was walked for these ports.
    ///
    /// The ordinary case for a port scan, and the only variant from which a
    /// consumer may conclude that a particular endpoint of a covered address was
    /// probed.
    Every(PortSet),
    /// Addresses were walked for differing sets of ports, and this is their
    /// union.
    ///
    /// A port here was walked for at least one address and not necessarily for
    /// any given one. A port *not* here was walked for none, which is the one
    /// conclusion this variant does support.
    Mixed(PortSet),
}

impl PortScope {
    /// The ports the phase walked, over all of its addresses.
    ///
    /// `None` where there are none to report or none recorded. Read this to
    /// describe what a scan reached; read [`covers`](Self::covers) to ask about
    /// one endpoint.
    pub fn ports(&self) -> Option<&PortSet> {
        match self {
            PortScope::Unstated | PortScope::NoPorts => None,
            PortScope::Every(ports) | PortScope::Mixed(ports) => Some(ports),
        }
    }

    /// Whether the phase walked `port` on `protocol`, for every address it
    /// covered.
    ///
    /// `None` is "the record cannot say", which is both a scope that recorded no
    /// ports and one whose addresses were walked for differing sets with this
    /// port among them. `Some(false)` is a real negative: no address in the
    /// phase was walked for this endpoint.
    pub fn covers(&self, port: u16, protocol: Protocol) -> Option<bool> {
        match self {
            PortScope::Unstated => None,
            PortScope::NoPorts => Some(false),
            PortScope::Every(ports) => Some(ports.contains(port, protocol)),
            PortScope::Mixed(ports) => {
                if ports.contains(port, protocol) {
                    None
                } else {
                    Some(false)
                }
            }
        }
    }

    /// The scope of a set of units, which is [`Every`](Self::Every) when they
    /// agree and [`Mixed`](Self::Mixed) when they do not.
    fn of<'a>(units: impl Iterator<Item = &'a PortSet>) -> Self {
        let mut units = units;
        let Some(first) = units.next().cloned() else {
            return PortScope::NoPorts;
        };

        let mut united = first.clone();
        let mut agreed = true;
        for ports in units {
            agreed &= *ports == first;
            united = united.union(ports);
        }

        if united.is_empty() {
            PortScope::NoPorts
        } else if agreed {
            PortScope::Every(united)
        } else {
            PortScope::Mixed(united)
        }
    }
}

/// What a phase was asked to cover, and what it was forbidden to.
///
/// The ranges are the canonical, merged form the engine actually iterated, not
/// the text a user typed. Overlapping arguments have already been coalesced, so
/// `addresses` is a count of distinct addresses rather than a sum of what was
/// requested, and a report can be trusted when it says a sweep covered 254
/// hosts.
///
/// [`ranges`](Self::ranges) is what was walked *after* the exclusion policy was
/// applied, and [`excluded`](Self::excluded) is that policy. The two together
/// are what makes a report evidence of scope rather than a list of findings: one
/// says where the scan went, the other says where it was told not to, and no
/// host in the report may fall inside the second.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetScope {
    ranges: Vec<IpRange>,
    links: Vec<Zone>,
    /// Links whose traffic was read without anything being sent to them.
    ///
    /// Deliberately not [`links`](Self::links), which means *swept*: a probe
    /// went out that everything on the link was obliged to answer, so a host
    /// there and not in the report is a host that was not there. Nothing of the
    /// kind follows from having listened: a machine that said nothing during
    /// the window is indistinguishable from one that is absent, and there is no
    /// experiment that separates them.
    ///
    /// Recorded because a reader still wants to know where a phase was
    /// standing. It never contributes to coverage, which is what keeps a quiet
    /// host from reading as one that went away.
    listened: Vec<Zone>,
    addresses: u128,
    probes: Option<u128>,
    ports: PortScope,
    protocols: Vec<Protocol>,
    excluded: Vec<IpRange>,
    withheld: u128,
}

impl TargetScope {
    /// The scope of a discovery sweep, which has no port dimension.
    ///
    /// Canonicalizes the set, so the recorded ranges are the merged ones the
    /// sweep iterates rather than the raw arguments it was built from.
    ///
    /// `ips` comes back narrowed, with everything `exclusions` forbids taken
    /// out of it, and the scope records what that cost. Applying the policy and
    /// recording it are one call because doing either without the other is the
    /// bug: a scope recorded before the subtraction overstates what was covered,
    /// and a subtraction with no scope to record it leaves a report that cannot
    /// show the exclusion was honoured. There is no way to write one and forget
    /// the other, which is the whole reason this takes `&mut`.
    ///
    /// Pass [`Exclusions::none`] where no policy is in force.
    pub fn from_ip_set(ips: &mut IpSet, exclusions: &Exclusions) -> Self {
        let withheld = exclusions.withhold(ips);
        ips.canonicalize();

        let ranges = ip_set_ranges(ips);
        let addresses = ips.len();

        Self {
            listened: Vec::new(),
            ranges,
            links: Vec::new(),
            addresses,
            probes: None,
            ports: PortScope::NoPorts,
            protocols: Vec::new(),
            excluded: exclusions.ranges(),
            withheld,
        }
    }

    /// The scope of a phase that sent nothing and read what `links` carried.
    ///
    /// Covers no address, and says so. A listener did not probe, so it
    /// cannot have timed anything out, so there is no address it can report as
    /// empty. The count is zero and the ranges are none, which is not a
    /// missing measurement but the honest one, and it is what stops a
    /// comparison reading a host that stayed quiet as a host that disappeared.
    ///
    /// The links are recorded as [`listened`](Self::listened) rather than as
    /// [`links`](Self::links), and the distinction is the whole of the above.
    ///
    /// `exclusions` is recorded so the report still shows the policy a passive
    /// phase was run under: it withholds nothing here, because nothing was
    /// enumerated for it to withhold, and it is enforced where it matters at
    /// the point findings are recorded.
    pub fn listening_on(links: Vec<Zone>, exclusions: &Exclusions) -> Self {
        Self {
            ranges: Vec::new(),
            links: Vec::new(),
            listened: links,
            addresses: 0,
            probes: None,
            ports: PortScope::NoPorts,
            protocols: Vec::new(),
            excluded: exclusions.ranges(),
            withheld: 0,
        }
    }

    /// The scope of a port scan, which pairs addresses with ports.
    ///
    /// `probes` counts address/port/protocol combinations, the unit a port scan
    /// is actually billed in. It is `None` when the target map is large enough
    /// to overflow that count, which is a failure to measure and is reported as
    /// one rather than as a plausible-looking number.
    ///
    /// `targets` comes back narrowed, on the same terms and for the same
    /// reasons as [`from_ip_set`](Self::from_ip_set). A unit left holding no
    /// address at all is dropped.
    pub fn from_target_map(targets: &mut TargetMap, exclusions: &Exclusions) -> Self {
        let withheld = exclusions.withhold_targets(targets);

        let mut ranges = Vec::new();
        let mut protocols = Vec::new();
        for unit in &targets.units {
            ranges.extend(ip_set_ranges(unit.ips()));
            for (_, protocol) in unit.ports().iter() {
                if !protocols.contains(&protocol) {
                    protocols.push(protocol);
                }
            }
        }
        ranges.sort_by_key(|range| (range.start_addr(), range.end_addr()));
        ranges.dedup();
        protocols.sort();

        let addresses = targets.gross_ips().unwrap_or(0);
        let probes = targets.gross_targets().ok();
        let ports = PortScope::of(targets.units.iter().map(TargetSet::ports));

        Self {
            listened: Vec::new(),
            ranges,
            links: Vec::new(),
            addresses,
            probes,
            ports,
            protocols,
            excluded: exclusions.ranges(),
            withheld,
        }
    }

    /// The address ranges covered, in ascending order.
    pub fn ranges(&self) -> &[IpRange] {
        &self.ranges
    }

    /// How many distinct addresses were in scope.
    pub fn addresses(&self) -> u128 {
        self.addresses
    }

    /// How many address/port/protocol combinations were in scope, or `None` for
    /// a discovery sweep and for a target set too large to count.
    pub fn probes(&self) -> Option<u128> {
        self.probes
    }

    /// The links this phase swept whole, by the interface each is on.
    ///
    /// [`ranges`](Self::ranges) is what a target set named, and for a sweep of a
    /// local segment that is only part of what was covered: an all-nodes
    /// solicitation is one probe every IPv6 neighbour on the link is required to
    /// answer, and it reaches hosts holding addresses nobody could have named in
    /// advance.
    ///
    /// A link is not an address range and is not recorded as one.
    /// `fe80::/64` would be the obvious thing to put in `ranges`, and it
    /// would make [`addresses`](Self::addresses) read eighteen quintillion:
    /// destroying the one property that type has, that a report saying it
    /// covered 254 hosts can be believed. A link is named by its interface, so
    /// that is what is recorded.
    ///
    /// Empty for a phase that swept no segment, which is every port scan and
    /// every sweep of a routed range.
    pub fn links(&self) -> &[Zone] {
        &self.links
    }

    /// The links this phase read traffic from without probing them.
    ///
    /// Never coverage. See the field's own documentation, and
    /// [`listening_on`](Self::listening_on).
    pub fn listened(&self) -> &[Zone] {
        &self.listened
    }

    /// Whether this phase swept the link a host was found on.
    ///
    /// The question is about the link, not about the addresses on it. An
    /// all-nodes solicitation reaches every IPv6 host on the segment whatever
    /// addresses it holds, and a host that answers one is routinely keyed under
    /// a global address: this engine prefers a routable address over a
    /// link-local one when both are known. Asking whether the *address* is
    /// link-local would then miss exactly the hosts this exists to cover.
    ///
    /// `zone` is the interface the host was found on, which a record carries
    /// whenever a local scanner put it there. A host with no zone was not found
    /// on a link and is not claimed.
    pub fn swept(&self, zone: Option<&Zone>) -> bool {
        let Some(zone) = zone else {
            return false;
        };

        self.links.iter().any(|link| link.name() == zone.name())
    }

    /// Records that this phase swept a link whole.
    ///
    /// Called once a phase is over, because which links its strategies reached
    /// is only knowable then: the scope itself is fixed before a probe goes
    /// out. See
    /// [`PhaseRecorder::finish`](crate::scanner::recorder::PhaseRecorder::finish).
    pub(crate) fn record_sweeps(&mut self, links: Vec<Zone>) {
        for link in links {
            if !self.links.iter().any(|held| held.name() == link.name()) {
                self.links.push(link);
            }
        }
    }

    /// Which ports the phase walked, and whether it walked the same ones for
    /// every address.
    ///
    /// [`probes`](Self::probes) counts the address-and-port combinations in
    /// scope; this says which ports they were. The two are separate because a
    /// count survives a target set too large to enumerate and a set does not.
    pub fn ports(&self) -> &PortScope {
        &self.ports
    }

    /// The transport protocols the phase was asked about, deduplicated and in
    /// ascending [`Protocol`] order, which puts TCP before UDP.
    ///
    /// Empty for a discovery sweep, whose probes are the strategy's choice
    /// rather than the caller's.
    pub fn protocols(&self) -> &[Protocol] {
        &self.protocols
    }

    /// The address ranges the phase was forbidden to probe, in ascending order.
    ///
    /// The exclusion policy that was in force, merged, whether or not it
    /// overlapped anything this phase would have covered. Empty means no policy
    /// was set: not that one was set and did nothing, which is
    /// [`withheld`](Self::withheld) returning zero and is a different fact.
    ///
    /// This is the half of the record a reader can check the engine against.
    /// Every range here is ground the report promises it did not cover, and no
    /// host in the report may fall inside one.
    pub fn excluded(&self) -> &[IpRange] {
        &self.excluded
    }

    /// How many addresses the exclusion policy took out of this phase.
    ///
    /// Measured against what the phase was handed, at the moment its scope was
    /// recorded, so it is the overlap between the policy and this phase's
    /// input, not the size of the policy. Zero from a policy that named ground
    /// this phase was never going to walk, and zero again from a phase whose
    /// input an earlier one had already narrowed.
    ///
    /// It is the difference between a scope document that was applied and one
    /// that was merely configured, and those look identical without it.
    pub fn withheld(&self) -> u128 {
        self.withheld
    }
}

/// Returns every range of a set as protocol-agnostic [`IpRange`] values.
fn ip_set_ranges(ips: &IpSet) -> Vec<IpRange> {
    let v4 = ips.v4().iter().copied().map(IpRange::V4);
    let v6 = ips.v6().iter().copied().map(IpRange::V6);
    v4.chain(v6).collect()
}

/// What a scan changed about the packets it sent, to read a finding against.
///
/// Each field holds the value the scan used for one evasion technique, or `None`
/// where it left the default alone: a scan that pinned a source port but not the
/// hop limit has [`source_port`](Self::source_port) set and [`ttl`](Self::ttl)
/// `None`. A port's state under a probe from source port 53 is a different fact
/// than the same state under an ordinary probe, and this is where a reader tells
/// the two apart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EvasionRecord {
    /// The source port every probe left from, or `None` if the scan did not pin
    /// one.
    pub source_port: Option<u16>,
    /// The hop limit (IPv4 TTL / IPv6 hop limit) every ordinary probe carried,
    /// or `None` if the scan kept the default.
    pub ttl: Option<u8>,
    /// The number of random bytes appended to each probe's payload, or `None` if
    /// the scan padded nothing.
    pub padding: Option<u16>,
    /// Whether TCP probes carried a deliberately wrong checksum.
    pub bad_tcp_checksum: bool,
    /// The hardware address every frame claimed to come from, or `None` if the
    /// scan used the interface's own.
    pub spoof_mac: Option<MacAddr>,
    /// The largest each IP fragment a probe was split into, in bytes, or `None`
    /// if the scan sent probes whole.
    pub fragment: Option<u16>,
    /// The addresses probes were also sent from as decoys, or empty if the scan
    /// sent from this host alone.
    pub decoys: Vec<IpAddr>,
    /// The exact TCP flag byte every port probe carried in place of the
    /// technique's own, or `None` if the scan sent the technique's. The bits are
    /// those of [`crate::protocols::tcp::flags`].
    pub flags: Option<u8>,
}

impl EvasionRecord {
    /// The record of what an [`EvasionProfile`] changed, or `None` if it changed
    /// nothing.
    #[must_use]
    pub fn from_profile(profile: &EvasionProfile) -> Option<Self> {
        profile.is_active().then(|| Self {
            source_port: profile.source_port,
            ttl: profile.ttl,
            padding: profile.padding,
            bad_tcp_checksum: profile.bad_tcp_checksum,
            spoof_mac: profile.spoof_mac,
            fragment: profile.fragment,
            decoys: profile.decoys.clone(),
            flags: profile.flags,
        })
    }
}

/// The settings that shaped what a phase did.
///
/// A subset of [`ZondConfig`]: the fields here are the ones that
/// change which packets went out and how long the engine waited for answers, so
/// they are the ones needed to interpret - or reproduce - a result. The rest of
/// the config drives presentation (banner, verbosity, key handling) and has no
/// bearing on the finding, so recording it would only invite a reader to treat
/// a quieter terminal as a different scan.
///
/// Keeping this separate from [`ZondConfig`] also means the two can evolve
/// independently: a new interface knob does not silently become part of every
/// exported report.
#[derive(Debug, Clone, PartialEq)]
pub struct ScanSettings {
    /// How raw probes were placed on the wire.
    pub send_mode: SendMode,
    /// Which segment each TCP port probe carried, and so what its answers mean.
    ///
    /// Two ports both reported `Closed` are different findings depending on
    /// this: one refused a connection attempt, the other reset a segment that
    /// was not one. A report without it cannot be read.
    pub tcp_technique: TcpScanTechnique,
    /// Which chunk each SCTP port probe carried, and so what its answers mean.
    ///
    /// Recorded for the reason [`tcp_technique`](Self::tcp_technique) is. An
    /// SCTP port reported `open_filtered` came from a COOKIE-ECHO scan, which
    /// cannot report one open at all; the same port under an INIT scan would
    /// have been settled either way.
    pub sctp_technique: SctpScanTechnique,
    /// The retransmission budget and patience in force.
    pub retry: RetryConfig,
    /// The probe-rate ceiling, or `None` if the scanner's own default applied.
    pub max_probe_rate: Option<std::num::NonZeroU32>,
    /// The probe-rate floor, or `None` if the scan was free to settle wherever
    /// it liked.
    ///
    /// Recorded because it bounds a reading of the traffic as much as the
    /// ceiling does. A scan that emitted more packets than its targets were
    /// answering did so because it was told to finish, and a reader comparing
    /// two runs needs the floor in front of them before concluding the network
    /// got noisier.
    pub min_probe_rate: Option<std::num::NonZeroU32>,
    /// The shortest gap kept between two probes at one host, or `None` if none
    /// was asked for.
    ///
    /// Recorded because it bounds how long a phase's own numbers took to reach.
    /// A sweep of a thousand addresses spaced a tenth of a second apart cannot
    /// have finished in under a hundred seconds, and a reader comparing two runs
    /// needs to see the spacing before reading the slower one as a slower
    /// network.
    pub host_probe_interval: Option<Duration>,
    /// The wall-clock budget each host was given, or `None` if none was set.
    ///
    /// Recorded because it bounds what a host's entry can say. A machine with
    /// three open ports out of a thousand is a different finding depending on
    /// whether the other nine hundred and ninety-seven were asked; which hosts
    /// actually ran out is [`ScanPhase::timed_out`].
    pub host_timeout: Option<Duration>,
    /// The wall-clock budget the whole phase was given, or `None` if none was
    /// set.
    ///
    /// Recorded for the same reason as [`host_timeout`](Self::host_timeout),
    /// one level up: a phase that stopped on this covered less than it was
    /// asked to, and a reader comparing two runs of the same schedule needs to
    /// know the bound was there before concluding the network changed.
    pub scan_timeout: Option<Duration>,
    /// Whether name resolution was permitted to generate traffic.
    pub dns_enabled: bool,
    /// Whether the caller asked for identifying detail to be masked.
    pub redact: bool,
    /// How far the phase went to identify the operating system behind each host.
    ///
    /// A host reported without one is a different finding depending on this: at
    /// [`OsDetection::Off`] nothing looked, and at any other level something
    /// looked and found nothing conclusive. The level also bounds how much of
    /// this phase's traffic the engine originated. see
    /// [`OsDetection::is_active`].
    pub os_detection: OsDetection,
    /// How far the phase went to identify what was listening behind each open
    /// port.
    ///
    /// A port reported with no service is a different finding depending on
    /// this: at [`ServiceDetection::Off`] nothing asked, and at any other level
    /// something asked and could not tell. It also says whether the phase
    /// completed a connection to each open port at all, which is what a target's
    /// application logs would have recorded.
    pub service_detection: ServiceDetection,

    /// How intrusive a detection the phase was permitted to run over the services
    /// it identified.
    ///
    /// Recorded because it decides which findings could appear at all: a port
    /// with no vulnerability finding is one thing when the envelope permitted the
    /// detection that would have found one, and another when it withheld it. The
    /// report says which, so a reader is not left to guess whether a clean port
    /// was probed or spared.
    pub detection: DetectionEnvelope,

    /// Whether the phase measured the route to each host that answered.
    ///
    /// Recorded because a host with no path is two different findings: a scan
    /// that did not look, and a scan that looked and got nothing back. Only this
    /// separates them.
    pub traceroute: bool,

    /// Whether the phase characterised the filter in front of each host that
    /// answered.
    ///
    /// Recorded for the same reason as [`traceroute`](Self::traceroute): a host
    /// with no filtering finding is two things, a scan that did not look, and
    /// one that looked and the filter showed nothing, and only this tells them
    /// apart.
    pub characterise: bool,

    /// Which IP protocols the phase asked each host that answered about,
    /// ascending.
    ///
    /// Recorded for the reason [`characterise`](Self::characterise) is, and it
    /// carries the numbers rather than a flag because the question is per
    /// protocol: a host with no verdict for 47 is one the pass never named, and
    /// only this says which those were.
    pub ip_protocols: Vec<u8>,

    /// Whether the phase established what each TLS port accepts, rather than
    /// only what one handshake negotiated.
    ///
    /// Recorded for the reason [`characterise`](Self::characterise) is. A port
    /// whose security block names one version and lists no accepted suites is
    /// two different findings: a scan that never enumerated, and one that did
    /// and found an endpoint refusing every offer it was given.
    pub tls_enumeration: bool,

    /// What the scan changed about the packets it sent, or `None` if it changed
    /// nothing. A filtered port found with a probe from a trusted source port is
    /// a different fact than the same port found with an ordinary probe; see
    /// [`EvasionRecord`].
    pub evasion: Option<EvasionRecord>,

    /// The zombie a TCP port scan read its verdicts through, or `None` for an
    /// ordinary scan. Its presence is what tells a reader the ports were inferred
    /// from a third party's counter rather than from the target's own replies,
    /// which changes what an `open` or a `closed_filtered` means. See
    /// [`IdleScan`].
    pub idle_scan: Option<IdleScan>,

    /// Whether the capture kept ICMP errors for a technique that did not need
    /// them for its verdict.
    ///
    /// Recorded because it decides what a silence means. A filtered port carries
    /// [`ScanResponse::NoResponse`](crate::model::port::discovery::ScanResponse::NoResponse)
    /// either way, and only this says whether that is a port nothing answered
    /// for or a port whose refusal the scan was not listening for.
    pub icmp_evidence: bool,
}

impl From<&ZondConfig> for ScanSettings {
    /// What a phase records about the request behind it.
    ///
    /// Destructured with every field named rather than read through `cfg.`,
    /// which is the same technique
    /// [`ProbeTuning`](crate::config::ProbeTuning) uses on this type and for
    /// the same reason: a field added to [`ZondConfig`] is then a compile error
    /// here rather than a setting the report quietly stops carrying. What this
    /// records is the whole of why a report exists, nine hosts after a
    /// thorough privileged sweep and nine after an unprivileged fallback are the
    /// same nine hosts and not the same result, so a field going missing here
    /// costs more than it does anywhere else the config is read.
    fn from(cfg: &ZondConfig) -> Self {
        let ZondConfig {
            send_mode,
            tcp_technique,
            sctp_technique,
            retry,
            max_probe_rate,
            min_probe_rate,
            host_probe_interval,
            host_timeout,
            scan_timeout,
            no_dns,
            redact,
            os_detection,
            service_detection,
            detection,
            traceroute,
            characterise,
            ip_protocols,
            tls_enumeration,
            evasion,
            idle_scan,
            icmp_evidence,

            // Recorded elsewhere, and named so that dropping one is a decision
            // rather than an omission. The exclusion policy and whether the
            // sweep went beyond its targets are both properties of what a phase
            // *covered*, which is `TargetScope`'s to say; `assume_up` is
            // visible in the phase list, since a scan that skipped the liveness
            // pass records no discovery phase.
            exclusions: _,
            segment_sweep: _,
            assume_up: _,

            // Not recorded: which local source a scan was pinned to is transport
            // plumbing the findings do not turn on. Unlike `send_mode` it names
            // host-specific addresses, so it waits for a reader that needs it.
            send_source: _,
        } = cfg;

        Self {
            send_mode: *send_mode,
            tcp_technique: *tcp_technique,
            sctp_technique: *sctp_technique,
            retry: *retry,
            max_probe_rate: *max_probe_rate,
            min_probe_rate: *min_probe_rate,
            host_probe_interval: *host_probe_interval,
            host_timeout: *host_timeout,
            scan_timeout: *scan_timeout,
            dns_enabled: !no_dns,
            redact: *redact,
            os_detection: *os_detection,
            service_detection: *service_detection,
            detection: *detection,
            traceroute: *traceroute,
            characterise: *characterise,
            ip_protocols: ip_protocols.iter().copied().collect(),
            tls_enumeration: *tls_enumeration,
            evasion: EvasionRecord::from_profile(evasion),
            idle_scan: *idle_scan,
            icmp_evidence: *icmp_evidence,
        }
    }
}

// --------------------------------------------------------------------------
// What a scan measured about itself
// --------------------------------------------------------------------------
//
// Instrumentation, not findings. These bound how much the host list can be
// trusted: a sweep that stopped on a deadline while replies were still arriving
// found fewer hosts than the network holds, and nothing in the hosts says so.

/// Upper bounds, in milliseconds, of the discovery-time histogram buckets in
/// [`ProbeStats::found_at`]. A final bucket catches everything later than the
/// last bound.
///
/// These measure how far into the run a host was first credited, **not** its
/// round trip. The two diverge exactly where it matters: a host found at 700 ms
/// because its third attempt went out at 690 ms has a 10 ms round trip, and
/// reading the bucket as latency turns a retry schedule into an imaginary slow
/// path. Round trips are reported per host, not here.
///
/// Spaced roughly logarithmically because the question being asked spans three
/// orders of magnitude: a same-segment reply lands under a millisecond, a
/// healthy internet round trip in the tens, and a host recovered by a late
/// retry in the hundreds. A linear scale would put every interesting answer in
/// one bucket.
pub const BUCKET_BOUNDS_MS: [u64; 9] = [1, 2, 5, 10, 25, 50, 100, 250, 1_000];

/// How many attempts [`ProbeStats::answered_on`] counts separately before the
/// rest are lumped together.
///
/// Sized past the largest budget any path runs (five, under
/// [`ScanEffort::Thorough`](crate::config::ScanEffort)), so the
/// distribution is reported in full for every configuration that ships and a
/// hand-raised budget still has somewhere to land.
pub const ATTEMPTS_COUNTED: usize = 6;

/// Why a scanner's receive loop stopped.
///
/// This is the single most informative field in an audit: a run that ends in
/// [`AllResponded`](StopReason::AllResponded) was not cut short by anything, and
/// one that ends in [`DeadlineExpired`](StopReason::DeadlineExpired) with
/// replies still arriving near the end almost certainly was.
///
/// There is no "still running" variant. A scan loop yields its
/// reason as the value it breaks with, so every exit path has to name one and
/// the audit cannot report a reason the code never took.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StopReason {
    /// The caller aborted the scan through the scan handle.
    Aborted,
    /// Every target answered.
    AllResponded,
    /// Nothing is left outstanding: every target either answered or was asked
    /// as many times as the retry budget allows. Like
    /// [`AllResponded`](StopReason::AllResponded) this is a scan that finished
    /// rather than one that ran out of time, and waiting longer could not have
    /// changed what it found.
    AttemptsSpent,
    /// The adaptive deadline expired: either the hard budget ran out or the
    /// silence tolerance did.
    DeadlineExpired,
    /// The capture stream closed underneath the scanner.
    StreamClosed,
    /// The wall-clock budget the caller set on the whole scan ran out, and
    /// every strategy wound down where it stood. See
    /// [`ZondConfig::scan_timeout`](crate::config::ZondConfig::scan_timeout).
    ///
    /// Apart from [`Aborted`](StopReason::Aborted) because the two answer a
    /// scheduled run's first question differently: one says somebody was there
    /// and stopped it, the other says the scan was given less time than the
    /// network needed. Apart from
    /// [`DeadlineExpired`](StopReason::DeadlineExpired) because that one is the
    /// engine's own pacing running out against a single receive loop, which is
    /// a fact about one strategy rather than about the run.
    TimedOut,
}

impl StopReason {
    /// Every reason a receive loop stops this build knows, in declaration order.
    ///
    /// Here for the reason [`Protocol::ALL`](crate::model::port::Protocol::ALL)
    /// gives: the enum is `#[non_exhaustive]`, and the export conformance suite
    /// reads this list against the published schema's own and fails unless they hold
    /// the same names. A variant added without a place in the schema is a value this
    /// engine writes and no consumer's validator accepts.
    pub const ALL: [StopReason; 6] = [
        Self::Aborted,
        Self::AllResponded,
        Self::AttemptsSpent,
        Self::DeadlineExpired,
        Self::StreamClosed,
        Self::TimedOut,
    ];

    /// Whether the loop stopped because it had nothing left to do, rather than
    /// because something cut it short.
    ///
    /// A run that ends complete found everything it was ever going to find;
    /// waiting longer or sending more could not have changed it. One that does
    /// not is a result with a known upper bound on its own trustworthiness.
    pub fn is_complete(&self) -> bool {
        matches!(self, StopReason::AllResponded | StopReason::AttemptsSpent)
    }
}

impl fmt::Display for StopReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            StopReason::Aborted => "aborted by the caller",
            StopReason::AllResponded => "every target answered",
            StopReason::AttemptsSpent => "attempts spent",
            StopReason::DeadlineExpired => "deadline expired",
            StopReason::StreamClosed => "capture stream closed",
            StopReason::TimedOut => "scan budget spent",
        };
        f.write_str(text)
    }
}

/// What one raw scanner observed about its own run.
///
/// A host count on its own cannot say why a sweep came back short, and the three
/// possible answers call for opposite fixes. Probes or replies may have been
/// lost, which is what retransmission exists for; replies may have arrived
/// after the scan had already **stopped**, which makes the deadline wrong rather
/// than the network; or they may have arrived and gone **unrecognized**, which
/// no amount of extra time or extra packets would help.
///
/// These counters separate those. [`sends_attempted`](Self::sends_attempted)
/// against [`segments_seen`](Self::segments_seen) bounds the first,
/// [`stop_reason`](Self::stop_reason) against
/// [`last_reply`](Self::last_reply) bounds the second, and
/// [`segments_off_target`](Self::segments_off_target) with
/// [`replies_without_rtt`](Self::replies_without_rtt) bounds the third.
///
/// One bound is not measurable from inside a scanner at all: a reply the kernel
/// discards because the capture buffer was full never reaches any counter here,
/// so loss on the receive path and loss on the network read identically.
/// [`capture`](Self::capture) is carried for that reason - it is the only place
/// the difference is visible.
///
/// This is instrumentation about the scan, not a finding about the network.
/// Nothing here changes what a scan reports about a host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeStats {
    // Written by `ProbeAudit`, which lives in another module and so cannot use
    // private fields. Read-only to the outside world through the accessors
    // below: a consumer must never be able to edit a measurement.
    pub(crate) scanner: ScannerKind,
    pub(crate) targets: u128,
    pub(crate) stop_reason: StopReason,
    pub(crate) elapsed: Duration,
    pub(crate) sends_attempted: u64,
    pub(crate) sends_failed: u64,
    pub(crate) sends_witnessed: u64,
    pub(crate) segments_seen: u64,
    pub(crate) segments_off_target: u64,
    pub(crate) replies_without_rtt: u64,
    pub(crate) hosts_found: u64,
    pub(crate) answered_on: [u64; ATTEMPTS_COUNTED],
    pub(crate) answered_unattributed: u64,
    pub(crate) first_reply: Option<Duration>,
    pub(crate) last_reply: Option<Duration>,
    pub(crate) found_at: [u64; BUCKET_BOUNDS_MS.len() + 1],
    pub(crate) capture: Option<CaptureCounts>,
    pub(crate) window: Option<WindowSummary>,
}

impl ProbeStats {
    /// The strategy these counters belong to.
    pub fn scanner(&self) -> ScannerKind {
        self.scanner
    }

    /// How many targets this scanner owned: addresses for a discovery sweep,
    /// `(address, port)` probes for a port scan.
    pub fn targets(&self) -> u128 {
        self.targets
    }

    /// Why the receive loop stopped.
    pub fn stop_reason(&self) -> StopReason {
        self.stop_reason
    }

    /// How long the scanner ran.
    pub fn elapsed(&self) -> Duration {
        self.elapsed
    }

    /// Probes the scanner tried to put on the wire.
    pub fn sends_attempted(&self) -> u64 {
        self.sends_attempted
    }

    /// Of those, ones the sender refused. A non-zero count means the shortfall
    /// starts at home, before the network is implicated at all.
    pub fn sends_failed(&self) -> u64 {
        self.sends_failed
    }

    /// How many probes were watched leaving on the wire. Read against
    /// [`sends_attempted`](Self::sends_attempted), and only when non-zero: the
    /// gap is probes the OS took and dropped. Zero means no egress capture.
    pub fn sends_witnessed(&self) -> u64 {
        self.sends_witnessed
    }

    /// Segments the capture handed up, before any of the scanner's own checks.
    pub fn segments_seen(&self) -> u64 {
        self.segments_seen
    }

    /// What this run's congestion window did, for a scanner paced by one.
    ///
    /// The difference between "these ports are filtered" and "this scan was
    /// outrun and cannot tell". A run whose window bottomed out and still left
    /// most of its probes unanswered did not establish that anything is
    /// filtered; it established that it could not ask. Nothing else in these
    /// counters distinguishes the two, and a consumer that renders one as the
    /// other is publishing a claim about somebody's firewall that is really a
    /// claim about a saturated link.
    ///
    /// `None` for a scanner that paces itself some other way.
    pub fn window(&self) -> Option<WindowSummary> {
        self.window
    }

    /// Segments from an address outside this scan's target set. Expected to be
    /// small; a large count means the capture filter is admitting other traffic.
    pub fn segments_off_target(&self) -> u64 {
        self.segments_off_target
    }

    /// In-set replies that answered no outstanding probe, so they proved a host
    /// alive but yielded no round-trip sample. Duplicates land here, and so does
    /// a correlation bug.
    pub fn replies_without_rtt(&self) -> u64 {
        self.replies_without_rtt
    }

    /// Targets a reply resolved, counted once each.
    ///
    /// The unit is whatever the scanner's targets are, which is also the unit of
    /// [`targets`](Self::targets), so the two read together as answered against
    /// asked: a host for a discovery sweep, an `(address, port)` probe for a port
    /// scan. Named for the first of those because discovery was the first
    /// strategy to carry an audit.
    ///
    /// This is the number a run is judged on. Read against `targets` it is
    /// coverage; read against [`stop_reason`](Self::stop_reason) and
    /// [`last_reply`](Self::last_reply) it says whether the run was still finding
    /// things when it ended.
    pub fn hosts_found(&self) -> u64 {
        self.hosts_found
    }

    /// Found hosts by the attempt whose reply revealed them.
    ///
    /// Index `i` counts hosts answered on attempt `i + 1`; the last slot counts
    /// attempt [`ATTEMPTS_COUNTED`] *or later*, so a hand-raised retry budget
    /// still has somewhere to land.
    ///
    /// This is what says whether retransmission is earning its traffic. A host
    /// found on its first attempt needed only for the scan to still be
    /// listening; one found on its third needed the packet to be sent again.
    pub fn answered_on(&self) -> &[u64] {
        &self.answered_on
    }

    /// Found hosts whose reply named no attempt: it arrived after the probe had
    /// been written off, or carried nothing to match against.
    pub fn answered_unattributed(&self) -> u64 {
        self.answered_unattributed
    }

    /// How far into the run the first host was credited.
    pub fn first_reply(&self) -> Option<Duration> {
        self.first_reply
    }

    /// How far into the run the last host was credited. Close to
    /// [`elapsed`](Self::elapsed) on a run that stopped for
    /// [`DeadlineExpired`](StopReason::DeadlineExpired) means the scan was still
    /// finding hosts when it ran out of time.
    pub fn last_reply(&self) -> Option<Duration> {
        self.last_reply
    }

    /// Hosts by how far into the run they were credited, bucketed by
    /// [`BUCKET_BOUNDS_MS`]. Index `i` counts hosts found at or under
    /// `BUCKET_BOUNDS_MS[i]` milliseconds; the final slot counts everything
    /// later than the last bound.
    pub fn found_at(&self) -> &[u64] {
        &self.found_at
    }

    /// What the kernel capture reported, where there was one to ask. A scanner
    /// driven by a synthetic receive stream has no kernel buffer, and reports
    /// `None` rather than a clean-looking zero.
    pub fn capture(&self) -> Option<CaptureCounts> {
        self.capture
    }
}

// --------------------------------------------------------------------------
// What a scan did not cover
// --------------------------------------------------------------------------
//
// Two kinds, and the difference is whether anything went wrong. A strategy that
// could not run is a `ScannerFailure`; ground the engine declined before sending
// anything is a `Refusal`. Both narrow a result and only one of them is a fault,
// so a reader who cannot tell them apart learns to ignore both.

/// Ground a scan decided not to cover, and why.
///
/// Not a failure, and kept apart from one for the reason
/// [`unroutable`](ScanPhase::unroutable) is kept apart from both: nothing broke.
/// The engine worked out before sending anything that some part of what it was
/// asked for had no strategy behind it, and said so. A raw socket that would not
/// open is a [`ScannerFailure`]; an SCTP port named by a scan with no way to
/// probe one is this.
///
/// A reader has to be able to tell them apart because the remedies are
/// opposite. A failure means something is wrong with the machine or the
/// network and the same scan might work next time. A refusal means the scan as
/// written cannot answer the question, and running it again will refuse it
/// again.
///
/// The live form is [`RefusedStep`](crate::scanner::plan::RefusedStep), which a
/// plan carries before anything runs. This is the recorded form, on the same
/// terms [`ScannerFailure`] is the recorded form of
/// [`StrategyError`](crate::scanner::strategy::StrategyError).
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    scanner: ScannerKind,
    reason: String,
}

impl Refusal {
    /// Records that `scanner`'s work was declined, for `reason`.
    pub fn new(scanner: ScannerKind, reason: impl Into<String>) -> Self {
        Self {
            scanner,
            reason: reason.into(),
        }
    }

    /// The strategy that would have taken this work.
    pub fn scanner(&self) -> ScannerKind {
        self.scanner
    }

    /// What was not done, and what the caller could ask for instead.
    pub fn reason(&self) -> &str {
        &self.reason
    }
}

/// A scanning strategy that did not run to completion.
///
/// A scan continues with whatever strategies remain when one of them fails, so
/// a report that carries failures still carries results - just narrower ones
/// than the caller asked for. This is the record that lets a consumer tell a
/// genuinely empty network from a sweep whose raw scanner never started.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScannerFailure {
    scanner: ScannerKind,
    reason: String,
    at: SystemTime,
}

impl ScannerFailure {
    /// Records a failure as having happened now.
    pub fn new(scanner: ScannerKind, reason: impl Into<String>) -> Self {
        Self {
            scanner,
            reason: reason.into(),
            at: SystemTime::now(),
        }
    }

    /// The strategy that failed.
    pub fn scanner(&self) -> ScannerKind {
        self.scanner
    }

    /// A human-readable description of the failure.
    pub fn reason(&self) -> &str {
        &self.reason
    }

    /// Restores the time this failure was recorded.
    ///
    /// [`new`](Self::new) stamps the current time, which is what a running scan
    /// wants. A failure restored from a journal happened when it happened, not
    /// when the record of it was read.
    pub fn recorded_at(mut self, at: SystemTime) -> Self {
        self.at = at;
        self
    }

    /// When the failure was observed.
    pub fn at(&self) -> SystemTime {
        self.at
    }
}

impl fmt::Display for ScannerFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} scanner failed: {}", self.scanner, self.reason)
    }
}

// --------------------------------------------------------------------------
// Rebuilding what was recorded
// --------------------------------------------------------------------------
//
// Each `*Parts` struct is followed by the `from_parts` that consumes it, rather
// than sitting with the type it rebuilds. The pairs are the path a report takes
// coming back off a disk, and reading them together is the only way to see that
// path whole. It is also why `impl ScanPhase` appears below before
// `struct ScanPhase` does, and why `TargetScope` and `ProbeStats` each have a
// second impl block here rather than one block each.

/// Everything a [`TargetScope`] holds, for rebuilding one that was recorded.
///
/// A plain struct rather than positional arguments: two `u128` counts and two
/// range lists sit next to each other, and nothing would diagnose them being
/// swapped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScopeParts {
    /// The ranges that were walked, after exclusions.
    pub ranges: Vec<IpRange>,
    /// The links swept whole, by the interface each is on.
    pub links: Vec<Zone>,
    /// The links read from without being probed, which are never coverage.
    pub listened: Vec<Zone>,
    /// How many distinct addresses those ranges hold.
    pub addresses: u128,
    /// How many probes the scope implies, where ports were known.
    pub probes: Option<u128>,
    /// Which ports were walked, and whether uniformly.
    pub ports: PortScope,
    /// The transports the scope covered.
    pub protocols: Vec<Protocol>,
    /// The ranges the policy withheld.
    pub excluded: Vec<IpRange>,
    /// How many addresses that withheld.
    pub withheld: u128,
}

impl TargetScope {
    /// Rebuilds a scope from what was recorded of it.
    ///
    /// Unlike [`from_ip_set`](Self::from_ip_set), this applies no policy and
    /// narrows nothing: the exclusions were applied when the scope was first
    /// computed, and this restores the result rather than repeating the work.
    pub fn from_parts(parts: ScopeParts) -> Self {
        Self {
            listened: parts.listened,
            ranges: parts.ranges,
            links: parts.links,
            addresses: parts.addresses,
            probes: parts.probes,
            ports: parts.ports,
            protocols: parts.protocols,
            excluded: parts.excluded,
            withheld: parts.withheld,
        }
    }
}

/// Everything a [`ProbeStats`] holds, for rebuilding one that was recorded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeStatsParts {
    /// Which strategy this describes.
    pub scanner: ScannerKind,
    /// How many targets it was given.
    pub targets: u128,
    /// Why its receive loop stopped.
    pub stop_reason: StopReason,
    /// How long it ran.
    pub elapsed: Duration,
    /// How many sends it attempted.
    pub sends_attempted: u64,
    /// How many of those the host refused.
    pub sends_failed: u64,
    /// How many of those were seen leaving on the wire.
    pub sends_witnessed: u64,
    /// How many segments its capture handed it.
    pub segments_seen: u64,
    /// Where its congestion window ended up.
    pub window: Option<WindowSummary>,
    /// How many captured segments belonged to something else.
    pub segments_off_target: u64,
    /// How many replies could not be attributed to one attempt.
    pub replies_without_rtt: u64,
    /// How many hosts it found.
    pub hosts_found: u64,
    /// How many answers arrived on each attempt, one slot per counted attempt.
    pub answered_on: [u64; ATTEMPTS_COUNTED],
    /// How many answers named no attempt.
    pub answered_unattributed: u64,
    /// When the first reply arrived, from the start of the run.
    pub first_reply: Option<Duration>,
    /// When the last one did.
    pub last_reply: Option<Duration>,
    /// How many hosts were found in each time bucket, one slot per bound plus
    /// the tail.
    pub found_at: [u64; BUCKET_BOUNDS_MS.len() + 1],
    /// What the capture reported about its own losses.
    pub capture: Option<CaptureCounts>,
}

impl ProbeStats {
    /// Rebuilds probe statistics from what was recorded of them.
    pub fn from_parts(parts: ProbeStatsParts) -> Self {
        Self {
            scanner: parts.scanner,
            targets: parts.targets,
            stop_reason: parts.stop_reason,
            elapsed: parts.elapsed,
            sends_attempted: parts.sends_attempted,
            sends_failed: parts.sends_failed,
            sends_witnessed: parts.sends_witnessed,
            segments_seen: parts.segments_seen,
            window: parts.window,
            segments_off_target: parts.segments_off_target,
            replies_without_rtt: parts.replies_without_rtt,
            hosts_found: parts.hosts_found,
            answered_on: parts.answered_on,
            answered_unattributed: parts.answered_unattributed,
            first_reply: parts.first_reply,
            last_reply: parts.last_reply,
            found_at: parts.found_at,
            capture: parts.capture,
        }
    }
}

// --------------------------------------------------------------------------
// One phase of a scan
// --------------------------------------------------------------------------
//
// A phase is one engine call: a sweep, a port scan, a watch. A report holds a
// list of them rather than one set of metadata, because a caller who runs
// discovery and then a port scan is describing one job.

/// Which switch port the machine running a phase was plugged into.
///
/// Not a finding about any host in the report: a relation between *this*
/// machine and somebody else's equipment, learned from an announcement the
/// equipment sends unprompted (see [`crate::protocols::lldp`] and
/// [`crate::protocols::cdp`]). No probe obtains it, and nothing else in a scan
/// answers the question it answers: **where, physically, was this run from.**
///
/// # Why it hangs on the phase
///
/// For the reason [`PhaseOrigin`] does. A [`merge`](crate::merge) folds phases
/// measured from several vantage points into one report, and each of them ran
/// somewhere different. Recorded once for the whole report, two machines'
/// attachments would have to be arbitrated: a contest with no right answer,
/// since both are true. On the phase, each keeps the vantage it was actually
/// observed from and nothing has to be decided.
///
/// A phase may carry several: one per link it captured on, and another whenever
/// the answer changed while it ran, which for a listener running for days is a
/// cable somebody moved.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
    link: Zone,
    source: AttachmentSource,
    device_mac: Option<MacAddr>,
    device_name: Option<String>,
    port: Option<String>,
    native_vlan: Option<u16>,
    management: Option<IpAddr>,
    observed_at: SystemTime,
}

/// Which protocol an [`Attachment`] was read from.
///
/// Carried because the two do not cover the same ground: Cisco equipment runs
/// CDP by default and LLDP only when somebody enables it, so a network that
/// answers on one and not the other is saying something about what it is made
/// of. It is also the honest answer to "why does this say VLAN 40": the two
/// protocols carry that field in different places and not every device sends
/// either.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum AttachmentSource {
    /// IEEE 802.1AB, which anything may speak.
    Lldp,
    /// Cisco Discovery Protocol.
    Cdp,
}

impl AttachmentSource {
    /// Every announcement protocol this build knows, in declaration order.
    ///
    /// Here for the reason [`Protocol::ALL`](crate::model::port::Protocol::ALL)
    /// gives: the enum is `#[non_exhaustive]`, and the export conformance suite
    /// reads this list against the published schema's own and fails unless they hold
    /// the same names. A variant added without a place in the schema is a value this
    /// engine writes and no consumer's validator accepts.
    pub const ALL: [AttachmentSource; 2] = [Self::Lldp, Self::Cdp];
}

impl Attachment {
    /// An attachment on `link`, read from `source`, with nothing established
    /// about it yet.
    pub fn new(link: Zone, source: AttachmentSource, observed_at: SystemTime) -> Self {
        Self {
            link,
            source,
            device_mac: None,
            device_name: None,
            port: None,
            native_vlan: None,
            management: None,
            observed_at,
        }
    }

    /// Names the device by the hardware address it identified its chassis with.
    ///
    /// The field worth having above the name: it is what ties this attachment to
    /// a [`Host`] elsewhere in the same report, where a name is a string two
    /// devices may share.
    pub fn with_device_mac(mut self, mac: MacAddr) -> Self {
        self.device_mac = Some(mac);
        self
    }

    /// Names the device as it names itself.
    pub fn with_device_name(mut self, name: impl Into<String>) -> Self {
        self.device_name = Some(name.into());
        self
    }

    /// Names the port, as the device calls it in its own configuration.
    pub fn with_port(mut self, port: impl Into<String>) -> Self {
        self.port = Some(port.into());
        self
    }

    /// Records the VLAN untagged traffic on this port lands in.
    pub fn with_native_vlan(mut self, vlan: u16) -> Self {
        self.native_vlan = Some(vlan);
        self
    }

    /// Records an address the device is managed at.
    pub fn with_management_address(mut self, address: IpAddr) -> Self {
        self.management = Some(address);
        self
    }

    /// Which of this machine's interfaces the announcement arrived on.
    pub fn link(&self) -> &Zone {
        &self.link
    }

    /// Which protocol said so.
    pub fn source(&self) -> AttachmentSource {
        self.source
    }

    /// The hardware address the device identified its chassis with.
    pub fn device_mac(&self) -> Option<MacAddr> {
        self.device_mac
    }

    /// What the device calls itself, which on managed equipment is its
    /// hostname.
    pub fn device_name(&self) -> Option<&str> {
        self.device_name.as_deref()
    }

    /// What the device calls the port this machine is plugged into.
    pub fn port(&self) -> Option<&str> {
        self.port.as_deref()
    }

    /// The VLAN untagged traffic on this port lands in, where the device said.
    pub fn native_vlan(&self) -> Option<u16> {
        self.native_vlan
    }

    /// An address the device is managed at, where it advertised one.
    pub fn management_address(&self) -> Option<IpAddr> {
        self.management
    }

    /// When the announcement this was read from arrived.
    ///
    /// Worth recording separately from the phase's own span, because a phase
    /// that runs for days may see the answer change, which is somebody moving
    /// a cable, and is only legible if the two answers can be ordered.
    pub fn observed_at(&self) -> SystemTime {
        self.observed_at
    }
}

/// Which document a phase came from, for a report folded out of several.
///
/// A report merged from an archived nmap file, last night's journal and a scan
/// that just finished holds all of their phases, and each phase's scope, timing
/// and settings describe one of the three. This says which. Without it a merged
/// report states what it covered and cannot say on whose word.
///
/// `None` on a phase this process measured, which needs no attribution: it is
/// the report's own.
///
/// The label is the caller's. The engine opens no files and has no word for
/// one, so whoever read the document passes the name it used for it: a path, a
/// record id, a bucket key. [`merge`](crate::merge) is the only thing that
/// writes a `PhaseOrigin`, and it takes the version from the source report's own
/// attribution.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhaseOrigin {
    label: Option<Arc<str>>,
    engine_version: Arc<str>,
}

impl PhaseOrigin {
    /// An origin attributing a phase to `engine_version`, unnamed.
    pub fn new(engine_version: impl Into<Arc<str>>) -> Self {
        Self {
            label: None,
            engine_version: engine_version.into(),
        }
    }

    /// Names the document the phase was read from.
    pub fn with_label(mut self, label: impl Into<Arc<str>>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// What the caller called the document, if it said.
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// What produced the phase, as that scanner attributed itself. `nmap 7.94`
    /// for a report read out of nmap's XML, and no evidence this crate ran
    /// anything.
    pub fn engine_version(&self) -> &str {
        &self.engine_version
    }
}

/// Everything a [`ScanPhase`] holds, for rebuilding one that was recorded.
///
/// Mirrors the phase field for field, without a default: a
/// field added to [`ScanPhase`] is added here too, and every place that builds
/// one stops compiling until it says what the new field should be. That is what
/// keeps a journal from quietly losing what a phase gained.
#[derive(Debug, Clone)]
pub struct PhaseParts {
    /// Which entry point the phase recorded.
    pub kind: ScanKind,
    /// When it began.
    pub started_at: SystemTime,
    /// How long it ran.
    pub elapsed: Duration,
    /// Which sockets the phase had, or `None` where this engine did not measure
    /// it and cannot say.
    pub privilege: Option<Privilege>,
    /// What it was asked to cover, and what it was forbidden.
    pub targets: TargetScope,
    /// The settings it ran under.
    pub settings: ScanSettings,
    /// The strategies that could not do their job.
    pub failures: Vec<ScannerFailure>,
    /// Ground the phase declined before sending anything.
    pub refusals: Vec<Refusal>,
    /// Addresses this host had no route to.
    pub unroutable: Vec<IpAddr>,
    /// Addresses whose per-host budget ran out before the phase finished with
    /// them.
    pub timed_out: Vec<IpAddr>,
    /// Addresses a raw phase reached by TCP connect. See
    /// [`ScanPhase::reached_by_connect`].
    pub reached_by_connect: Vec<IpRange>,
    /// What each strategy recorded about its own run.
    pub probes: Vec<ProbeStats>,
    /// Which document the phase came from, for one folded in from elsewhere.
    pub origin: Option<PhaseOrigin>,
    /// Which switch ports the machine running the phase was plugged into.
    pub attachments: Vec<Attachment>,
}

impl ScanPhase {
    /// Rebuilds a phase from what was recorded of it.
    ///
    /// For restoring an earlier sitting of a resumed scan, so its report
    /// describes both rather than presenting the second as the whole job. A
    /// phase a scan is currently running comes from
    /// [`PhaseRecorder`](crate::scanner::recorder::PhaseRecorder) instead, which measures it.
    pub fn from_parts(parts: PhaseParts) -> Self {
        Self {
            kind: parts.kind,
            started_at: parts.started_at,
            elapsed: parts.elapsed,
            privilege: parts.privilege,
            targets: parts.targets,
            settings: parts.settings,
            failures: parts.failures,
            refusals: parts.refusals,
            unroutable: parts.unroutable,
            timed_out: parts.timed_out,
            reached_by_connect: parts.reached_by_connect,
            probes: parts.probes,
            origin: parts.origin,
            attachments: parts.attachments,
        }
    }

    /// Attributes this phase to the document it was read from.
    ///
    /// Used by [`merge`](crate::merge) as it folds a source in, which is the one
    /// place that knows both the document's name and what produced it.
    pub fn attribute(&mut self, origin: PhaseOrigin) {
        self.origin = Some(origin);
    }
}

/// One completed call into the engine.
#[derive(Debug, Clone)]
pub struct ScanPhase {
    kind: ScanKind,
    started_at: SystemTime,
    elapsed: Duration,
    privilege: Option<Privilege>,
    targets: TargetScope,
    settings: ScanSettings,
    failures: Vec<ScannerFailure>,
    /// Addresses this host had no route to, so nothing was sent to them.
    ///
    /// Distinct from a host that answered nothing, and the distinction is the
    /// whole reason it is recorded: an address that went unprobed because there
    /// is no path to it is not one that stayed silent, and the two call for
    /// different things from a reader. Telling somebody to scan an unreachable
    /// address on trust is advice that cannot work.
    unroutable: Vec<IpAddr>,
    /// Ground this phase declined before sending anything, and why.
    ///
    /// Beside `unroutable` rather than inside `failures`, on the reasoning
    /// [`Refusal`] gives: both of these are the scan saying what it did not
    /// cover, and neither is the scan saying something went wrong.
    refusals: Vec<Refusal>,
    /// Addresses the phase stopped working on because their own budget ran out.
    ///
    /// Beside `unroutable` for the reason that one is beside `failures`: this
    /// is the phase saying what it did not finish covering, and nothing here
    /// went wrong. The distinction it carries is the one a reader cannot make
    /// otherwise, since a host left early is reported with the ports it never
    /// reached taking the scan's silence verdict, and a page of filtered ports
    /// looks the same whether the scan asked and heard nothing or ran out of
    /// time to ask.
    timed_out: Vec<IpAddr>,
    /// Addresses this phase reached by TCP connect although it held the
    /// privilege its raw strategies need.
    ///
    /// Beside `unroutable` for the same reason `timed_out` is: this is the
    /// phase qualifying what it covered, not reporting that anything broke. See
    /// [`reached_by_connect`](Self::reached_by_connect).
    reached_by_connect: Vec<IpRange>,
    probes: Vec<ProbeStats>,
    /// Which document this phase was folded in from, for a merged report.
    origin: Option<PhaseOrigin>,
    /// Which switch ports the machine running this phase was plugged into.
    attachments: Vec<Attachment>,
}

impl ScanPhase {
    /// Which document this phase came from, for one folded into a merged report
    /// from elsewhere. `None` for a phase this process measured.
    pub fn origin(&self) -> Option<&PhaseOrigin> {
        self.origin.as_ref()
    }

    /// Where the machine running this phase was plugged in, as the equipment on
    /// the far end of the cable announced itself.
    ///
    /// Empty for a phase that heard no such announcement, which is every phase
    /// on an unmanaged network and every phase this engine ran before it
    /// learned to listen for one. Never a claim that the machine is attached to
    /// nothing.
    pub fn attachments(&self) -> &[Attachment] {
        &self.attachments
    }

    /// Which entry point this phase records.
    pub fn kind(&self) -> ScanKind {
        self.kind
    }

    /// When the phase began.
    pub fn started_at(&self) -> SystemTime {
        self.started_at
    }

    /// How long the phase ran, measured monotonically.
    pub fn elapsed(&self) -> Duration {
        self.elapsed
    }

    /// Whether the engine held the privileges its raw strategies need. An
    /// unprivileged phase reached its targets over plain TCP connect attempts,
    /// which see less and are more visible to the target.
    ///
    /// `None` for a phase this engine did not measure. The question is about
    /// *these* strategies and the sockets *they* need, and a scan another
    /// program ran answers it about its own. Recording `false` there said an
    /// nmap sweep performed over ARP as root had no raw sockets: a claim about
    /// this engine that no document supports, printed under findings that
    /// plainly contradicted it.
    pub fn privilege(&self) -> Option<Privilege> {
        self.privilege
    }

    /// What the phase was asked to cover.
    pub fn targets(&self) -> &TargetScope {
        &self.targets
    }

    /// The settings the phase ran under.
    pub fn settings(&self) -> &ScanSettings {
        &self.settings
    }

    /// Strategies that did not run to completion.
    pub fn unroutable(&self) -> &[IpAddr] {
        &self.unroutable
    }

    /// Addresses the phase left before it had finished with them, because the
    /// per-host budget in
    /// [`ScanSettings::host_timeout`](ScanSettings::host_timeout) ran out.
    ///
    /// Empty for a phase that set no budget, and for one where every host fitted
    /// inside it. A host named here still carries every port the phase managed
    /// to ask about; what it does not carry is the rest of them.
    pub fn timed_out(&self) -> &[IpAddr] {
        &self.timed_out
    }

    /// Addresses this phase reached by TCP connect although it held the
    /// privilege its raw strategies need, ascending.
    ///
    /// A raw probe goes where this process can put a packet of its own, and
    /// some addresses are beyond that whatever the privilege: loopback, and an
    /// address nothing routes to. A process that can inject frames and holds no
    /// raw socket, which is an unprivileged run on macOS with the BPF devices
    /// handed to its group, also cannot reach this host's own addresses,
    /// anything the kernel routes through a tunnel, or, for its port probes, an
    /// IPv6 neighbour. The phase probed those the way an unprivileged phase
    /// would, and what it found there is connect evidence under a phase whose
    /// [`privilege`](Self::privilege) reads as raw: a port that answered
    /// nothing may have been told nothing by the local stack, and no port was
    /// asked with the technique the settings name.
    ///
    /// Empty for most phases, and for every phase at
    /// [`Privilege::Connect`], which reached everything this way and says so
    /// once.
    pub fn reached_by_connect(&self) -> &[IpRange] {
        &self.reached_by_connect
    }

    /// The strategies in this phase that could not do their job.
    pub fn failures(&self) -> &[ScannerFailure] {
        &self.failures
    }

    /// Ground this phase declined to cover, and why.
    ///
    /// Read beside [`failures`](Self::failures) rather than instead of it:
    /// together they are everything the phase was asked for and did not answer,
    /// and apart they say whether anything went wrong. See [`Refusal`].
    pub fn refusals(&self) -> &[Refusal] {
        &self.refusals
    }

    /// What each instrumented scanner observed about its own run.
    ///
    /// Empty where no strategy in this phase carries instrumentation, which is
    /// not the same as a phase whose scanners saw nothing. Only the raw paths
    /// count packets; the TCP-connect fallback has no capture to audit.
    pub fn probe_stats(&self) -> &[ProbeStats] {
        &self.probes
    }
}

// --------------------------------------------------------------------------
// The report itself
// --------------------------------------------------------------------------
//
// What the phases and the hosts add up to. Every count here is computed from the
// hosts on demand rather than stored, so a summary cannot drift out of step with
// the data it describes.

/// Counts derived from a report's hosts.
///
/// Computed on demand by [`ScanReport::summary`] rather than stored, so it
/// cannot disagree with the hosts it describes.
///
/// Both headline counts are paired with a full distribution. `hosts_alive` and
/// `ports_open` are the numbers a person reads first, but collapsing the
/// remaining states into a single "not found" bucket would throw away the
/// distinction the scanner worked hardest to establish - a filtered port is
/// evidence of a firewall, a closed one is evidence of a live host, and neither
/// is silence.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScanSummary {
    /// Hosts recorded, whatever their status.
    pub hosts_total: usize,
    /// Hosts confirmed to be on the network, either responding or filtered.
    pub hosts_alive: usize,
    /// How many hosts fell into each status.
    pub hosts_by_status: BTreeMap<HostStatus, usize>,
    /// Port records across all hosts.
    pub ports_total: usize,
    /// Ports found accepting connections.
    pub ports_open: usize,
    /// How many ports fell into each state.
    pub ports_by_state: BTreeMap<PortState, usize>,
    /// Ports whose service was identified by fingerprinting.
    pub services_identified: usize,
    /// How many hosts were reachable at an IPv4 address, at an IPv6 one, and at
    /// both.
    ///
    /// Counted per host rather than per address, and the three do not sum to
    /// [`hosts_total`](Self::hosts_total): a dual-stack host appears in
    /// `ipv4`, in `ipv6` and in `dual_stack`. That is what makes the numbers
    /// answer the question they are asked, "how much of this network did I see
    /// over IPv6", where a partition into three would answer a different one.
    pub hosts_by_family: FamilyCounts,
}

/// Hosts counted by the address families they answered at.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FamilyCounts {
    /// Hosts with at least one IPv4 address.
    pub ipv4: usize,
    /// Hosts with at least one IPv6 address.
    pub ipv6: usize,
    /// Hosts with both, counted again here.
    pub dual_stack: usize,
}

/// Everything known about a completed scan.
///
/// Obtained from [`ScanTask::join`](crate::scanner::ScanTask::join) once a scan
/// finishes. See the [module documentation](self) for how it relates to the
/// live [`ScanSession`](crate::scanner::session::ScanSession).
#[derive(Debug, Clone)]
#[must_use = "a report is the record of the scan that just ran; dropping it discards it"]
pub struct ScanReport {
    /// Which build produced the findings, rather than which build is holding
    /// them. A report read back from a journal carries the version recorded
    /// with it, so it is borrowed for a scan this build ran and owned for one
    /// it is only reading.
    engine_version: Cow<'static, str>,
    phases: Vec<ScanPhase>,
    /// Keyed by [`ScopedIp`] rather than by the bare address.
    ///
    /// A host is keyed by the address it is reported under, and for an IPv6
    /// link-local that address is not an identity on its own: `fe80::1` names a
    /// different machine on every segment, and a scanner watching two of them
    /// finds two hosts under one number. Keyed by the bare `IpAddr` the second
    /// silently replaced the first, so a report could hold fewer hosts than were
    /// found and say nothing about it.
    ///
    /// [`ScopedIp::scoped`] drops the zone from every address that does not need
    /// one, so this is the ordinary bare address for every host but that case,
    /// and the map still orders by address: the zone only breaks ties between
    /// identically-numbered link-locals. Iteration order is plain address order
    /// for every report that does not contain one.
    ///
    /// This is the same distinction [`pairing`](crate::diff::pairing) draws when
    /// it decides which records are one host, so a fold that correctly separates
    /// two link-locals has somewhere to put them both.
    hosts: BTreeMap<ScopedIp, Host>,
}

impl ScanReport {
    /// Builds a single-phase report over the hosts a scan produced.
    ///
    /// Hosts are keyed by the address they are reported under, carrying the
    /// interface where that address needs one, so a host that gained addresses
    /// during the scan appears once rather than once per address and two
    /// link-locals on different segments stay two hosts.
    pub fn new(phase: ScanPhase, hosts: impl IntoIterator<Item = Host>) -> Self {
        Self {
            engine_version: Cow::Borrowed(ENGINE_VERSION),
            phases: vec![phase],
            hosts: index(hosts),
        }
    }

    /// A report over the phases of a job that ran in more than one sitting.
    ///
    /// The counterpart of [`new`](Self::new) for a resumed scan, whose earlier
    /// sittings are restored from a journal rather than measured. `phases` is
    /// kept in the order given, which is the order they ran.
    ///
    /// The report is attributed to this build, because this build is the one
    /// continuing the job. Use [`recorded`](Self::recorded) to rebuild a report
    /// nothing is continuing.
    pub fn from_phases(phases: Vec<ScanPhase>, hosts: impl IntoIterator<Item = Host>) -> Self {
        Self::attributed(Cow::Borrowed(ENGINE_VERSION), phases, hosts)
    }

    /// A report rebuilt from what an earlier scan wrote down, attributed to the
    /// engine that ran it.
    ///
    /// For reading a finished scan back, out of a journal, or out of a report
    /// this engine exported, where no new probing is happening. The version
    /// comes from the record rather than from this build, so a scan run by
    /// 0.11 still says 0.11 when 0.12 reads it. Every other constructor here
    /// describes a scan this build is part of, and names this build for that
    /// reason.
    pub fn recorded(
        engine_version: impl Into<String>,
        phases: Vec<ScanPhase>,
        hosts: impl IntoIterator<Item = Host>,
    ) -> Self {
        Self::attributed(Cow::Owned(engine_version.into()), phases, hosts)
    }

    fn attributed(
        engine_version: Cow<'static, str>,
        phases: Vec<ScanPhase>,
        hosts: impl IntoIterator<Item = Host>,
    ) -> Self {
        Self {
            engine_version,
            phases,
            hosts: index(hosts),
        }
    }

    /// The engine version that produced this report.
    pub fn engine_version(&self) -> &str {
        &self.engine_version
    }

    /// The phases that contributed to this report, in the order they ran.
    ///
    /// A report a scan produced always has at least one, since a phase
    /// completing is what produces it. One rebuilt with
    /// [`recorded`](Self::recorded) can have none, which is what a scan that
    /// stopped before it wrote a phase down reads back as.
    pub fn phases(&self) -> &[ScanPhase] {
        &self.phases
    }

    /// Whether this report was folded out of documents rather than measured by
    /// one run.
    ///
    /// True when any phase carries a [`PhaseOrigin`], which is what
    /// [`merge`](crate::merge) stamps on every phase it folds in and what
    /// nothing else writes.
    ///
    /// The distinction matters to anything that reads a report as an account of
    /// a single job, and to one thing in particular:
    /// [`elapsed`](Self::elapsed) is a sum over the phases, so for a merged
    /// report it is the working time of several scanners across arbitrary
    /// moments. That is a real quantity and it is not a length of time anything
    /// took, so presenting it as a duration would describe a scan that never
    /// ran. The span such a report draws on is
    /// [`finished_at`](Self::finished_at) less
    /// [`started_at`](Self::started_at) instead.
    pub fn is_merged(&self) -> bool {
        self.phases.iter().any(|phase| phase.origin().is_some())
    }

    /// Every host recorded, ordered by primary IP.
    pub fn hosts(&self) -> impl Iterator<Item = &Host> {
        self.hosts.values()
    }

    /// Every host recorded, to be changed in place.
    ///
    /// Crate-private, because a report is a record and letting a consumer edit
    /// one would make it a mutable document that still claims to describe a scan
    /// that happened. The one thing that legitimately runs over a finished
    /// report is a pass adding what the scan already knew but had not been asked
    /// to conclude, and [`cve::correlate_report`](crate::cve::correlate_report)
    /// is the whole of that today.
    pub(crate) fn hosts_mut(&mut self) -> impl Iterator<Item = &mut Host> {
        self.hosts.values_mut()
    }

    /// The number of hosts recorded.
    pub fn host_count(&self) -> usize {
        self.hosts.len()
    }

    /// Looks up a host by the address it is reported under.
    ///
    /// Where a report holds two link-locals at the same number on different
    /// segments this answers with the first, since a bare address cannot say
    /// which was meant. [`host_scoped`](Self::host_scoped) is the lookup that
    /// can.
    pub fn host(&self, ip: &IpAddr) -> Option<&Host> {
        self.hosts
            .range(ScopedIp::unscoped(*ip)..)
            .next()
            .filter(|(key, _)| key.addr() == *ip)
            .map(|(_, host)| host)
    }

    /// Looks up a host by the address it is reported under, together with the
    /// interface that address is valid on.
    ///
    /// The exact lookup, and the one to use for a link-local: `fe80::1%en0` and
    /// `fe80::1%en1` are two hosts and this is what tells them apart.
    pub fn host_scoped(&self, ip: &ScopedIp) -> Option<&Host> {
        self.hosts.get(ip)
    }

    /// Takes this report's phases, consuming it.
    ///
    /// For a caller assembling a new report out of several, which needs the
    /// phases themselves rather than a copy of each. The hosts are read through
    /// [`hosts`](Self::hosts) before this is called, since folding them is what
    /// the new report is for.
    pub fn into_phases(self) -> Vec<ScanPhase> {
        self.phases
    }

    /// When the earliest phase began.
    pub fn started_at(&self) -> SystemTime {
        self.phases
            .iter()
            .map(ScanPhase::started_at)
            .min()
            .unwrap_or_else(SystemTime::now)
    }

    /// When the latest phase stopped looking.
    ///
    /// The moment this report's findings are *as of*, which is what anything
    /// judging them against a clock wants: a certificate's remaining validity,
    /// how stale a record is, which of two reports is the later word. A phase's
    /// end is its own `started_at + elapsed`, since `elapsed` is measured
    /// monotonically over that one phase; the report-wide
    /// [`elapsed`](Self::elapsed) is a sum and cannot be added to a start.
    ///
    /// Distinct from [`started_at`](Self::started_at), which answers when the
    /// job began. The two differ by a scan's duration for an ordinary report and
    /// by however long the sources span for a merged one.
    /// A phase whose end cannot be represented is placed at its start. The
    /// addition is checked because a phase's `elapsed` is not always something
    /// this engine measured: a report read out of another scanner's document
    /// carries whatever that document claimed, and nmap's `elapsed` is a decimal
    /// number of seconds with no bound on it. A [`Duration`] holds five hundred
    /// billion years quite happily, a [`SystemTime`] does not, and `+` panics on
    /// the difference: in a method a consumer calls to ask when a report is as
    /// of.
    ///
    /// Placing such a phase at its start understates it, which is the safe
    /// direction: taken with the `max` below it still says the report had not
    /// finished before its latest phase began, and that much is true whatever
    /// the document claimed.
    pub fn finished_at(&self) -> SystemTime {
        self.phases
            .iter()
            .map(|phase| {
                phase
                    .started_at()
                    .checked_add(phase.elapsed())
                    .unwrap_or_else(|| phase.started_at())
            })
            .max()
            .unwrap_or_else(SystemTime::now)
    }

    /// The moment this report is judged to have happened.
    ///
    /// A report's findings are as of when it stopped looking, so a report with
    /// phases is placed by [`finished_at`](Self::finished_at) rather than by
    /// when its first phase began. For an ordinary scan the two differ by the
    /// scan's own duration, which no certificate threshold can notice. For a
    /// report merged out of several they differ by however long the sources
    /// span, and taking the earliest would judge tonight's certificates against
    /// last quarter.
    ///
    /// A report without phases, a foreign scanner's output, or a scan that
    /// ended before it wrote a phase down, is placed by the latest time any of
    /// its hosts was seen, which is the only other thing in the record that is a
    /// time the scan happened rather than the time it is being read.
    ///
    /// This is the clock [`merge`](crate::merge) folds sources by and
    /// [`diff`](crate::diff) places its two sides by, and it is public so that a
    /// caller can order documents the way those will before handing them over.
    pub fn observed_at(&self) -> SystemTime {
        if !self.phases.is_empty() {
            return self.finished_at();
        }

        self.hosts()
            .map(Host::last_seen)
            .max()
            .unwrap_or_else(SystemTime::now)
    }

    /// How long the engine spent scanning, summed over the phases.
    ///
    /// This is time the engine was working, not the span from the first phase
    /// starting to the last one ending. The two differ by whatever the caller
    /// did between phases - rendering a table, waiting for a confirmation - and
    /// attributing that to the scan would make the engine look slower than it
    /// is. For the wall-clock span, take the difference between
    /// [`started_at`](Self::started_at) and the last phase's end.
    pub fn elapsed(&self) -> Duration {
        self.phases.iter().map(ScanPhase::elapsed).sum()
    }

    /// Every strategy failure across all phases, in the order they were
    /// recorded.
    pub fn failures(&self) -> impl Iterator<Item = &ScannerFailure> {
        self.phases.iter().flat_map(ScanPhase::failures)
    }

    /// Every refusal, across all phases.
    pub fn refusals(&self) -> impl Iterator<Item = &Refusal> {
        self.phases.iter().flat_map(ScanPhase::refusals)
    }

    /// Every instrumented scanner's counters, across all phases.
    pub fn probe_stats(&self) -> impl Iterator<Item = &ProbeStats> {
        self.phases.iter().flat_map(ScanPhase::probe_stats)
    }

    /// Whether any strategy failed to run to completion. A `true` here means
    /// the results are narrower than the caller asked for.
    pub fn is_partial(&self) -> bool {
        self.phases.iter().any(|phase| !phase.failures.is_empty())
    }

    /// Counts derived from the recorded hosts.
    pub fn summary(&self) -> ScanSummary {
        let mut summary = ScanSummary::default();

        for host in self.hosts.values() {
            summary.hosts_total += 1;
            if host.is_alive() {
                summary.hosts_alive += 1;
            }
            *summary.hosts_by_status.entry(host.status()).or_default() += 1;

            let v4 = host.ips().iter().any(IpAddr::is_ipv4);
            let v6 = host.ips().iter().any(IpAddr::is_ipv6);
            summary.hosts_by_family.ipv4 += usize::from(v4);
            summary.hosts_by_family.ipv6 += usize::from(v6);
            summary.hosts_by_family.dual_stack += usize::from(v4 && v6);

            for port in host.ports() {
                summary.ports_total += 1;
                if port.state() == PortState::Open {
                    summary.ports_open += 1;
                }
                *summary.ports_by_state.entry(port.state()).or_default() += 1;
                if port.service().is_some() {
                    summary.services_identified += 1;
                }
            }
        }

        summary
    }

    /// The hosts this report found alive, as targets for a port scan.
    ///
    /// The join between the engine's two phases, which is the whole economy of
    /// having two: sweep a range cheaply, then spend the expensive phase only on
    /// what answered. Without this a caller has to walk the hosts, filter them,
    /// and assemble four types by hand to say something the report already
    /// knows.
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use zond_engine::{PortSet, ZondConfig, discover, scan};
    /// use zond_engine::detect::Detections;
    /// use zond_engine::model::parse::ip::to_set;
    ///
    /// let cfg = ZondConfig::default();
    /// let (_, sweep) = discover(to_set(&["192.0.2.0/24"], None, None)?, &cfg).await?;
    /// let mut report = sweep.join().await?;
    ///
    /// // The sweep already established these hosts answer, so the scan is told
    /// // to take them on trust rather than probe for liveness a second time.
    /// let mut scanning = cfg.clone();
    /// scanning.assume_up = true;
    /// let targets = report.alive_targets(PortSet::try_from("22,80,443")?);
    /// let (_, ports) = scan(targets, &scanning, Detections::embedded()).await?;
    /// report.merge(ports.join().await?);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Only hosts that answered. [`Host::is_alive`] is the filter, so a host
    /// recorded as [`Down`](HostStatus::Down), a router said it was
    /// unreachable, or [`Unknown`](HostStatus::Unknown) is left out. Probing an
    /// address nothing answered for costs a full port scan's worth of silence to
    /// learn what the sweep already established.
    ///
    /// One address per host, the one it is reported under. A dual-stack host
    /// is one machine and is scanned once, at the address
    /// [`Host::primary_ip`] picked; scanning both would report it twice, keyed
    /// separately, which is the outcome that ranking exists to prevent. A caller
    /// who does want every address can build the set from [`Host::ips`] instead.
    ///
    /// A link-local address carries the interface it was found on, because it is
    /// meaningless without one: `fe80::1` names a different machine on every
    /// segment, and the sweep that found it is the only thing that knows which.
    pub fn alive_targets(&self, ports: PortSet) -> TargetMap {
        let mut ips = IpSet::new();

        for host in self.hosts.values().filter(|host| host.is_alive()) {
            match host.primary_ip() {
                IpAddr::V4(v4) => {
                    if let Ok(range) = Ipv4Range::new(v4, v4) {
                        ips.push_v4_range(range);
                    }
                }
                IpAddr::V6(v6) => {
                    // The zone is kept for exactly the addresses that cannot be
                    // reached without one, and dropped for the rest for the
                    // reason `ScopedIp` drops it: the same global address
                    // through two interfaces is one address, not two.
                    let zone = v6
                        .is_unicast_link_local()
                        .then(|| host.zone().and_then(Zone::index))
                        .flatten();
                    if let Ok(range) = Ipv6Range::scoped(v6, v6, zone) {
                        ips.push_v6_range(range);
                    }
                }
            }
        }

        ips.canonicalize();

        let mut targets = TargetMap::new();
        // An empty unit is not the same as no unit: a `TargetMap` holding a set
        // with no addresses would have a port dimension and nothing to apply it
        // to, and `scan` would report a phase that covered nothing rather than
        // one there was nothing to do.
        if !ips.is_empty() {
            targets.add_unit(TargetSet::new(ips, ports));
        }
        targets
    }

    /// Folds a later phase of the same job into this report.
    ///
    /// Hosts present in both are combined with [`Host::merge`], so a host
    /// discovered in the first phase keeps its MAC and telemetry when the second
    /// adds its ports. Phases and their failures are appended in call order.
    ///
    /// The engine version is left as this report's. Two reports from different
    /// engine builds are not part of one job, and silently averaging their
    /// provenance would be worse than keeping the first.
    pub fn merge(&mut self, other: ScanReport) {
        self.phases.extend(other.phases);

        for (key, host) in other.hosts {
            match self.hosts.get_mut(&key) {
                Some(existing) => existing.merge(host),
                None => {
                    self.hosts.insert(key, host);
                }
            }
        }
    }
}

/// Keys hosts by the address each is reported under.
///
/// Folds rather than replaces where two records key the same, which is what a
/// caller means by handing over two records of one host: the live store already
/// folds them, and a caller assembling a report by hand should not lose a
/// finding for having done it in two pieces. Replacing was the previous
/// behaviour and it discarded whichever record arrived first, silently.
fn index(hosts: impl IntoIterator<Item = Host>) -> BTreeMap<ScopedIp, Host> {
    let mut indexed: BTreeMap<ScopedIp, Host> = BTreeMap::new();

    for host in hosts {
        match indexed.get_mut(&host.scoped_ip()) {
            Some(existing) => existing.merge(host),
            None => {
                indexed.insert(host.scoped_ip(), host);
            }
        }
    }

    indexed
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

// --------------------------------------------------------------------------
// Naming the strategies
// --------------------------------------------------------------------------
//
// Which strategy a failure, a refusal or a set of counters belongs to. Last
// because everything above refers to it and nothing it refers to is here.

/// Which scanning strategy a [`ScanEvent::ScannerFailed`](crate::scanner::session::ScanEvent::ScannerFailed) refers to.
///
/// Marked `#[non_exhaustive]`: strategies are added as the engine learns to
/// probe in new ways, and a consumer matching on this enum should pay for that
/// with a recompile rather than a major version.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScannerKind {
    /// Layer-2 discovery (ARP/NDP) on a local segment.
    Local,
    /// Reading a link's own traffic, having sent nothing.
    ///
    /// The one strategy here that puts no packet on the wire, which changes
    /// what its counters mean. `sends_attempted` is zero for it and always
    /// will be; what it saw is bounded by what the network happened to carry
    /// rather than by anything this engine chose, so a quiet run says the
    /// segment was quiet and never that a host was absent.
    Passive,
    /// Raw TCP SYN discovery for gateway-routed targets.
    Routed,
    /// The same sweep asking over SCTP: one INIT per address, for a scan whose
    /// ports name SCTP.
    ///
    /// Named apart from [`Routed`](Self::Routed) because it is a different
    /// question put to the network and it fails for its own reasons. A host
    /// behind a filter that passes SCTP and drops TCP answers this and nothing
    /// else, and a report attributing that finding to the SYN sweep would
    /// describe a packet which drew silence.
    RoutedSctp,
    /// Raw TCP SYN port scanning (the port-scan phase, distinct from [`Routed`]
    /// host discovery).
    ///
    /// [`Routed`]: ScannerKind::Routed
    SynPort,
    /// Raw TCP port scanning with a probe that is not a SYN - a FIN, a flagless
    /// segment, a bare ACK.
    ///
    /// The same scanner as [`SynPort`], asking a different question. They are
    /// named apart because a report saying `syn_port` should mean a half-open
    /// connection attempt was made, and for these it was not; which technique
    /// ran is in the phase's settings.
    ///
    /// [`SynPort`]: ScannerKind::SynPort
    TcpPort,
    /// Unprivileged TCP connect fallback, for both host discovery and port
    /// scanning.
    Connect,
    /// Unprivileged UDP fallback.
    ///
    /// Named apart from [`Connect`] because a report has to be able to say which
    /// half of an unprivileged scan failed. The two send different datagrams,
    /// read different answers, and fail for different reasons: a host that
    /// refuses one may be perfectly happy with the other, and one name for both
    /// makes that indistinguishable.
    ///
    /// [`Connect`]: ScannerKind::Connect
    ConnectUdp,
    /// Privileged raw UDP port scanning.
    UdpPort,
    /// Privileged raw SCTP port scanning: an INIT chunk per port, classified by
    /// the chunk that answers it.
    ///
    /// Named apart from the others because there is no unprivileged form of it
    /// to fall back to and no service pass behind it, so a report saying this
    /// step failed is saying the SCTP ports went unprobed entirely.
    SctpPort,
    /// The active operating-system echo probe, sent at the hosts the passive
    /// sources could not name.
    ///
    /// Named apart from the port scanners because it answers a different
    /// question about a different dimension: not which ports a host has, but
    /// which stack answered the ping. A report attributing an echo probe to any
    /// other strategy would describe traffic nobody sent.
    OsEcho,
    /// The active operating-system series probe: one host asked the same
    /// question several times, so the policies behind its counters become
    /// visible.
    ///
    /// Named apart from [`SynPort`] though it sends the same segment, because
    /// what it is doing with the answers is a different activity and a report
    /// that filed it as a port scan would describe traffic nobody asked for:
    /// these probes revisit ports whose state is already settled, and none of
    /// their replies changes one.
    ///
    /// [`SynPort`]: ScannerKind::SynPort
    OsSeries,
    /// The active operating-system management probe: one SNMP `GetRequest` at a
    /// host whose kernel is not otherwise known.
    ///
    /// Named apart from the port scanners because it establishes no port state.
    /// It asks one question of one service and files the answer against the
    /// *host*; whether anything is listening on 161 is the port scan's to
    /// report, and this phase does not.
    OsSnmp,
    /// The idle (zombie) TCP port scan: port states read off a third party's
    /// IP-ID counter rather than from any reply the target sent this scanner.
    ///
    /// Named apart from [`SynPort`](Self::SynPort) though the forged probe is a
    /// SYN, because what it produces and what can go wrong are its own: a
    /// verdict is `Open` or `ClosedFiltered` and nothing finer, and a run is
    /// refused for want of a suitable zombie or an Ethernet path where a raw SYN
    /// scan would simply have proceeded.
    Idle,
    /// Composite scanner that delegates to protocol-specific scanners.
    Composite,
    /// The service-identification pass, which opens a connection to each open
    /// port a raw scan classified without ever holding one.
    ///
    /// Named apart from [`Connect`] though it makes the same kind of
    /// connection, because a report has to be able to say which pass lost work.
    /// A connect scan that failed means port *states* are missing; this failing
    /// means the states stand and the services behind them were not identified,
    /// which is a narrower and differently actionable result. Filed as
    /// `connect`, a scan that ran no connect strategy at all reported one as
    /// having broken.
    ///
    /// [`Connect`]: ScannerKind::Connect
    Service,
    /// The detection pass, which runs the authored corpus over the services the
    /// scan identified.
    ///
    /// Named apart from [`Service`] because it depends on it and can fail
    /// alone: with the services named and this pass broken, the report carries
    /// every port and none of the findings a detection would have drawn.
    ///
    /// [`Service`]: ScannerKind::Service
    Detection,
    /// The journal a scan was writing itself into.
    ///
    /// Not a strategy, and here because it is the one channel a library
    /// consumer reads without opting in. A checkpoint that could not be written
    /// costs nothing a scan found and everything a *resume* would have skipped,
    /// so it is a fact about the disk rather than about the network, and
    /// filing it as a scanning strategy would tell a caller that ports had gone
    /// unprobed when none had.
    Journal,
}

/// What a [`CongestionWindow`](crate::scanner::pacing::congestion::CongestionWindow) did over one run.
///
/// Instrumentation rather than telemetry: it says whether pacing engaged and how
/// hard, which is the difference between "this host is firewalled" and "this
/// host was asked too fast", and that difference is otherwise invisible in
/// everything else a scan reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WindowSummary {
    /// The window at the end of the run.
    pub capacity: usize,
    /// The largest it reached.
    pub peak: usize,
    /// How many times it was cut.
    pub reductions: u32,
    /// Whether it was allowed to move at all.
    pub adaptive: bool,
    /// Whether it finished cut back as far as it is permitted to go.
    ///
    /// The controller having run out of room, which is the one state worth
    /// telling an operator about: it means the scan was still being outrun when
    /// it stopped, so what it recorded as silence may be loss rather than
    /// filtering, and the remedy is a narrower scan rather than a different
    /// setting.
    pub at_floor: bool,
}

impl ScannerKind {
    /// Every strategy this build knows, in declaration order.
    ///
    /// Here for the reason [`Protocol::ALL`](crate::model::port::Protocol::ALL)
    /// gives: the enum is `#[non_exhaustive]`, and the export conformance suite
    /// reads this list against the published schema's own and fails unless they hold
    /// the same names. A variant added without a place in the schema is a value this
    /// engine writes and no consumer's validator accepts.
    pub const ALL: [ScannerKind; 18] = [
        Self::Local,
        Self::Passive,
        Self::Routed,
        Self::RoutedSctp,
        Self::SynPort,
        Self::TcpPort,
        Self::Connect,
        Self::ConnectUdp,
        Self::UdpPort,
        Self::SctpPort,
        Self::OsEcho,
        Self::OsSeries,
        Self::OsSnmp,
        Self::Idle,
        Self::Composite,
        Self::Service,
        Self::Detection,
        Self::Journal,
    ];

    /// What a raw TCP scan carrying `technique` reports itself as.
    ///
    /// One function because the answer has to be the same everywhere it is
    /// asked, and it is asked twice: once by the plan, to attribute a step that
    /// could not open its socket, and once by the running scanner, to attribute
    /// anything that went wrong afterwards. Two spellings meant one strategy
    /// filed its failures under two names depending on when it failed, and the
    /// planning half called every technique [`SynPort`](Self::SynPort) whether
    /// or not a SYN was involved.
    pub const fn for_raw_tcp(technique: TcpScanTechnique) -> Self {
        match technique {
            TcpScanTechnique::Syn => Self::SynPort,
            _ => Self::TcpPort,
        }
    }
}

impl fmt::Display for WindowSummary {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.adaptive {
            return write!(f, "fixed {}", self.capacity);
        }
        write!(
            f,
            "{} (peak {}, cut {}x){}",
            self.capacity,
            self.peak,
            self.reductions,
            if self.at_floor { " at floor" } else { "" }
        )
    }
}

#[cfg(test)]
mod tests {

    /// A phase given one port set for every address can say a particular
    /// endpoint was probed. One given different sets cannot, and the union it
    /// publishes says so.
    #[test]
    fn a_scope_says_whether_its_addresses_agree_about_ports() {
        use crate::model::parse::ip::to_set;
        use crate::model::port::PortSet;
        use crate::model::target::TargetSet;

        let unit = |cidr: &str, ports: &str| {
            TargetSet::new(
                to_set(&[cidr], None, None).expect("a range"),
                PortSet::try_from(ports).expect("a port specification"),
            )
        };

        let mut same = TargetMap::new();
        same.add_unit(unit("192.0.2.0/30", "80,443"));
        same.add_unit(unit("198.51.100.0/30", "80,443"));
        let scope = TargetScope::from_target_map(&mut same, &Exclusions::none());
        assert_eq!(
            scope.ports().covers(443, Protocol::Tcp),
            Some(true),
            "every address was walked for it"
        );
        assert_eq!(scope.ports().covers(8080, Protocol::Tcp), Some(false));

        let mut differing = TargetMap::new();
        differing.add_unit(unit("192.0.2.0/30", "80,443"));
        differing.add_unit(unit("198.51.100.0/30", "8080"));
        let scope = TargetScope::from_target_map(&mut differing, &Exclusions::none());
        assert_eq!(
            scope.ports().covers(8080, Protocol::Tcp),
            None,
            "walked for one unit and not the other, so the scope cannot say"
        );
        assert_eq!(
            scope.ports().covers(9999, Protocol::Tcp),
            Some(false),
            "absent from the union means walked for no address at all"
        );
    }

    /// A sweep walks addresses, and that is a fact about its endpoints rather
    /// than an absence of one.
    #[test]
    fn a_discovery_sweep_walked_no_ports_and_says_so() {
        let mut ips = crate::model::parse::ip::to_set(&["192.0.2.0/30"], None, None).unwrap();
        let scope = TargetScope::from_ip_set(&mut ips, &Exclusions::none());

        assert_eq!(*scope.ports(), PortScope::NoPorts);
        assert_eq!(scope.ports().covers(80, Protocol::Tcp), Some(false));
    }
    use super::*;
    use crate::model::ip::range::Ipv4Range;
    use crate::model::port::{Port, PortSet, Service};
    use crate::model::target::TargetSet;
    use std::net::Ipv4Addr;
    use std::str::FromStr;

    fn ip(last: u8) -> IpAddr {
        IpAddr::V4(Ipv4Addr::new(203, 0, 113, last))
    }

    fn phase(kind: ScanKind) -> ScanPhase {
        ScanPhase {
            attachments: Vec::new(),
            kind,
            started_at: SystemTime::UNIX_EPOCH,
            elapsed: Duration::from_millis(500),
            privilege: Some(Privilege::Raw),
            targets: TargetScope::from_ip_set(&mut IpSet::new(), &Exclusions::none()),
            settings: ScanSettings::from(&ZondConfig::default()),
            failures: Vec::new(),
            refusals: Vec::new(),
            unroutable: Vec::new(),
            timed_out: Vec::new(),
            reached_by_connect: Vec::new(),
            probes: Vec::new(),
            origin: None,
        }
    }

    /// A duration no clock can add to is a phase to place at its start, not a
    /// process to end.
    ///
    /// `finished_at` cannot add a phase's `elapsed` to its start with `+`,
    /// which panics on overflow, because a phase's `elapsed` is not always
    /// something this engine measured: a report read out of nmap's XML carries
    /// whatever `<finished elapsed="...">` claimed, and that is a decimal number
    /// of seconds with no bound on it. A `Duration` holds five hundred billion
    /// years and a `SystemTime` does not.
    ///
    /// The panic would take the process down from inside `ScanDiff::between`,
    /// which is what a nightly comparison calls on every report it reads, and
    /// `elapsed="1222222222…"` is enough to cause it.
    #[test]
    fn a_phase_claiming_more_time_than_a_clock_holds_does_not_end_the_process() {
        let mut absurd = phase(ScanKind::PortScan);
        absurd.started_at = SystemTime::UNIX_EPOCH;
        absurd.elapsed = Duration::from_secs(u64::MAX);

        let ordinary = phase(ScanKind::Discovery);
        let ends_at = ordinary.started_at + ordinary.elapsed;

        let report = ScanReport::recorded("zond", vec![absurd, ordinary], Vec::new());

        assert_eq!(
            report.finished_at(),
            ends_at,
            "the phase that could be placed is the one that should place the report"
        );

        // And the comparison that reads it, which is where the panic surfaced.
        assert!(crate::diff::ScanDiff::between(&report, &report).is_empty());
    }

    fn ip_set(spec: &str) -> IpSet {
        let mut set = IpSet::new();
        set.insert_range(IpRange::from_str(spec).expect("valid range"));
        set
    }

    #[test]
    fn scope_merges_overlapping_ranges_before_counting() {
        let mut ips = ip_set("203.0.113.0/24");
        ips.insert_range(IpRange::from_str("203.0.113.128/25").expect("valid range"));

        let scope = TargetScope::from_ip_set(&mut ips, &Exclusions::none());

        // The second range is wholly inside the first, so the scope covers one
        // /24 rather than the 384 addresses the two arguments add up to.
        assert_eq!(scope.ranges().len(), 1);
        assert_eq!(scope.addresses(), 256);
        assert_eq!(scope.probes(), None);
        assert!(scope.protocols().is_empty());
    }

    #[test]
    fn port_scan_scope_counts_probes_not_addresses() {
        let ports = PortSet::from_iter([
            (80, Protocol::Tcp),
            (443, Protocol::Tcp),
            (53, Protocol::Udp),
        ]);

        let mut targets = TargetMap::new();
        targets.add_unit(TargetSet::new(ip_set("192.0.2.1-192.0.2.4"), ports));

        let scope = TargetScope::from_target_map(&mut targets, &Exclusions::none());

        assert_eq!(scope.addresses(), 4);
        assert_eq!(scope.probes(), Some(12));
        assert_eq!(scope.protocols(), &[Protocol::Tcp, Protocol::Udp]);
    }

    /// A phase's settings are what a reader needs to interpret its findings, so
    /// a run that put something different on the wire has to record something
    /// different.
    ///
    /// The other half of this, that a run differing only in how it was
    /// *displayed* records the same settings, holds by construction:
    /// presentation is the front end's and no field of [`ZondConfig`] is about
    /// it, so there is nothing that could leak into a report and nothing for a
    /// test to catch.
    #[test]
    fn settings_record_what_changed_the_scan() {
        let scanning = ZondConfig {
            no_dns: true,
            ..Default::default()
        };

        assert_ne!(
            ScanSettings::from(&scanning),
            ScanSettings::from(&ZondConfig::default())
        );
    }

    #[test]
    fn summary_counts_states_and_services() {
        let mut up = Host::new(ip(1));
        up.set_status(HostStatus::Up);
        up.add_port(
            Port::new(22, Protocol::Tcp, PortState::Open).with_service(Service::new("ssh", 90)),
        );
        up.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
        up.add_port(Port::new(81, Protocol::Tcp, PortState::Filtered));

        let mut filtered = Host::new(ip(2));
        filtered.set_status(HostStatus::Filtered);

        let mut down = Host::new(ip(3));
        down.set_status(HostStatus::Down);

        let report = ScanReport::new(phase(ScanKind::PortScan), [up, filtered, down]);
        let summary = report.summary();

        assert_eq!(summary.hosts_total, 3);
        assert_eq!(summary.hosts_alive, 2);
        assert_eq!(summary.hosts_by_status[&HostStatus::Up], 1);
        assert_eq!(summary.hosts_by_status[&HostStatus::Down], 1);
        assert_eq!(summary.ports_total, 3);
        assert_eq!(summary.ports_open, 2);
        assert_eq!(summary.ports_by_state[&PortState::Filtered], 1);
        assert_eq!(summary.services_identified, 1);
    }

    /// The whole economy of running discovery first: a host that never answered
    /// costs a full port scan's worth of silence to learn what the sweep already
    /// established.
    #[test]
    fn only_hosts_that_answered_become_port_scan_targets() {
        let mut up = Host::new(ip(1));
        up.set_status(HostStatus::Up);
        let mut filtered = Host::new(ip(2));
        filtered.set_status(HostStatus::Filtered);
        let mut down = Host::new(ip(3));
        down.set_status(HostStatus::Down);
        let unknown = Host::new(ip(4));

        let report = ScanReport::new(phase(ScanKind::Discovery), [up, filtered, down, unknown]);

        let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));

        // Up and Filtered are both alive - something is there, whether or not it
        // is answering for itself. Down and Unknown are not.
        assert_eq!(targets.gross_ips().expect("countable"), 2);
        assert_eq!(targets.gross_targets().expect("countable"), 2);
    }

    /// A dual-stack host is one machine. Scanning it at every address it holds
    /// would report it once per address, keyed separately - which is exactly
    /// what `consider_primary_ip`'s ranking exists to prevent.
    #[test]
    fn a_dual_stack_host_is_scanned_once() {
        let mut dual = Host::new(ip(1));
        dual.set_status(HostStatus::Up);
        dual.add_ip(IpAddr::from_str("2001:db8::1").unwrap());

        let report = ScanReport::new(phase(ScanKind::Discovery), [dual]);
        let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));

        assert_eq!(targets.gross_ips().expect("countable"), 1);
    }

    /// `fe80::1` names a different machine on every segment, and a socket cannot
    /// be opened to one without the interface's scope id. The sweep that found
    /// it is the only thing that knows which, so the target has to carry it or
    /// the port scan cannot reach the host discovery just found.
    #[test]
    fn a_link_local_target_keeps_the_interface_it_was_found_on() {
        let lla: IpAddr = "fe80::10".parse().unwrap();
        let mut host = Host::new(lla);
        host.set_status(HostStatus::Up);
        host.set_zone(Zone::new(7, "en0"));

        let report = ScanReport::new(phase(ScanKind::Discovery), [host]);
        let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));

        let zones: Vec<Option<u32>> = targets
            .units
            .iter()
            .flat_map(|unit| unit.ips().v6().iter().map(|range| range.zone()))
            .collect();
        assert_eq!(zones, vec![Some(7)]);
    }

    /// A sweep that found nothing yields no work, not an empty unit carrying a
    /// port dimension with nothing to apply it to.
    #[test]
    fn a_sweep_that_found_nothing_yields_no_targets() {
        let report = ScanReport::new(phase(ScanKind::Discovery), [Host::new(ip(1))]);
        let targets = report.alive_targets(PortSet::from_iter([(80, Protocol::Tcp)]));

        assert!(targets.is_empty());
        assert!(targets.units.is_empty());
    }

    #[test]
    fn hosts_are_ordered_by_ip_regardless_of_discovery_order() {
        let scrambled = [Host::new(ip(30)), Host::new(ip(2)), Host::new(ip(17))];
        let report = ScanReport::new(phase(ScanKind::Discovery), scrambled);

        let order: Vec<IpAddr> = report.hosts().map(Host::primary_ip).collect();
        assert_eq!(order, vec![ip(2), ip(17), ip(30)]);
    }

    #[test]
    fn merge_combines_hosts_and_keeps_phase_order() {
        let mut discovered = Host::new(ip(1));
        discovered.set_status(HostStatus::Up);
        discovered.add_rtt(Duration::from_millis(3));
        let mut first = ScanReport::new(phase(ScanKind::Discovery), [discovered]);

        let mut scanned = Host::new(ip(1));
        scanned.add_port(Port::new(443, Protocol::Tcp, PortState::Open));
        let second = ScanReport::new(phase(ScanKind::PortScan), [scanned, Host::new(ip(9))]);

        first.merge(second);

        // The port scan's record of .1 carried no status and no telemetry; the
        // merge must not let that erase what discovery established.
        let host = first.host(&ip(1)).expect("host survives the merge");
        assert_eq!(host.status(), HostStatus::Up);
        assert_eq!(host.port_count(), 1);
        assert!(host.min_rtt().is_some());

        assert_eq!(first.host_count(), 2);
        assert_eq!(
            first
                .phases()
                .iter()
                .map(ScanPhase::kind)
                .collect::<Vec<_>>(),
            vec![ScanKind::Discovery, ScanKind::PortScan]
        );
        assert_eq!(first.elapsed(), Duration::from_secs(1));
    }

    #[test]
    fn failures_are_visible_across_phases() {
        let mut failed = phase(ScanKind::Discovery);
        failed.failures.push(ScannerFailure::new(
            ScannerKind::Routed,
            "raw socket unavailable",
        ));

        let clean = ScanReport::new(phase(ScanKind::PortScan), []);
        let mut report = ScanReport::new(failed, []);
        report.merge(clean);

        assert!(report.is_partial());
        assert_eq!(report.failures().count(), 1);
    }

    /// A phase whose scanners carry no instrumentation reports no counters,
    /// which must not be confused with a scanner that measured zero.
    #[test]
    fn an_uninstrumented_phase_reports_no_probe_stats() {
        let report = ScanReport::new(phase(ScanKind::PortScan), []);

        assert!(report.phases()[0].probe_stats().is_empty());
        assert_eq!(report.probe_stats().count(), 0);
    }

    #[test]
    fn a_stop_reason_knows_whether_the_run_finished() {
        assert!(StopReason::AllResponded.is_complete());
        assert!(StopReason::AttemptsSpent.is_complete());
        assert!(!StopReason::DeadlineExpired.is_complete());
        assert!(!StopReason::Aborted.is_complete());
        assert!(!StopReason::StreamClosed.is_complete());
        assert!(!StopReason::TimedOut.is_complete());
    }

    #[test]
    fn a_clean_report_is_not_partial() {
        let report = ScanReport::new(phase(ScanKind::Discovery), []);

        assert!(!report.is_partial());
        assert_eq!(report.failures().count(), 0);
        assert_eq!(report.engine_version(), ENGINE_VERSION);
    }

    #[test]
    fn scope_ranges_cover_both_families() {
        let mut ips = ip_set("192.0.2.0/30");
        ips.insert_range(IpRange::from_str("fe80::/126").expect("valid range"));

        let scope = TargetScope::from_ip_set(&mut ips, &Exclusions::none());

        assert_eq!(scope.addresses(), 8);
        assert!(matches!(scope.ranges()[0], IpRange::V4(_)));
        assert!(matches!(scope.ranges()[1], IpRange::V6(_)));
    }

    #[test]
    fn ipv4_range_scope_reports_its_own_bounds() {
        let mut ips = IpSet::new();
        ips.push_v4_range(
            Ipv4Range::new(Ipv4Addr::new(192, 0, 2, 5), Ipv4Addr::new(192, 0, 2, 9))
                .expect("valid range"),
        );

        let scope = TargetScope::from_ip_set(&mut ips, &Exclusions::none());

        assert_eq!(scope.addresses(), 5);
        assert_eq!(
            scope.ranges()[0].start_addr(),
            IpAddr::V4(Ipv4Addr::new(192, 0, 2, 5))
        );
    }

    /// A dual-stack host is one host, counted under both families.
    ///
    /// These counts answer "how much of this network did I see over IPv6",
    /// which is a different question from "how do the hosts partition", so
    /// they do not sum to `hosts_total`, and a test that asserted
    /// they did would be pinning the wrong contract.
    #[test]
    fn family_counts_record_a_dual_stack_host_under_both() {
        let mut dual = Host::new(ip(1));
        dual.add_ip(IpAddr::from_str("2001:db8::1").unwrap());
        let v6_only = Host::new(IpAddr::from_str("2001:db8::2").unwrap());

        let report = ScanReport::new(
            phase(ScanKind::Discovery),
            [dual, Host::new(ip(2)), v6_only],
        );

        let summary = report.summary();
        assert_eq!(summary.hosts_total, 3);
        assert_eq!(summary.hosts_by_family.ipv4, 2);
        assert_eq!(summary.hosts_by_family.ipv6, 2);
        assert_eq!(summary.hosts_by_family.dual_stack, 1);
    }
}