zond-engine 0.18.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
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
// 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

//! # One scan's journal on disk
//!
//! ```text
//! <root>/<id>/
//!     manifest.json   the plan, written as the job begins
//!     cursor.json     how far the scan got, rewritten on a timer
//!     hosts.jsonl     what it found, appended as it finds it
//!     phases.jsonl    what each sitting did, appended as each one ends
//!     sitting-*.jsonl what a sitting has done so far, until it ends
//!     LOCK            who is writing, if anyone
//! ```
//!
//! The cursor is rewritten because it describes one state, and the findings are
//! appended because they accumulate. A host that changes appears more than once
//! and the records fold together on reading, the later over the earlier, which
//! is what makes a torn tail survivable: the worst it costs is one host's most
//! recent update.
//!
//! ## A host is written by what changed in it
//!
//! A record carries the whole host but only the ports that differ from what
//! the file already holds of them. A host scanned on every port holds tens of
//! thousands of them, and written whole each time anything about it changed it
//! was a record of megabytes every checkpoint, most of it a copy of the last.
//! Folding is what makes leaving the rest out safe: a port's later record is
//! merged over its earlier one, and a port a record leaves out keeps what the
//! file already says of it. What the file holds of each port is remembered as a
//! digest of the record written, so telling what changed costs no copy of the
//! host.
//!
//! ## A sitting is written down before it ends
//!
//! A sitting's phases are appended to `phases.jsonl` when it stops, and one
//! killed outright never stops. So each sitting also keeps a file of its own,
//! named for when it started, holding its phases as they stand: those that
//! have closed, and the open one so far. It is rewritten whole at every
//! checkpoint and removed once the phases are appended. One still there when
//! the journal is read is a sitting that never ended, and its phases are read
//! beside the rest. A phase that never closed says what it opened with, how
//! long it ran and what failed in it, and claims nothing only its close could
//! establish; it says instead that it is open, which is what keeps it from
//! reading as a phase that ran to its end. A phase read from both, left by
//! a sitting stopped between the append and the removal, is read once.
//!
//! [`Journal::create`] begins one, [`Journal::resume`] continues one, and
//! [`list`] enumerates them for a caller offering a choice.
//!
//! A journal holds the addresses an engagement was pointed at, so everything is
//! `0600` under a `0700` directory, and a scan that runs elevated leaves it owned
//! by the user who invoked it rather than by root. See [`paths`](super::paths).

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use super::cursor::Checkpoint;
use super::file::{
    append_existing, claim_directory_for_invoking_user, create_private as create_private_file,
    create_private_directory, exists, kinds, names, open_existing, open_to_read,
    remove as remove_file, remove_directory, replace,
};
use super::format::JournalError;
use super::lock::{Lock, LockRefused, LockState};
use super::manifest::{JobOptions, JournalManifest, Plan, PlanChanged};
use super::ownership::Kind;
use super::settle::Settlements;
use crate::detect::compute::{DetectionLine, DetectionRunRecord, PortRunsRecord};
use crate::model::host::Host;
use crate::model::ip::scoped::ScopedIp;
use crate::model::port::Protocol;
use crate::record::{HostRecord, PhaseRecord};
use crate::report::{ScanKind, ScanPhase, ScanReport, Unheard};
use crate::system::privilege::Privilege;

const MANIFEST: &str = "manifest.json";
const CURSOR: &str = "cursor.json";
const HOSTS: &str = "hosts.jsonl";
const PHASES: &str = "phases.jsonl";
const DETECTIONS: &str = "detections.jsonl";
/// The hosts each sitting that ran to its end had run every pass over. See
/// [`Journal::record_finished`].
const FINISHED: &str = "finished.jsonl";
const LOCK: &str = "LOCK";
/// What a sitting's record of its phases as they stand is named after,
/// before when it started.
const SITTING: &str = "sitting-";
/// What the job runs under, written once, when its first sitting starts. See
/// [`Journal::options`].
const OPTIONS: &str = "options.json";

/// Why a journal could not be opened for writing.
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum OpenError {
    /// The plan offered is not the plan this journal's positions are counted in.
    #[error("{0}")]
    PlanChanged(#[from] PlanChanged),

    /// The journal records the other phase of a scan.
    ///
    /// A sweep's positions count addresses and a port scan's count
    /// address-and-port pairs, so one continued as the other would skip targets
    /// nothing ever probed.
    #[error("this journal records a {held} and cannot be continued as a {asked}")]
    WrongPhase {
        /// The phase the journal holds.
        held: &'static str,
        /// The phase it was asked to continue as.
        asked: &'static str,
    },

    /// The journal was written under a format this build can read but cannot
    /// continue.
    ///
    /// Only [`Journal::resume`] raises it. [`report`] and [`list`] read such a
    /// journal as they read any other, since everything written down still means
    /// what it said. What is gone is the ability to prove the plan has not moved,
    /// and continuing a scan on an unprovable plan is the failure
    /// [`manifest`](crate::journal::manifest) exists to prevent.
    #[error(
        "this journal was written in format {found} and this build continues \
         format {understood}; its findings still read, but it cannot be resumed"
    )]
    VersionTooOld {
        /// The format the journal was written in.
        found: u32,
        /// The format this build continues.
        understood: u32,
    },

    /// Somebody else holds it, or might.
    #[error("{0}")]
    Locked(LockRefused),

    /// The journal could not be read or written.
    #[error("{0}")]
    Journal(#[from] JournalError),
}

impl From<LockRefused> for OpenError {
    fn from(refused: LockRefused) -> Self {
        OpenError::Locked(refused)
    }
}

/// A journal open for writing.
///
/// Releases its lock on drop.
#[derive(Debug)]
pub struct Journal {
    directory: PathBuf,
    manifest: JournalManifest,
    lock: Lock,
    resume_point: Checkpoint,
    restored: Vec<Host>,
    earlier: Vec<ScanPhase>,
    /// Whether this handle made the journal, rather than reopening one. See
    /// [`withdraw`](Journal::withdraw).
    created: bool,
    options: Option<JobOptions>,
    /// What the findings file holds of each host, and how much of it later
    /// records superseded. See [`record_hosts`](Journal::record_hosts).
    written: Written,
    /// How long the findings file is.
    length: u64,
    /// How much has to be superseded before a compaction is tried again, once
    /// one has failed. See [`compact`](Journal::compact).
    compact_after: u64,
    /// Where this sitting writes its phases as they stand. See the module
    /// documentation.
    sitting: PathBuf,
}

impl Journal {
    /// Begins a journal for `plan` under `root`, minting an id for it.
    ///
    /// The plan carries which phase it belongs to, so a sweep and a port scan
    /// both come through here and neither can be read back as the other.
    pub fn create(
        root: &Path,
        plan: &Plan,
        privilege: Privilege,
        summary: impl Into<String>,
    ) -> Result<Self, OpenError> {
        let (id, directory) = claim_directory(root)?;
        let manifest = JournalManifest::new(id, plan, privilege, summary);

        // A scan that never started should leave no trace, whichever step
        // failed, so every failure past the claim is caught in this one arm.
        // Without it, a lock it could not take would clean up after itself, but
        // a manifest write that ran out of disk, or a findings header that could
        // not be flushed, would propagate and leave the directory behind, which
        // lists as a scan that found nothing, or does not list at all. Both are
        // the state that reasoning called unreadable.
        match Self::furnish(&directory, manifest) {
            Ok(journal) => Ok(journal),
            Err(error) => {
                let _ = remove_directory(&directory);
                Err(error)
            }
        }
    }

    /// Everything [`create`](Self::create) does once the directory is claimed.
    ///
    /// Split out so there is one place a failure past the claim is caught, rather
    /// than each step having to remember to undo the directory on its way out.
    fn furnish(directory: &Path, manifest: JournalManifest) -> Result<Self, OpenError> {
        write_private(
            &directory.join(MANIFEST),
            &serde_json::to_vec(&manifest).map_err(JournalError::json)?,
        )?;

        let lock = Lock::acquire(&directory.join(LOCK))?;
        let sitting = sitting_file(directory, &lock);

        let mut journal = Self {
            directory: directory.to_path_buf(),
            manifest,
            lock,
            resume_point: Checkpoint::default(),
            restored: Vec::new(),
            earlier: Vec::new(),
            created: true,
            options: None,
            written: Written::default(),
            length: 0,
            compact_after: 0,
            sitting,
        };
        journal.open_findings()?;
        journal.length = findings_length(directory)?;
        Ok(journal)
    }

    /// Continues the journal at `directory`, refusing a plan that has moved or a
    /// scan somebody else is running.
    ///
    /// Returns the checkpoint to subtract from the plan; feed it to
    /// [`Checkpoint::remaining`] and to [`Settlements::resuming`].
    pub fn resume(
        directory: &Path,
        plan: &Plan,
        privilege: Privilege,
    ) -> Result<(Self, Checkpoint), OpenError> {
        Self::resume_locking(directory, plan, privilege, Lock::acquire)
    }

    /// [`resume`](Self::resume), taking the lock by `lock`.
    fn resume_locking(
        directory: &Path,
        plan: &Plan,
        privilege: Privilege,
        lock: fn(&Path) -> Result<Lock, LockRefused>,
    ) -> Result<(Self, Checkpoint), OpenError> {
        let manifest = read_manifest(directory)?;
        // The format before anything about the plan, since it decides whether
        // the fingerprint below is a value this build can recompute. A journal
        // from an older derivation would otherwise fail `covers` and be reported
        // as a plan that changed, which that message must never say when the
        // plan did not.
        if manifest.journal_version < super::JOURNAL_VERSION {
            return Err(OpenError::VersionTooOld {
                found: manifest.journal_version,
                understood: super::JOURNAL_VERSION,
            });
        }
        // The phase before the fingerprint, so continuing a sweep as a port scan
        // is named for what it is rather than reported as a plan that moved.
        if manifest.kind() != plan.kind() {
            return Err(OpenError::WrongPhase {
                held: phase_name(manifest.kind()),
                asked: phase_name(plan.kind()),
            });
        }
        // The plan next. A refusal here is about the caller's arguments, and
        // reporting it before taking a lock means a mistaken resume disturbs
        // nothing.
        manifest.covers(plan, privilege)?;

        let lock = lock(&directory.join(LOCK))?;
        let sitting = sitting_file(directory, &lock);
        let checkpoint = read_checkpoint(directory)?;
        let earlier = read_phases(directory)?;
        // Less the records the earlier sittings heard nothing from, which a
        // report of the job drops by the same reading, but for those a
        // sitting killed before its verdicts left for this one to decide; see
        // `Unheard::decided`.
        let unheard = Unheard::decided(&earlier);
        let mut restored = read_findings(directory)?;
        restored.retain(|host| !unheard.drops(host));
        // What the file already holds, so a restored host a new sitting changes
        // is written by what changed in it rather than whole. Whatever the file
        // holds beyond what those fold to is records they superseded. A file an
        // earlier sitting left behind with nothing in it is no length at all.
        let length = findings_length(directory)?;
        let written = Written::holding(&restored, length)?;

        Ok((
            Self {
                directory: directory.to_path_buf(),
                manifest,
                lock,
                resume_point: checkpoint.clone(),
                restored,
                earlier,
                created: false,
                options: read_options(directory)?,
                written,
                length,
                compact_after: 0,
                sitting,
            },
            checkpoint,
        ))
    }

    /// Continues the journal at `directory`, scanning the plan it recorded.
    ///
    /// The counterpart of [`resume`](Self::resume) for a caller who has nothing
    /// to describe the scan with but its id. The plan comes back as it was
    /// written down, phase included, so a hostname that has moved since does not
    /// change what is being continued and a caller that can only continue one of
    /// the two phases can see which it has
    /// before it starts.
    ///
    /// Refused if this process holds different privileges than the scan did: the
    /// connect fallback asks a different question than a raw technique does, and
    /// a journal half of each would be counting two things.
    pub fn reopen(
        directory: &Path,
        privilege: Privilege,
    ) -> Result<(Self, Checkpoint, Plan), OpenError> {
        let plan = read_manifest(directory)?.recorded();
        let (journal, checkpoint) = Self::resume(directory, &plan, privilege)?;
        Ok((journal, checkpoint, plan))
    }

    /// [`reopen`](Self::reopen), taking over a lock whose holder has stopped
    /// checkpointing.
    ///
    /// For the refusal [`LockState::Stale`] names: a live process holds the
    /// number the lock records, and nothing here can tell whether it is the
    /// scan, hung, or an unrelated process the number was reissued to after
    /// the scan died. A caller who knows which it is can continue the job
    /// here instead of removing the lock by hand. A lock whose holder is
    /// checkpointing now is still refused. See [`Lock::take_over`].
    pub fn take_over(
        directory: &Path,
        privilege: Privilege,
    ) -> Result<(Self, Checkpoint, Plan), OpenError> {
        let plan = read_manifest(directory)?.recorded();
        let (journal, checkpoint) =
            Self::resume_locking(directory, &plan, privilege, Lock::take_over)?;
        Ok((journal, checkpoint, plan))
    }

    /// What earlier sittings of this scan found.
    ///
    /// Empty for a journal just created. A scan seeds its store with these, so
    /// the report it produces describes the whole job rather than the last
    /// sitting of it.
    ///
    /// A record of an address an earlier sitting went on to hear nothing from
    /// is left out, as the job's report leaves it out. One a sitting killed
    /// before its port phase's verdicts had yet to decide is here, though the
    /// report leaves it out as well: this sitting asks what is left at the
    /// address and decides it.
    pub fn restored(&self) -> &[Host] {
        &self.restored
    }

    /// Appends what `hosts` currently hold that the file does not.
    ///
    /// Called with whatever
    /// [`take_changed_hosts`](crate::scanner::session::ScanContext::take_changed_hosts)
    /// yields, so a host is written once per change rather than once per
    /// checkpoint for the rest of the run. Each record carries the host's own
    /// fields and only the ports that changed since the file last held them;
    /// see the module documentation for why that reads back as the whole host.
    /// A host may carry only some of its ports, and those it leaves out stand
    /// as the file holds them. A host the file already holds as it is gets no
    /// record.
    ///
    /// What was written is remembered only once the write has succeeded, so a
    /// failed one leaves every port it carried to be written again.
    pub fn record_hosts(&mut self, hosts: &[Host]) -> Result<(), JournalError> {
        let mut records = Vec::with_capacity(hosts.len());
        for host in hosts {
            records.extend(self.written.delta(host)?);
        }
        if records.is_empty() {
            return Ok(());
        }

        let file = open_for_append(&self.directory.join(HOSTS))?;
        // Measured on the handle, as a compaction measures what it wrote.
        let measured = file.try_clone()?;

        let mut deltas = Vec::with_capacity(records.len());
        let mut writer = crate::journal::format::Writer::append(std::io::BufWriter::new(file));
        for (record, delta) in records {
            writer.write(&record)?;
            deltas.push(delta);
        }
        writer.flush()?;
        drop(writer);

        for delta in deltas {
            self.written.update(delta);
        }
        self.length = measured.metadata()?.len();
        Ok(())
    }

    /// Appends the tapes of detection runs, each recording what one detection read
    /// from its capabilities so the run can be replayed offline later.
    ///
    /// Written a port to a line, the responses the port's runs read held once
    /// for all of them; see `PortRunsRecord`. [`read_detections`] hands each
    /// run back whole.
    ///
    /// Its own file, created on the first run and appended after. The resume path
    /// never reads it: a tape is evidence for later analysis, not a settled
    /// verdict, so it does not advance a cursor or change what a resume skips.
    ///
    /// All or nothing: a write that fails part way is cut back to where it
    /// began, so a caller that hands the same runs to a later write records
    /// each of them once.
    pub fn record_detections(&mut self, runs: &[DetectionRunRecord]) -> Result<(), JournalError> {
        if runs.is_empty() {
            return Ok(());
        }

        // Appending is tried first and the file created only where there is
        // none, rather than asking whether one exists and then acting on the
        // answer. `create_private` refuses a name that exists, so losing that
        // race is reported rather than costing every tape written before it.
        let path = self.directory.join(DETECTIONS);
        let (file, mut writer) = match open_for_append(&path) {
            Ok(file) => {
                let written = file.try_clone()?;
                let writer =
                    crate::journal::format::Writer::append(std::io::BufWriter::new(written));
                (file, writer)
            }
            Err(JournalError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
                let file = create_private_file(&path)?;
                let written = file.try_clone()?;
                let writer =
                    crate::journal::format::Writer::create(std::io::BufWriter::new(written))?;
                (file, writer)
            }
            Err(error) => return Err(error),
        };
        // Where this write begins: past the header a new file was just given,
        // which a write cut back leaves in place.
        writer.flush()?;
        let began = file.metadata()?.len();
        let outcome = PortRunsRecord::grouping(runs)
            .iter()
            .try_for_each(|line| writer.write(line))
            .and_then(|()| writer.flush());
        if outcome.is_err() {
            // Dropped first, since dropping flushes what it still buffers,
            // and then everything written past the start is cut away. A cut
            // that fails too leaves a torn tail, which the next append mends.
            drop(writer);
            let _ = file.set_len(began);
        }
        outcome
    }

    /// Appends that a sitting ran every pass that follows its probes over
    /// `hosts`, each named as its address and link are written.
    ///
    /// For a sitting that ran to its end, whose passes each finished over
    /// every host it held. A later sitting reads these back through
    /// [`finished_hosts`](Self::finished_hosts) and runs those passes again
    /// only over what it asks something new of. Without the record, every
    /// sitting would identify each port's service, run each detection, walk
    /// each TLS port and trace each route again for every host an earlier one
    /// had finished with, which on a job resumed after it was done is the whole
    /// of what the resume does.
    ///
    /// Its own file, created on the first record and appended after, so a
    /// journal an older engine wrote reads as one no sitting finished, and a
    /// newer one read by an older engine is merely not consulted.
    pub(crate) fn record_finished(
        &mut self,
        hosts: impl IntoIterator<Item = String>,
    ) -> Result<(), JournalError> {
        let record = FinishedRecord {
            hosts: hosts.into_iter().collect(),
        };
        if record.hosts.is_empty() {
            return Ok(());
        }

        // Created where there is none, as the tapes' file is; see
        // `record_detections` for why appending is tried first.
        let path = self.directory.join(FINISHED);
        let mut writer = match open_for_append(&path) {
            Ok(file) => crate::journal::format::Writer::append(std::io::BufWriter::new(file)),
            Err(JournalError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
                let file = create_private_file(&path)?;
                crate::journal::format::Writer::create(std::io::BufWriter::new(file))?
            }
            Err(error) => return Err(error),
        };
        writer.write(&record)?;
        writer.flush()
    }

    /// Every host an earlier sitting that ran to its end had finished every
    /// pass over, named as [`record_finished`](Self::record_finished) wrote
    /// it.
    ///
    /// Empty for a journal no sitting finished, and for one written before the
    /// record was kept, which a resume reads as owing every pass to every host.
    pub(crate) fn finished_hosts(&self) -> Result<HashSet<String>, JournalError> {
        let file = match open_to_read(&self.directory.join(FINISHED)) {
            Ok(file) => file,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(HashSet::new()),
            Err(e) => return Err(e.into()),
        };
        let mut reader = match crate::journal::format::Reader::open(std::io::BufReader::new(file)) {
            Ok(reader) => reader,
            Err(JournalError::NotAJournal) => return Ok(HashSet::new()),
            Err(e) => return Err(e),
        };

        let mut hosts = HashSet::new();
        while let Some(record) = reader.read::<FinishedRecord>()? {
            hosts.extend(record.hosts);
        }
        Ok(hosts)
    }

    /// Whether the findings file holds enough superseded records to be worth
    /// writing whole again.
    ///
    /// A host is appended each interval in which anything about it changed,
    /// and the dispatcher shuffles targets across the whole plan, so on a long
    /// scan most hosts change in most intervals. Their ports are written only
    /// as they change, but each record repeats the host's own fields, so the
    /// file grows with the scan's duration as well as with what it found.
    /// Compaction bounds it.
    ///
    /// Counted in bytes, since what a compaction costs and what it recovers
    /// are both bytes, and a count of records says neither: one record can be
    /// a line or a host's every port. What is counted is what later records
    /// superseded, not what was appended, since a file growing by what the
    /// scan found holds nothing a rewrite would drop. The file is rewritten
    /// once the superseded part outgrows the rest, so it stays under twice
    /// its live size, and a compaction writing the live part is paid for by
    /// at least as much superseded since the last one. Below the floor a file
    /// is not worth rewriting whatever it holds.
    pub fn should_compact(&self) -> bool {
        outgrown(self.length, self.written.superseded)
            && self.written.superseded >= self.compact_after
    }

    /// Writes the findings file whole, replacing everything superseded.
    ///
    /// `all` has to be every host the scan has found rather than the recent ones,
    /// since this replaces the file rather than adding to it. Written to a sibling
    /// and renamed over, so a compaction interrupted part way leaves the previous
    /// file untouched.
    ///
    /// A compaction that fails removes its sibling, and
    /// [`should_compact`](Self::should_compact) does not ask for another until
    /// as much again has been superseded. What stops one, most often a disk
    /// with no room for a second copy of the findings, stops the next, and one
    /// is due every checkpoint once the file has outgrown itself: retried each
    /// time, a scan would write the live findings again every few seconds and
    /// leave a partial copy holding whatever room the disk had left.
    pub fn compact(&mut self, all: &[Host]) -> Result<(), JournalError> {
        let compacted = self.write_whole(all);
        if compacted.is_err() {
            let superseded = self.written.superseded;
            let live = self.length.saturating_sub(superseded);
            self.compact_after = superseded.saturating_add(COMPACT_FLOOR.max(live));
        }
        compacted
    }

    /// [`compact`](Self::compact)'s writing, through a staged sibling that a
    /// failure removes.
    fn write_whole(&mut self, all: &[Host]) -> Result<(), JournalError> {
        let destination = self.directory.join(HOSTS);
        let (written, length) = replace(
            &destination,
            &destination.with_extension("jsonl-tmp"),
            |file| {
                // Measured on the handle, so the length is the file's that was
                // written rather than whatever the name holds by the time it is
                // asked.
                let measured = file.try_clone()?;
                let mut written = Written::default();
                let mut writer =
                    crate::journal::format::Writer::create(std::io::BufWriter::new(file))?;
                for host in all {
                    // Measured against nothing written, so the record is the
                    // whole host and what it remembers is all of it.
                    if let Some((record, delta)) = Written::default().delta(host)? {
                        writer.write(&record)?;
                        written.update(delta);
                    }
                }
                writer.flush()?;
                drop(writer);
                Ok::<_, JournalError>((written, measured.metadata()?.len()))
            },
        )?;
        self.written = written;
        self.length = length;
        self.compact_after = 0;
        Ok(())
    }

    /// What earlier sittings of this scan did.
    ///
    /// A resumed report carries these alongside its own, so it describes a job
    /// that ran in several sittings rather than presenting the last one as the
    /// whole of it.
    pub fn earlier_phases(&self) -> &[ScanPhase] {
        &self.earlier
    }

    /// Appends what one sitting did, once it has finished doing it.
    pub fn record_phases(&mut self, phases: &[ScanPhase]) -> Result<(), JournalError> {
        if phases.is_empty() {
            return Ok(());
        }

        let file = open_for_append(&self.directory.join(PHASES))?;

        let mut writer = crate::journal::format::Writer::append(std::io::BufWriter::new(file));
        for phase in phases {
            writer.write(&PhaseRecord::from(phase))?;
        }
        writer.flush()
    }

    /// Writes down this sitting's phases as they stand, over what it wrote
    /// of them last. See the module documentation.
    ///
    /// Written to a sibling and renamed over, as the cursor is, so a sitting
    /// killed part way through leaves the previous record whole.
    pub(crate) fn record_standing(&mut self, phases: &[ScanPhase]) -> Result<(), JournalError> {
        if phases.is_empty() {
            return Ok(());
        }
        replace(
            &self.sitting,
            &self.sitting.with_extension("jsonl-tmp"),
            |file| {
                let mut writer =
                    crate::journal::format::Writer::create(std::io::BufWriter::new(file))?;
                for phase in phases {
                    writer.write(&PhaseRecord::from(phase))?;
                }
                writer.flush()
            },
        )
    }

    /// Appends what one sitting did once it has finished doing it, and
    /// removes what it wrote of its phases as they stood.
    ///
    /// The removal only once the append has landed: until then the standing
    /// record is the only one there is.
    pub(crate) fn end_sitting(&mut self, phases: &[ScanPhase]) -> Result<(), JournalError> {
        if phases.is_empty() {
            return Ok(());
        }
        self.record_phases(phases)?;
        match remove_file(&self.sitting) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e.into()),
        }
    }

    /// Writes the appended files' headers, so each is self-describing before
    /// anything is added to it.
    fn open_findings(&mut self) -> Result<(), JournalError> {
        for name in [HOSTS, PHASES] {
            let path = self.directory.join(name);
            let file = create_private_file(&path)?;
            crate::journal::format::Writer::create(std::io::BufWriter::new(file))?.flush()?;
        }
        Ok(())
    }

    /// What an earlier sitting settled, and this one may skip.
    ///
    /// Empty for a journal that was just created. A scan reads this to seed both
    /// its dispatcher and its settlements, so the second sitting's cursor
    /// continues the first's rather than starting over.
    pub fn resume_point(&self) -> &Checkpoint {
        &self.resume_point
    }

    /// Writes how far the scan has got, and reports the writer is alive.
    ///
    /// Cheap enough to call on a timer. The cursor is a watermark and a short
    /// list however large the scan is, and the write is a rename over a small
    /// file. See [`Checkpoint::write_atomically`].
    pub fn checkpoint(&mut self, settlements: &Settlements) -> Result<(), JournalError> {
        self.write_cursor(&settlements.checkpoint())
    }

    /// Writes `cursor` as how far the scan has got, and reports the writer is
    /// alive.
    ///
    /// For a writer that read the cursor before taking the findings it wrote
    /// beside it, which is the order a running scan needs; see
    /// [`checkpoint`](crate::scanner::checkpoint).
    pub(crate) fn write_cursor(&mut self, cursor: &Checkpoint) -> Result<(), JournalError> {
        cursor.write_atomically(&self.directory.join(CURSOR))?;
        self.lock.beat()
    }

    /// Writes down what the scan has found and how far it has got.
    ///
    /// Findings first. A cursor claiming a target is settled, beside a file
    /// missing what settling it produced, is the one ordering that loses a
    /// finding. The other way round costs a target being probed twice.
    ///
    /// The cursor is read here, after `hosts` were taken, so this suits a scan
    /// that has stopped settling targets. While one is running, a target can
    /// settle between the two readings with its finding in neither; the
    /// scanner's own checkpoints read the cursor first for that reason.
    pub fn record(
        &mut self,
        hosts: &[Host],
        settlements: &Settlements,
    ) -> Result<(), JournalError> {
        self.record_hosts(hosts)?;
        self.checkpoint(settlements)
    }

    /// The options the job runs under, or `None` where they were never
    /// recorded.
    ///
    /// Recorded by the engine when the journal's first sitting starts, from the
    /// configuration it was handed, and never rewritten. A later sitting is
    /// held to them, and a caller continuing a job by its id restores them with
    /// [`JobOptions::apply_to`]; the type says which options those are.
    ///
    /// `None` for a journal whose first sitting ran on an engine that did not
    /// record them, for one no sitting has started yet, and for a watch's,
    /// which asks nothing for them to decide. The first has no record of what
    /// it ran under and is continued under whatever the caller passes.
    pub fn options(&self) -> Option<&JobOptions> {
        self.options.as_ref()
    }

    /// Records the options the job runs under, where this is its first
    /// sitting.
    ///
    /// Only then: a journal an earlier sitting ran against without recording
    /// them ran under options nobody wrote down, and recording this sitting's
    /// as the job's would claim the earlier one ran under them too.
    ///
    /// The ports they exclude are ones every sitting numbers the plan without,
    /// so no sitting asks or settles them, and the manifest's total, written
    /// before they were known, counts them out here. Counted in, they are a
    /// remainder nothing reaches: a finished job would list as unfinished for
    /// good, and a resume would announce probes it will not send. Only in a
    /// manifest this handle wrote: rewriting one another build wrote would
    /// drop whatever fields this one does not know.
    pub(crate) fn record_options(&mut self, options: JobOptions) -> Result<(), JournalError> {
        if self.options.is_some() || !self.is_untouched() {
            return Ok(());
        }

        write_private(
            &self.directory.join(OPTIONS),
            &serde_json::to_vec(&options).map_err(JournalError::json)?,
        )?;
        let numbered = self
            .manifest
            .recorded()
            .numbered_targets(&options.excluded_ports());
        self.options = Some(options);
        if self.created && numbered != self.manifest.total_targets {
            self.manifest.total_targets = numbered;
            write_private(
                &self.directory.join(MANIFEST),
                &serde_json::to_vec(&self.manifest).map_err(JournalError::json)?,
            )?;
        }
        Ok(())
    }

    /// Whether no sitting has run against this journal: no cursor written, no
    /// phase and no finding recorded.
    ///
    /// A cursor that cannot be looked for is taken to be there, which keeps
    /// the journal: what this decides is whether to write the job's options
    /// and whether to remove the journal, and a journal wrongly called touched
    /// costs a record of its options, where one wrongly called untouched
    /// could lose a sitting's work.
    fn is_untouched(&self) -> bool {
        self.earlier.is_empty()
            && self.restored.is_empty()
            && !exists(&self.directory.join(CURSOR)).unwrap_or(true)
    }

    /// What this journal is a journal of.
    pub fn manifest(&self) -> &JournalManifest {
        &self.manifest
    }

    /// Where it lives.
    pub fn directory(&self) -> &Path {
        &self.directory
    }

    /// Gives up a journal handed to a scan that refused before it started, and
    /// removes it if no sitting ever ran against it.
    ///
    /// A scan that never started should leave no trace, which is the rule
    /// [`create`](Self::create) keeps for a journal it could not finish
    /// making, and a refusal is the same case arriving later. Kept, the record
    /// lists as a job nobody ran, resumable with nothing done, and counts
    /// against whatever limit a front end keeps on records. Its caller cannot
    /// tidy it: the journal was handed over by value.
    ///
    /// Only a journal this handle made and no sitting has touched: no cursor
    /// written, no phase and no finding recorded. One an earlier sitting ran
    /// against holds that sitting's work. One reopened was kept by whoever
    /// made it, even with nothing in it, and a caller reopens a job to run it
    /// once a first attempt was refused. Either is released for the next
    /// sitting.
    ///
    /// Removed while the lock is held, so nothing takes the journal up between
    /// the decision and the removal. The lock file goes with the directory and
    /// the drop that follows finds nothing to release, which it tolerates.
    pub(crate) fn withdraw(self) {
        if self.created && self.is_untouched() {
            // Best effort, as removing a half-made journal in `create` is: a
            // directory that will not go is a record of nothing, which is the
            // state this avoids rather than a reason to report the refusal
            // any differently.
            let _ = remove_directory(&self.directory);
        }
    }

    /// Releases the lock, reporting a failure the drop would swallow.
    pub fn close(self) -> Result<(), JournalError> {
        self.lock.release()
    }
}

/// Whether a findings file `length` bytes long, `superseded` of them records
/// something later superseded, is due to be written whole again. See
/// [`Journal::should_compact`].
fn outgrown(length: u64, superseded: u64) -> bool {
    superseded > COMPACT_FLOOR.max(length.saturating_sub(superseded))
}

/// The size below which a findings file is not worth rewriting.
const COMPACT_FLOOR: u64 = 4 * 1024 * 1024;

/// What a journal's findings file holds of each host, and how many of its
/// bytes later records superseded.
///
/// Each port is remembered as a digest of the record last written for it,
/// rather than as the port, so remembering what was written costs a few bytes
/// a port rather than a second copy of every host the scan holds. Kept for
/// this process only and never written down, so the hasher need not be stable
/// across builds.
///
/// Sizes are those of each piece as serialised, which is within a separator of
/// what the line holds; the count they feed is a threshold, not an account.
#[derive(Debug, Default)]
struct Written {
    hosts: std::collections::HashMap<ScopedIp, HeldHost>,
    /// How many of the file's bytes hold what a later record superseded.
    superseded: u64,
}

/// What the findings file holds of one host.
#[derive(Debug, Default)]
struct HeldHost {
    /// Its last record, less its ports.
    rest: Option<Mark>,
    ports: std::collections::HashMap<PortKey, Mark>,
}

/// A port as a host keys it: its number and its transport.
type PortKey = (u16, Protocol);

/// A record as written: a digest of it, and how long it was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Mark {
    digest: u64,
    length: u32,
}

/// What one record wrote of one host, to remember once the write succeeds.
#[derive(Debug)]
struct Delta {
    key: ScopedIp,
    rest: Mark,
    ports: Vec<(PortKey, Mark)>,
}

impl Delta {
    /// How many bytes the record holds, near enough.
    fn length(&self) -> u64 {
        u64::from(self.rest.length)
            + self
                .ports
                .iter()
                .map(|(_, mark)| u64::from(mark.length))
                .sum::<u64>()
    }
}

impl Written {
    /// What a file `length` bytes long holds, where `hosts` are what it folds
    /// to: those whole, and the rest of the file superseded.
    fn holding(hosts: &[Host], length: u64) -> Result<Self, JournalError> {
        let mut written = Self::default();
        let mut live = 0;
        for host in hosts {
            // A file that holds nothing of a host holds all of it as new.
            if let Some((_, delta)) = Self::default().delta(host)? {
                live += delta.length();
                written.update(delta);
            }
        }
        written.superseded = length.saturating_sub(live);
        Ok(written)
    }

    /// `host` as a record carrying only the ports whose record differs from
    /// what was last written of them, and what writing it would hold; `None`
    /// where the file already holds all of it.
    ///
    /// Compared rather than trusted to have changed: a host is marked changed
    /// by whatever edited it, and an edit that confirmed what was on record,
    /// a finding reached again or a service named as it was, changes nothing a
    /// record would carry. Written anyway, every such pass over a host would
    /// cost a record of it.
    fn delta(&self, host: &Host) -> Result<Option<(HostRecord, Delta)>, JournalError> {
        let held = self.hosts.get(&host.scoped_ip());
        let mut record = HostRecord::from(host);
        // `HostRecord` lists the ports in the order the host yields them, so
        // the two walk together.
        let ports = std::mem::take(&mut record.ports);
        let rest = mark(&record)?;
        let mut changed = Vec::new();
        for (port, written) in host.ports().zip(ports) {
            debug_assert_eq!(
                port.number(),
                written.port,
                "a record lists its host's ports"
            );
            let key = (port.number(), port.protocol());
            let mark = mark(&written)?;
            let unchanged = held
                .and_then(|held| held.ports.get(&key))
                .is_some_and(|was| was.digest == mark.digest);
            if !unchanged {
                changed.push((key, mark));
                record.ports.push(written);
            }
        }
        let unchanged = changed.is_empty()
            && held.and_then(|held| held.rest).map(|was| was.digest) == Some(rest.digest);
        if unchanged {
            return Ok(None);
        }
        let delta = Delta {
            key: host.scoped_ip(),
            rest,
            ports: changed,
        };
        Ok(Some((record, delta)))
    }

    /// Records that the file holds what `delta` wrote, over whatever it held
    /// of that host before, and counts what that superseded.
    fn update(&mut self, delta: Delta) {
        let held = match self.hosts.entry(delta.key) {
            std::collections::hash_map::Entry::Occupied(slot) => {
                let held = slot.into_mut();
                self.superseded += held.rest.map_or(0, |was| u64::from(was.length));
                held
            }
            std::collections::hash_map::Entry::Vacant(slot) => slot.insert(HeldHost::default()),
        };
        held.rest = Some(delta.rest);
        for (key, mark) in delta.ports {
            if let Some(was) = held.ports.insert(key, mark) {
                self.superseded += u64::from(was.length);
            }
        }
    }
}

/// A digest of `record` as it is written, and its length: the same
/// serialisation the file gets, fed to a hasher rather than to a buffer.
fn mark(record: &impl serde::Serialize) -> Result<Mark, JournalError> {
    use std::hash::Hasher;

    struct Hashing {
        hasher: std::collections::hash_map::DefaultHasher,
        length: u64,
    }
    impl std::io::Write for Hashing {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.hasher.write(bytes);
            self.length += bytes.len() as u64;
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    let mut hashing = Hashing {
        hasher: std::collections::hash_map::DefaultHasher::new(),
        length: 0,
    };
    serde_json::to_writer(&mut hashing, record).map_err(JournalError::json)?;
    Ok(Mark {
        digest: hashing.hasher.finish(),
        // A separator or a newline beside it, and saturated for a record past
        // four gigabytes, which is past what a journal line is read in.
        length: u32::try_from(hashing.length + 1).unwrap_or(u32::MAX),
    })
}

/// A journal as it appears to a caller choosing between them. Read without
/// taking the lock, so listing never disturbs a running scan.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Entry {
    /// Where it lives.
    pub directory: PathBuf,
    /// What it is a journal of.
    pub manifest: JournalManifest,
    /// How far it got, or `None` where that could not be read.
    ///
    /// A journal that never checkpointed carries a fresh cursor rather than
    /// nothing, since settling no targets is a fact about the scan. `None` is the
    /// other case: the file is there and this process cannot read it, usually
    /// because the scan ran under `sudo` and left it behind. That must not read
    /// as no progress, or a listing reports every such scan as
    /// untouched and offers to continue work that is already done.
    pub checkpoint: Option<Checkpoint>,
    /// Whether anything is writing it.
    pub lock: LockState,
}

impl Entry {
    /// A listing entry from its parts, for a caller rendering one it did not
    /// read off disk.
    pub fn new(
        directory: PathBuf,
        manifest: JournalManifest,
        checkpoint: Option<Checkpoint>,
        lock: LockState,
    ) -> Self {
        Self {
            directory,
            manifest,
            checkpoint,
            lock,
        }
    }

    /// Whether this journal has anything left to do.
    ///
    /// A journal whose cursor covers the whole plan is finished; one that never
    /// checkpointed has everything left. One whose cursor cannot be read is not
    /// finished as far as anything here can tell, which is the answer that keeps
    /// a retention sweep from deleting it.
    pub fn is_complete(&self) -> bool {
        // A watch is never finished. It enumerated nothing, so its total is
        // zero, and by the arithmetic below every listen journal would be
        // complete the moment it was created, offering no resume and inviting a
        // retention sweep to take it. What is true instead is that another
        // sitting can always be appended.
        if self.kind() == ScanKind::Listen {
            return false;
        }

        self.settled()
            .is_some_and(|settled| settled >= self.manifest.total_targets)
    }

    /// Which phase this journal records.
    ///
    /// A sweep and a port scan are counted in different units, so a caller
    /// reporting progress or offering to continue one has to know which it is
    /// looking at.
    pub fn kind(&self) -> ScanKind {
        self.manifest.kind()
    }

    /// How many targets are settled, or `None` where the cursor could not be
    /// read.
    ///
    /// [`Checkpoint::settled_count`], which counts a position the list names
    /// that a watermark has already passed once, by the watermark, as
    /// [`Cursor::from_checkpoint`](super::cursor::Cursor::from_checkpoint)
    /// does. `Checkpoint::read` deliberately does not drop such entries, so
    /// without that filter a damaged list would be counted twice here and
    /// nowhere else. That inflates the total, and
    /// [`is_complete`](Self::is_complete) can tip to `true` on the inflation,
    /// which is what a retention sweep deletes on. Two readers of one file
    /// should not disagree about the scan it describes.
    pub fn settled(&self) -> Option<u128> {
        self.checkpoint
            .as_ref()
            .map(|checkpoint| u128::from(checkpoint.settled_count()))
    }
}

/// Creates the directory journals are kept in, and gives it to the user who
/// invoked an elevated run.
///
/// Call this before [`Journal::create`]. It exists because `create_dir_all`
/// alone is not enough, and the gap stays invisible until somebody runs a scan
/// that does not need root.
///
/// # The defect this closes
///
/// Every raw strategy needs root, so the first run on a machine is almost always
/// under `sudo`, and [`paths::root`](super::paths::root) resolves the invoking
/// user's home so the journals land where that user will look. What they land in
/// is two directories created by a root process, and claiming each scan's own
/// directory does not give away the two above it.
///
/// Left to root, the result is silent and total. Every later run that does not
/// need root finds a directory it cannot write to, says `not recording this
/// run: Permission denied`, and carries on. A listening phase needs no
/// privileges, so it would never record anything on a machine where a scan had
/// run first.
///
/// # It repairs as well as creates
///
/// The two directories are claimed whether or not this call created them.
/// Creating and claiming alone would fix new installations and leave every
/// existing one broken, since the directory may already be there, made by a run
/// that left it to root. Claiming an already-correct directory is a `chown` to
/// the owner it already has.
///
/// Above those two, what this call created is given too: a first run on a
/// machine with no `~/.local/state` creates it and `~/.local` on the way, and
/// left to root they are directories no other program of the user's can keep
/// its state in. One that was already there may predate this engine by years
/// and belongs to whoever made it, unless that is root, which is how an
/// elevated run that gave nothing back leaves it; see
/// the `ownership` module for why that one is given back.
///
/// Nothing is given outside the invoking user's home, wherever the root is:
/// a state root kept through `sudo` that points elsewhere stays root's, as a
/// settings directory there does.
///
/// Best effort, like every other claim here: a directory that cannot be given
/// away is not worth failing a scan over, and an unprivileged run has no
/// invoking user to give it to and no need of one.
pub fn prepare_root(root: &Path) -> std::io::Result<()> {
    let own = super::paths::root().as_deref() == Some(root);
    #[cfg(unix)]
    let home = super::ownership::invoking().map(|user| user.home.as_path());
    #[cfg(not(unix))]
    let home = None;
    prepare_root_with(root, own, home, |path, hand| match hand {
        Hand::Give => claim_directory_for_invoking_user(path),
        Hand::Reclaim => super::ownership::reclaim(path),
    })
}

/// What [`prepare_root`] does with one directory on the way to a root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Hand {
    /// Gives it to the invoking user, whoever owns it now.
    Give,
    /// Gives it back only if root owns it.
    Reclaim,
}

/// [`prepare_root`] with the claim passed in, so a test can see what would be
/// given away without an elevated process to give it.
///
/// `own` says `root` is this crate's own location rather than one a caller
/// named, which is the one case where what lies above it is known to be
/// somewhere this engine may have created on the invoking user's behalf. A
/// caller that named its own location is telling us where to write, not
/// handing us everything above it.
///
/// `home` is the invoking user's, `None` for a run on nobody else's behalf;
/// the directories between it and the root are the ones a repair looks at.
fn prepare_root_with(
    root: &Path,
    own: bool,
    home: Option<&Path>,
    mut claim: impl FnMut(&Path, Hand),
) -> std::io::Result<()> {
    let created = super::ownership::create_missing(root, None)?;

    if own && let Some(above) = root.parent() {
        // Outermost first, as they were created.
        let mut between: Vec<&Path> = above
            .ancestors()
            .skip(1)
            .take_while(|directory| {
                home.is_some_and(|home| *directory != home && directory.starts_with(home))
            })
            .collect();
        between.reverse();
        for directory in between {
            let hand = if created.iter().any(|made| made == directory) {
                Hand::Give
            } else {
                Hand::Reclaim
            };
            claim(directory, hand);
        }
        claim(above, Hand::Give);
    }
    claim(root, Hand::Give);

    Ok(())
}

/// Every journal under `root`, newest first.
///
/// A journal that cannot be read is passed over rather than failing the
/// listing, since one unreadable journal must not hide the rest, and said to
/// be, with why: a listing short of a record with nothing to say so reads as
/// a record that is not there, and the reason, a link planted where its
/// manifest should be above all, is what its owner has to act on. A link
/// standing in the root is passed over in the same words, being no journal:
/// every journal is a directory this crate made. A directory holding no
/// manifest at all is passed over in silence, as one a scan starting now has
/// yet to write it into.
///
/// `Ok(vec![])` for a root that does not exist yet.
pub fn list(root: &Path) -> Result<Vec<Entry>, JournalError> {
    let held = match kinds(root) {
        Ok(held) => held,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };

    let mut found = Vec::new();
    for (name, kind) in held {
        let directory = root.join(&name);
        match kind {
            Kind::Directory => {}
            Kind::Link => {
                crate::warn!(
                    "{} not listed: a link, not a journal (not followed)",
                    name.to_string_lossy()
                );
                continue;
            }
            Kind::Other => continue,
        }
        let manifest = match read_manifest(&directory) {
            Ok(manifest) => manifest,
            Err(JournalError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => continue,
            // The system's words alone: the line already says whose they are.
            Err(JournalError::Io(e)) => {
                crate::warn!("{} not listed: {e}", name.to_string_lossy());
                continue;
            }
            Err(e) => {
                crate::warn!("{} not listed: {e}", name.to_string_lossy());
                continue;
            }
        };
        found.push(Entry {
            // `Err` here is a cursor that exists and could not be read, which
            // `Entry::checkpoint` records as `None` rather than as a scan that
            // settled nothing. A journal that never checkpointed comes back as
            // a fresh cursor from `read_checkpoint` itself.
            checkpoint: read_checkpoint(&directory).ok(),
            lock: super::lock::inspect(&directory.join(LOCK)),
            manifest,
            directory,
        });
    }

    found.sort_by_key(|entry| std::cmp::Reverse(entry.manifest.created_at));
    Ok(found)
}

/// The scan at `directory`, as the report it would have produced.
///
/// A journal holds everything a report is made of: what each sitting covered and
/// under which settings, and every host it found. So a scan that is over can be
/// read back and rendered as it was when it ended. That is what this returns, the
/// hosts and the phases in the order they ran and the engine
/// version taken from the manifest rather than from this build, so a scan run
/// by an older engine still says so.
///
/// Read without the lock, like [`list`], so it is safe to call on a scan that is
/// still running. What comes back is then a report of everything written down so
/// far, which is a checkpoint behind the live one.
///
/// A journal missing its findings or its phases reads as a scan that recorded
/// none, rather than as a failure: a sitting can end before its first
/// checkpoint, and a report of nothing is the truthful account of that.
pub fn report(directory: &Path) -> Result<ScanReport, JournalError> {
    let manifest = read_manifest(directory)?;

    Ok(ScanReport::recorded(
        manifest.engine_version,
        read_phases(directory)?,
        read_findings(directory)?,
    ))
}

/// How a phase is named in a refusal. Prose rather than the wire name, since
/// this reaches a person.
fn phase_name(kind: ScanKind) -> &'static str {
    match kind {
        ScanKind::Discovery => "host-discovery sweep",
        ScanKind::PortScan => "port scan",
        // A watch enumerates nothing, so its journal has no cursor and resuming
        // one appends a sitting rather than skipping settled work. It is still a
        // journal this build writes, so this name reaches a person.
        ScanKind::Listen => "listening phase",
    }
}

/// Deletes the journal at `directory`.
///
/// Refuses one a live scan is writing. A caller pruning by age should read
/// [`Entry::lock`] and skip what is held rather than relying on this, so a
/// sweep reports what it left alone.
///
/// The refusal is a check, not an exclusion. The lock is inspected and then
/// the directory is removed, and a scan that takes the lock between the two has
/// its journal deleted under it: it runs on with open descriptors, appending to
/// unlinked inodes, and nothing it writes lands anywhere. Reading [`Entry::lock`]
/// first, as above, is the same check raced one step earlier rather than a way
/// out of it. The window is one lock taken against one directory removal and both
/// parties are the same user's own processes, so this is documented rather than
/// closed. Closing it wants the lock held across the removal, which is a protocol
/// change belonging to `lock` rather than here.
pub fn remove(directory: &Path) -> Result<(), OpenError> {
    let state = super::lock::inspect(&directory.join(LOCK));
    if !state.is_resumable() {
        return Err(OpenError::Locked(LockRefused::Held(state)));
    }

    remove_directory(directory).map_err(JournalError::from)?;
    Ok(())
}

/// One line of the record [`Journal::record_finished`] keeps: the hosts one
/// sitting finished every pass over.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct FinishedRecord {
    hosts: Vec<String>,
}

/// Reads back what a journal's earlier sittings found.
///
/// Records are folded together, each as a later account of the host than the
/// ones before it, so a host written once when it answered and again when its
/// ports were classified comes back whole, with the round trips its last
/// record held; see [`Host::merge_later_account`].
///
/// Two records are the same host when they share any address rather than when
/// their primary addresses match. Local discovery promotes a host's primary
/// address when a better one turns up, such as a link-local giving way to a
/// global, so the same machine is written under one address and then another.
/// Keyed on the primary alone it would come back as two hosts that were never
/// two.
///
/// An address is the one [`ScopedIp::scoped`] makes of it with the record's
/// zone, so a link-local carries its interface and two machines answering to
/// `fe80::1` on two links stay two hosts. That is the identity the report keys
/// its hosts by and the one a diff pairs them by, so a job read back holds what
/// its live report held. A record that names no zone joins only others that
/// name none, as in pairing.
///
/// A missing file is no findings rather than a failure, since a journal can be
/// read before its first host is written.
fn read_findings(directory: &Path) -> Result<Vec<Host>, JournalError> {
    let file = match open_to_read(&directory.join(HOSTS)) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };

    let mut reader = match crate::journal::format::Reader::open(std::io::BufReader::new(file)) {
        Ok(reader) => reader,
        // A findings file with no header was never opened for writing, which
        // is a journal that stopped before it found anything.
        Err(JournalError::NotAJournal) => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };

    // Slots rather than a map: a record can join two hosts that were separate
    // until it arrived, and the one it merges into keeps its slot while the
    // other empties.
    let mut hosts: Vec<Option<Host>> = Vec::new();
    let mut slot_of: std::collections::BTreeMap<ScopedIp, usize> =
        std::collections::BTreeMap::new();

    while let Some(record) = reader.read::<HostRecord>()? {
        let host = Host::from(&record);

        let mut matched: Vec<usize> = scoped_ips(&host)
            .filter_map(|ip| slot_of.get(&ip).copied())
            .collect();
        matched.sort_unstable();
        matched.dedup();

        let slot = match matched.split_first() {
            Some((&keep, absorb)) => {
                // Every host this record has an address in common with is the
                // same machine, so they fold into one another as well.
                for &other in absorb {
                    if let Some(other) = hosts[other].take() {
                        merge_into(&mut hosts, keep, other, Host::merge);
                    }
                }
                merge_into(&mut hosts, keep, host, Host::merge_later_account);
                keep
            }
            None => {
                hosts.push(Some(host));
                hosts.len() - 1
            }
        };

        let Some(settled) = hosts[slot].as_ref() else {
            continue;
        };
        for ip in scoped_ips(settled) {
            slot_of.insert(ip, slot);
        }
    }

    Ok(hosts.into_iter().flatten().collect())
}

/// Every address of `host`, each carrying the host's zone where the address
/// needs one to name a machine.
fn scoped_ips(host: &Host) -> impl Iterator<Item = ScopedIp> + '_ {
    host.ips().iter().map(|ip| match host.zone() {
        Some(zone) => ScopedIp::scoped(*ip, zone.clone()),
        None => ScopedIp::unscoped(*ip),
    })
}

/// Folds `host` into the one at `slot` by `fold`, or puts it there if the
/// slot is empty.
///
/// A record folds in as a later account of what the slot holds, since the
/// file is appended in the order its records were written; see
/// [`Host::merge_later_account`]. Two slots a record shows to be one machine
/// fold as any two accounts of a host do.
fn merge_into(hosts: &mut [Option<Host>], slot: usize, host: Host, fold: fn(&mut Host, Host)) {
    match hosts[slot].as_mut() {
        Some(existing) => fold(existing, host),
        None => hosts[slot] = Some(host),
    }
}

/// How long the findings file in `directory` is, measured on the file it
/// opens to read rather than asked of the name: nothing here asks a
/// journal's names anything by path. A file not there yet is no length.
fn findings_length(directory: &Path) -> Result<u64, JournalError> {
    match open_to_read(&directory.join(HOSTS)) {
        Ok(file) => Ok(file.metadata()?.len()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
        Err(e) => Err(e.into()),
    }
}

/// Reads back what a journal's earlier sittings did, oldest first.
fn read_phases(directory: &Path) -> Result<Vec<ScanPhase>, JournalError> {
    let file = match open_to_read(&directory.join(PHASES)) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };

    let mut reader = match crate::journal::format::Reader::open(std::io::BufReader::new(file)) {
        Ok(reader) => reader,
        Err(JournalError::NotAJournal) => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };

    let mut phases = Vec::new();
    while let Some(record) = reader.read::<PhaseRecord>()? {
        phases.push(ScanPhase::from(&record));
    }

    // Sittings that never ended. A phase already appended is one a sitting
    // stopped between the append and the removal, and is read once.
    for standing in standing_phases(directory) {
        let recorded = phases.iter().any(|phase| {
            phase.kind() == standing.kind() && phase.started_at() == standing.started_at()
        });
        if !recorded {
            phases.push(standing);
        }
    }
    // Oldest first, as the appended ones already are: a sitting that never
    // ended ran before whatever was appended after it.
    phases.sort_by_key(ScanPhase::started_at);
    Ok(phases)
}

/// Where the sitting holding `lock` writes its phases as they stand: a name
/// ordered by when it started, so reading them in name order is reading them
/// in the order they ran.
fn sitting_file(directory: &Path, lock: &Lock) -> PathBuf {
    let started = lock
        .record()
        .started_at
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    directory.join(format!("{SITTING}{started:020}.jsonl"))
}

/// The phases of every sitting in `directory` that never ended, oldest first.
///
/// A standing record is written whole by rename, so one that cannot be read
/// is not a torn write but something else at the name, a link among them, and
/// is passed over rather than failing a journal whose own files read.
fn standing_phases(directory: &Path) -> Vec<ScanPhase> {
    let Ok(held) = names(directory) else {
        return Vec::new();
    };
    let mut files: Vec<PathBuf> = held
        .into_iter()
        .filter(|name| {
            name.to_str()
                .is_some_and(|name| name.starts_with(SITTING) && name.ends_with(".jsonl"))
        })
        .map(|name| directory.join(name))
        .collect();
    files.sort();

    let mut phases = Vec::new();
    for path in files {
        let Ok(file) = open_to_read(&path) else {
            continue;
        };
        let Ok(mut reader) = crate::journal::format::Reader::open(std::io::BufReader::new(file))
        else {
            continue;
        };
        while let Ok(Some(record)) = reader.read::<PhaseRecord>() {
            phases.push(ScanPhase::from(&record));
        }
    }
    phases
}

/// Reads back the detection-run tapes a journal holds, for offline replay.
///
/// A missing file is no runs rather than a failure, the same as a journal read
/// before any detection ran.
pub fn read_detections(directory: &Path) -> Result<Vec<DetectionRunRecord>, JournalError> {
    let file = match open_to_read(&directory.join(DETECTIONS)) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };

    let mut reader = match crate::journal::format::Reader::open(std::io::BufReader::new(file)) {
        Ok(reader) => reader,
        Err(JournalError::NotAJournal) => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };

    let mut runs = Vec::new();
    while let Some(line) = reader.read::<DetectionLine>()? {
        runs.extend(line.into_runs());
    }
    Ok(runs)
}

/// Opens a findings file to add to it, making it whole first.
///
/// [`format::Writer::append`](super::format::Writer::append) states a
/// precondition, "a caller appending has already opened the file for reading
/// and validated it", and this is what establishes it for all three append
/// sites, which would otherwise open by path and write. It is one function
/// rather than three checks because both failures below are the same defect
/// from two ends: the append path cannot see what it is appending
/// to, and `O_APPEND` guarantees it lands after whatever is there.
///
/// A torn tail stops being discardable the moment anything follows it. The
/// format promises that a torn final line is discarded rather than an error,
/// and [`format::Reader`](super::format::Reader) keeps that promise only while
/// the torn line is *last*. A resumed sitting appends directly after the torn
/// bytes; the tear becomes the prefix of the next record's line, that line is
/// newline-terminated, and a JSON prefix followed by a JSON object is
/// corruption by the reader's own rule. From then on the file can be neither
/// read nor resumed, and the hours in front of the tear are stranded, the exact
/// loss the torn-tail policy exists to prevent, arriving at the first append
/// after the crash it was written to survive. Truncating to the last newline
/// discards precisely what the reader would have discarded, one record inside
/// the replay interval, and nothing else.
///
/// A file with no header is mended or refused, never blessed.
/// [`Journal::open_findings`] creates the file and writes its header as two
/// steps, so a process killed between them leaves a zero-length file. The resume
/// path reads that as a journal that found nothing, which is true at that moment;
/// appending into it then writes records under no header, every later read is
/// `NotAJournal` mapped back to no findings, and the whole sitting is invisible
/// while the cursor advances and reports the ground covered. Empty is mended,
/// because there is nothing in the file to be mistaken for a record and
/// completing the header is what the interrupted call was doing. Non-empty
/// without a header is somebody else's file standing at this name, and naming it
/// in an error is the only honest answer: prepending a header would turn its
/// lines into records this engine claims to have written.
fn open_for_append(path: &Path) -> Result<fs::File, JournalError> {
    mend(path)?;
    Ok(append_existing(path)?)
}

/// Gives a findings file a header if it has none and no torn tail if it has one.
///
/// The header is checked through [`format::Reader::open`](super::format::Reader)
/// rather than by matching bytes here, so the rule this enforces is the same rule
/// the reader applies, the version refusal included, which an append to a journal
/// from a newer build should meet here as well as at the resume.
///
/// Order matters: the header is validated *before* anything is truncated, so a
/// stranger's file at this name is refused intact rather than edited and then
/// refused.
fn mend(path: &Path) -> Result<(), JournalError> {
    use std::io::{Read, Seek, SeekFrom};

    let mut file = open_existing(path)?;
    let length = file.metadata()?.len();

    // The header write that did not finish, which is the whole of the window
    // between `open_findings`' create and its write.
    if length == 0 {
        super::format::Writer::create(&mut file)?.flush()?;
        return Ok(());
    }

    super::format::Reader::open(std::io::BufReader::new(&file))?;

    file.seek(SeekFrom::End(-1))?;
    let mut last = [0u8; 1];
    file.read_exact(&mut last)?;
    if last[0] == b'\n' {
        return Ok(());
    }

    let keep = last_whole_line(&mut file, length)?;
    file.set_len(keep)?;

    // No whole line anywhere, so the header line is the torn one. It parsed, so
    // the file is this engine's and there is simply nothing in it to keep;
    // writing the header again is the same repair the empty case makes.
    if keep == 0 {
        file.seek(SeekFrom::Start(0))?;
        super::format::Writer::create(&mut file)?.flush()?;
    }

    Ok(())
}

/// The offset just past the file's last newline: where a whole record last ended.
///
/// Read backwards a window at a time rather than by reading the file. This runs
/// on every append, and a findings file grows with a scan's duration rather
/// than with what it found, the reason [`Journal::compact`] exists, so a scan
/// of any length would be paying for its own history on every checkpoint.
fn last_whole_line(file: &mut fs::File, length: u64) -> Result<u64, JournalError> {
    use std::io::{Read, Seek, SeekFrom};

    /// Comfortably more than a record, so the answer is almost always one read.
    ///
    /// A `u64`, so the arithmetic below stays in the width the file's length is
    /// measured in. A `usize` against `end as usize` would truncate wherever
    /// `usize` is narrower: a length that is an exact multiple of 4 GiB has low
    /// bits of zero, so the window would be empty, `start == end`, and the loop
    /// would stop advancing — a hang holding the journal's lock, on a 32-bit
    /// target, on the file this engine grows with a scan's duration.
    const WINDOW: u64 = 8 * 1024;

    let mut end = length;
    while end > 0 {
        let size = WINDOW.min(end);
        let start = end - size;

        file.seek(SeekFrom::Start(start))?;
        // Lossless: `size` is bounded by `WINDOW`, so the one cast that remains
        // cannot be the one that truncates.
        let mut window = vec![0u8; size as usize];
        file.read_exact(&mut window)?;

        if let Some(at) = window.iter().rposition(|byte| *byte == b'\n') {
            return Ok(start + at as u64 + 1);
        }

        end = start;
    }

    Ok(0)
}

/// The options a journal's job runs under, or `None` where none were recorded.
fn read_options(directory: &Path) -> Result<Option<JobOptions>, JournalError> {
    let text = match read_bounded(&directory.join(OPTIONS), "a journal's options") {
        Ok(text) => text,
        Err(JournalError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    Ok(Some(
        serde_json::from_str(&text).map_err(JournalError::json)?,
    ))
}

/// Reads a journal's manifest, refusing one written by a newer format than this
/// build understands rather than reading it approximately.
fn read_manifest(directory: &Path) -> Result<JournalManifest, JournalError> {
    let text = read_bounded(&directory.join(MANIFEST), "a journal manifest")?;
    let manifest: JournalManifest = serde_json::from_str(&text).map_err(JournalError::json)?;

    if manifest.journal_version > super::JOURNAL_VERSION {
        return Err(JournalError::VersionTooNew {
            found: manifest.journal_version,
            understood: super::JOURNAL_VERSION,
        });
    }

    Ok(manifest)
}

/// Reads how far a scan got, which is where a resume starts.
fn read_checkpoint(directory: &Path) -> Result<Checkpoint, JournalError> {
    match Checkpoint::read(&directory.join(CURSOR)) {
        Ok(checkpoint) => Ok(checkpoint),
        // A journal that stopped before its first checkpoint has settled
        // nothing, which is a fresh cursor rather than a failure.
        Err(JournalError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {
            Ok(Checkpoint::default())
        }
        Err(e) => Err(e),
    }
}

/// The characters an id is written in: Crockford base32, which has no letters a
/// reader can mistake for digits.
const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";

/// How many characters an id is.
///
/// Sixteen: the millisecond the scan started, then randomness. Shorter than a
/// ULID's twenty-six because an id is printed in a listing and typed at a
/// prompt, and a line of them should fit a terminal beside what it describes.
///
/// All ten characters of width come off the random half and none off the clock.
/// Timing to the millisecond is what makes ids sort into the order the scans ran
/// in, and two scans a fifth of a second apart are the pair a reader most needs
/// told apart. What is left is thirty-two bits for scans that started in the same
/// millisecond, and a collision is answered by
/// minting another id rather than by overwriting anything, so the cost of one is
/// a retry rather than a lost journal. See [`claim_directory`].
const ID_CHARS: usize = 16;

/// Milliseconds, as a ULID counts them, reaching the year 10 889.
const ID_TIME_BITS: u32 = 48;

/// A sortable id: the millisecond the scan started, then randomness, in
/// Crockford base32.
///
/// Sorts by creation time as text, which is what lets a listing be ordered
/// without reading every manifest. Written out rather than pulled in: it is
/// twenty lines against a dependency, and the crate already declines a crate per
/// format for the same reason.
fn mint_id() -> String {
    let millis = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map_or(0, |since| since.as_millis())
        & ((1u128 << ID_TIME_BITS) - 1);

    let random_bits = ID_CHARS as u32 * 5 - ID_TIME_BITS;
    let entropy = u128::from(rand::random::<u64>()) & ((1u128 << random_bits) - 1);
    let mut value = (millis << random_bits) | entropy;

    let mut out = [b'0'; ID_CHARS];
    for slot in out.iter_mut().rev() {
        *slot = ALPHABET[(value & 0x1F) as usize];
        value >>= 5;
    }

    // Every byte came from `ALPHABET`, which is ASCII.
    String::from_utf8(out.to_vec()).expect("base32 alphabet is ASCII")
}

/// Takes a directory under `root` that nothing else holds, and its id.
///
/// `create_dir` rather than `create_dir_all`. The second succeeds on a directory
/// that is already there, so two scans that minted the same id would share one,
/// the later overwriting the earlier's manifest and, once the earlier had
/// finished and released its lock, its findings too.
///
/// A collision is answered by minting another id rather than by failing. Ids
/// carry enough randomness that this should never run twice, and a scan is not
/// worth abandoning over a coincidence.
fn claim_directory(root: &Path) -> Result<(String, PathBuf), JournalError> {
    /// Enough that exhausting them means something other than chance is wrong: a
    /// root that is not a directory, or one nothing may write to.
    const ATTEMPTS: usize = 8;

    for _ in 0..ATTEMPTS {
        let id = mint_id();
        let directory = root.join(&id);

        match create_private_directory(&directory) {
            Ok(()) => {
                claim_directory_for_invoking_user(&directory);
                return Ok((id, directory));
            }
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(e.into()),
        }
    }

    Err(std::io::Error::new(
        std::io::ErrorKind::AlreadyExists,
        "could not find an unused id for this scan",
    )
    .into())
}

/// Reads a whole journal file, refusing one past
/// [`MAX_READ_BYTES`](super::format::MAX_READ_BYTES).
///
/// `fs::read_to_string` with a ceiling, and the ceiling applied through `take`
/// before the read rather than to the length afterwards. The two files read
/// whole, the manifest and the cursor, are the journal's own, in a directory
/// this crate documents as belonging to a user while the process reading them
/// is usually root; see [`MAX_READ_BYTES`](super::format::MAX_READ_BYTES) for
/// what that is and is not worth. Opened as every journal file is read, so a
/// link at the name is refused rather than followed; see [`open_to_read`].
pub(super) fn read_bounded(path: &Path, what: &str) -> Result<String, JournalError> {
    use std::io::Read;

    let mut text = String::new();
    let read = open_to_read(path)?
        .take(super::format::MAX_READ_BYTES + 1)
        .read_to_string(&mut text)?;

    if read as u64 > super::format::MAX_READ_BYTES {
        return Err(super::format::too_large(what));
    }

    Ok(text)
}

/// Writes a whole file at a journal's own mode and ownership. For the files
/// written once rather than a record at a time.
///
/// Staged and renamed, like [`Checkpoint::write_atomically`] and
/// [`Journal::compact`], so the name either holds the whole file or does not
/// exist. The manifest is its only caller. It is the file every other read
/// begins with, so written by truncate-and-write it would be the one torn file
/// no reader has a policy for: the torn-tail bargain covers records, and
/// [`read_manifest`] answers a partial document with a parse error that
/// [`list`] absorbs as a journal that is not there.
fn write_private(path: &Path, bytes: &[u8]) -> Result<(), JournalError> {
    use std::io::Write;

    replace(path, &path.with_extension("tmp"), |mut file| {
        file.write_all(bytes)
    })?;
    Ok(())
}

/// How long journals are kept.
///
/// A journal holds the addresses an engagement was pointed at, so it should not
/// accumulate in a state directory nobody looks at. It is also evidence, so it
/// should not vanish at a moment nobody chose. The defaults below take the
/// second more seriously than the first.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Retention {
    /// How long a finished journal is kept, or `None` to keep it indefinitely.
    pub completed_for: Option<Duration>,
    /// How long an unfinished one is kept, or `None` to keep it indefinitely.
    pub incomplete_for: Option<Duration>,
    /// The most journals to keep, or `None` for no cap.
    ///
    /// Applied after the ages above, and it removes finished journals before
    /// unfinished ones: a cap exists to bound a directory, and an unfinished
    /// journal is the one thing there somebody may still want.
    pub keep_at_most: Option<usize>,
}

impl Default for Retention {
    /// A month for finished journals, indefinitely for unfinished ones, and a
    /// cap of two hundred.
    ///
    /// The asymmetry is the point. A finished scan has a report; its journal is
    /// a duplicate that ages out. An unfinished one is the only copy of work
    /// somebody may still mean to continue, so nothing but the cap removes it.
    fn default() -> Self {
        Self {
            completed_for: Some(Duration::from_secs(30 * 24 * 60 * 60)),
            incomplete_for: None,
            keep_at_most: Some(200),
        }
    }
}

impl Retention {
    /// Removes nothing. For a caller who prunes on their own terms.
    pub fn keep_everything() -> Self {
        Self {
            completed_for: None,
            incomplete_for: None,
            keep_at_most: None,
        }
    }

    /// Which of `entries` this policy would remove, newest-first as [`list`]
    /// yields them.
    ///
    /// Pure, and separate from [`prune`] for the reason
    /// [`lock::classify`](crate::journal::lock::classify) is: the interesting
    /// cases are a directory full of journals of different ages and states, and
    /// arranging those on a real filesystem to test the policy would test the
    /// filesystem.
    ///
    /// A journal something is writing is never selected, whatever its age.
    pub fn expired(&self, entries: &[Entry], now: SystemTime) -> Vec<usize> {
        let age_of = |entry: &Entry| {
            now.duration_since(entry.manifest.created_at)
                .unwrap_or_default()
        };

        let mut removing: Vec<usize> = entries
            .iter()
            .enumerate()
            .filter(|(_, entry)| entry.lock.is_resumable())
            .filter(|(_, entry)| {
                let limit = if entry.is_complete() {
                    self.completed_for
                } else {
                    self.incomplete_for
                };
                limit.is_some_and(|limit| age_of(entry) > limit)
            })
            .map(|(index, _)| index)
            .collect();

        let Some(cap) = self.keep_at_most else {
            return removing;
        };

        // What the ages left behind, oldest last, since `list` is newest first.
        let mut surviving: Vec<usize> = (0..entries.len())
            .filter(|index| !removing.contains(index))
            .collect();

        // Ordered by how much a journal is worth keeping, most first: unfinished
        // before finished, and newer before older. The cap is then applied by
        // dropping from the end, so what goes is the oldest duplicate of work
        // that already has a report.
        surviving.sort_by_key(|&index| {
            let entry = &entries[index];
            (
                entry.is_complete(),
                std::cmp::Reverse(entry.manifest.created_at),
            )
        });

        while surviving.len() > cap {
            let Some(index) = surviving.pop() else { break };
            if entries[index].lock.is_resumable() {
                removing.push(index);
            }
        }

        removing.sort_unstable();
        removing
    }
}

/// What a prune did, and what it left alone.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Pruned {
    /// The journals removed, by id.
    pub removed: Vec<String>,
    /// The journals a policy selected but that could not be removed, each with
    /// why.
    ///
    /// Reported rather than swallowed: a sweep that quietly leaves things behind
    /// is one nobody can tell has stopped working.
    pub held: Vec<Held>,
}

/// A journal a prune could not remove.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Held {
    /// Which journal.
    pub id: String,
    /// Why it is still there.
    pub reason: String,
}

impl Held {
    /// The journal `id`, kept for `reason`.
    pub fn new(id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            reason: reason.into(),
        }
    }
}

/// Removes the journals under `root` that `retention` no longer keeps.
///
/// Journals a scan is writing are never removed, and are not reported as held
/// either: they were never selected. What reaches [`Pruned::held`] is a journal
/// the policy chose and the filesystem refused.
pub fn prune(root: &Path, retention: &Retention) -> Result<Pruned, JournalError> {
    let entries = list(root)?;
    let mut pruned = Pruned::default();

    for index in retention.expired(&entries, SystemTime::now()) {
        let entry = &entries[index];
        match remove(&entry.directory) {
            Ok(()) => pruned.removed.push(entry.manifest.id.clone()),
            Err(error) => pruned.held.push(Held {
                id: entry.manifest.id.clone(),
                reason: error.to_string(),
            }),
        }
    }

    Ok(pruned)
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::journal::settle::Outcome;
    // The ticker lives in `scanner`, which is above this module, and two tests
    // here reach up for it: what they assert is what ends up in the *journal*
    // when a scan is checkpointed, so the fixtures they need are these.
    use crate::model::exclusion::Exclusions;
    use crate::model::ip::set::IpSet;
    use crate::model::port::PortSet;
    use crate::model::target::{TargetMap, TargetSet};
    use crate::model::technique::TcpScanTechnique;
    use crate::scanner::checkpoint::spawn_checkpoints;

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("zond-store-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("scratch root");
        dir
    }

    fn plan(range: &str, ports: &str) -> TargetMap {
        let mut map = TargetMap::new();
        map.add_unit(TargetSet::new(
            range.parse::<IpSet>().expect("a range"),
            ports.parse::<PortSet>().expect("ports"),
        ));
        map
    }

    fn ports(map: &TargetMap) -> Plan {
        Plan::port_scan(map, &Exclusions::none(), TcpScanTechnique::Syn)
    }

    fn begin(root: &Path, map: &TargetMap) -> Journal {
        Journal::create(root, &ports(map), Privilege::Raw, "test").expect("creates")
    }

    /// A port phase that stood in for a liveness pass, naming `silent` the
    /// addresses it asked on every port and heard nothing from.
    fn standing_in(silent: &str) -> ScanPhase {
        use crate::config::ZondConfig;
        use crate::model::ip::range::IpRange;
        use crate::report::{LivenessSkip, PhaseParts, ScanSettings, TargetScope};

        let silent: IpSet = silent.parse().expect("a range");
        ScanPhase::from_parts(PhaseParts {
            open: false,
            attachments: Vec::new(),
            kind: ScanKind::PortScan,
            started_at: SystemTime::UNIX_EPOCH,
            elapsed: Duration::from_secs(1),
            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(),
            refused_by_route: Vec::new(),
            timed_out: Vec::new(),
            icmp_rate_limited: Vec::new(),
            reached_by_connect: Vec::new(),
            undecided: Vec::new(),
            liveness_skipped: Some(LivenessSkip::PortsNoDearer),
            silent: silent.v4().iter().copied().map(IpRange::V4).collect(),
            stopped: None,
            passes_cut: Vec::new(),
            unreached: 0,
            unheard_probes: 0,
            probes: Vec::new(),
            origin: None,
        })
    }

    /// A record a port scanner files at an address before anything is heard
    /// from it, as a checkpoint writes it down mid-sitting.
    fn unheard(address: &str) -> Host {
        use crate::model::port::{Port, PortState, Protocol};

        let mut host = Host::new(address.parse().expect("an address"));
        host.add_port(Port::new(80, Protocol::Tcp, PortState::Filtered));
        host
    }

    /// A host that answered.
    fn heard(address: &str) -> Host {
        let mut host = Host::new(address.parse().expect("an address"));
        host.set_status(crate::model::host::HostStatus::Up);
        host
    }

    /// **A record an earlier sitting heard nothing from is not restored.** The
    /// findings file can hold one, written before the phase decided the
    /// address was silent, and a report drops it by that phase. Restored, it
    /// would stand in the resumed sitting's live hosts as one the report does
    /// not list, and be written back out with them.
    #[test]
    fn a_record_an_earlier_sitting_heard_nothing_from_is_not_restored() {
        let root = scratch("unheard-restore");
        let map = plan("192.0.2.1-192.0.2.8", "80");

        let directory = {
            let mut journal = begin(&root, &map);
            journal
                .record_hosts(&[heard("192.0.2.1"), unheard("192.0.2.5")])
                .expect("records");
            journal
                .record_phases(&[standing_in("192.0.2.5")])
                .expect("records");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        let restored: Vec<_> = journal.restored().iter().map(Host::primary_ip).collect();

        assert_eq!(
            restored,
            ["192.0.2.1".parse::<std::net::IpAddr>().expect("an address")]
        );
        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// **A sitting that heard nothing from an address leaves no record of it on
    /// disk.** A checkpoint writes a scanner's record of the address down
    /// before the phase has decided it is silent, and the phase forgets it
    /// only in memory; the findings file is the job's record, and a dead
    /// record there is one every reader has to know to drop.
    #[tokio::test]
    async fn a_sitting_that_heard_nothing_from_an_address_leaves_no_record_of_it() {
        let root = scratch("unheard-close");
        let map = plan("192.0.2.1-192.0.2.8", "80");
        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        // Written down mid-sitting, and forgotten by the phase since: the live
        // store holds only the host that answered.
        journal
            .record_hosts(&[heard("192.0.2.1"), unheard("192.0.2.5")])
            .expect("records");
        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        ctx.restore_hosts(&[heard("192.0.2.1")]);

        spawn_checkpoints(journal, ctx.progress())
            .finish(&[standing_in("192.0.2.5")])
            .await;

        let file = fs::read_to_string(directory.join(HOSTS)).expect("reads");
        assert!(
            !file.contains("192.0.2.5"),
            "a record of the silent address is still on disk:\n{file}"
        );
        let kept: Vec<_> = read_findings(&directory)
            .expect("reads")
            .iter()
            .map(Host::primary_ip)
            .collect();
        assert_eq!(
            kept,
            ["192.0.2.1".parse::<std::net::IpAddr>().expect("an address")]
        );

        std::fs::remove_dir_all(&root).ok();
    }

    /// **A sitting killed before its port phase decides what it heard nothing
    /// from leaves each record it had yet to decide to the next sitting, and
    /// out of the job's report.** A phase standing in for a liveness pass
    /// decides its unanswered records only at its end, and a target it asked
    /// is settled as the answer, or the silence, is stored. Kept off the disk
    /// until a verdict a killed sitting never reaches, a record's ports would
    /// be settled with nothing on file to show for them: on no host if the
    /// address answers the next sitting, and counted by no sitting if it
    /// never does. Its probes at an address it had heard nothing from on
    /// every target are its own to count, being decided.
    #[tokio::test]
    async fn a_sitting_killed_before_its_verdicts_leaves_its_undecided_records_to_the_next() {
        use crate::config::ZondConfig;
        use crate::journal::settle::Outcome;
        use crate::model::port::{Port, PortState, Protocol};
        use crate::model::target::TargetIndex;
        use crate::report::{LivenessSkip, TargetScope};
        use crate::scanner::recorder::PhaseRecorder;

        let root = scratch("unheard-killed");
        let map = plan("192.0.2.1-192.0.2.8", "80,443");
        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        let address = |address: &str| address.parse::<std::net::IpAddr>().expect("an address");
        let position = |at: &str, port: u16| {
            map.iter()
                .position(|target| target.ip == address(at) && target.port == port)
                .expect("a planned target") as u64
        };

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        ctx.number_targets(TargetIndex::of(&map));
        let _phase = PhaseRecorder::start(
            ScanKind::PortScan,
            Privilege::Raw,
            TargetScope::from_ip_set(
                &mut "192.0.2.1-192.0.2.8".parse().expect("a range"),
                &Exclusions::none(),
            ),
            &ZondConfig::default(),
        )
        .skipping_liveness(LivenessSkip::PortsNoDearer)
        .opening_in(&ctx);
        ctx.await_verdicts();
        // A host; an address asked on one of its ports so far; and one asked
        // on both, heard from on neither.
        ctx.update_host(address("192.0.2.1"), |host| {
            host.set_status(crate::model::host::HostStatus::Up);
        });
        ctx.write_host(address("192.0.2.5"), |host| {
            *host = unheard("192.0.2.5");
            true
        });
        ctx.record_outcome(Outcome::Exhausted {
            position: position("192.0.2.5", 80),
        });
        ctx.write_host(address("192.0.2.6"), |host| {
            *host = unheard("192.0.2.6");
            host.add_port(Port::new(443, Protocol::Tcp, PortState::Filtered));
            true
        });
        for port in [80, 443] {
            ctx.record_outcome(Outcome::Exhausted {
                position: position("192.0.2.6", port),
            });
        }

        // One checkpoint lands, and the process dies before the phase ends.
        let mut ticker = spawn_checkpoints(journal, ctx.progress());
        ticker.checkpointed().await;
        ticker.kill().await;

        let hosts = report(&directory)
            .expect("reads")
            .hosts()
            .map(Host::primary_ip)
            .collect::<Vec<_>>();
        assert_eq!(
            hosts,
            [address("192.0.2.1")],
            "the report lists an undecided address"
        );

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        let restored: Vec<_> = journal
            .restored()
            .iter()
            .map(|host| (host.primary_ip(), host.ports().count()))
            .collect();
        assert_eq!(
            restored,
            [(address("192.0.2.1"), 0), (address("192.0.2.5"), 1)],
            "the undecided record, and only it beside the host, is the next sitting's"
        );
        let unheard: u128 = journal
            .earlier_phases()
            .iter()
            .map(ScanPhase::unheard_probes)
            .sum();
        assert_eq!(unheard, 2, "the silent address's probes went uncounted");
        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// **A sitting killed before its verdicts still names the addresses it
    /// had heard nothing from on every target.** Their targets are settled on
    /// disk, so a resume asks nothing more of them and restores no record of
    /// them; named only by the phase's end, which a killed sitting never
    /// reaches, they would be in no list of the job.
    #[tokio::test]
    async fn a_sitting_killed_before_its_verdicts_still_names_what_it_heard_nothing_from() {
        use crate::config::ZondConfig;
        use crate::journal::settle::Outcome;
        use crate::model::target::TargetIndex;
        use crate::report::TargetScope;
        use crate::scanner::recorder::PhaseRecorder;

        let root = scratch("unheard-named");
        let map = plan("192.0.2.1-192.0.2.8", "80");
        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        ctx.number_targets(TargetIndex::of(&map));
        let _phase = PhaseRecorder::start(
            ScanKind::PortScan,
            Privilege::Raw,
            TargetScope::from_ip_set(&mut IpSet::new(), &Exclusions::none()),
            &ZondConfig::default(),
        )
        .opening_in(&ctx);
        ctx.await_verdicts();
        // Asked and settled silent, and asked with its answer still owed.
        for address in ["192.0.2.5", "192.0.2.6"] {
            ctx.write_host(
                address.parse::<std::net::IpAddr>().expect("an address"),
                |host| {
                    *host = unheard(address);
                    true
                },
            );
        }
        ctx.record_outcome(Outcome::Exhausted { position: 4 });

        let mut ticker = spawn_checkpoints(journal, ctx.progress());
        ticker.checkpointed().await;
        ticker.kill().await;

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        let silent: Vec<_> = journal
            .earlier_phases()
            .iter()
            .flat_map(|phase| phase.silent().iter().copied())
            .collect();
        let named: IpSet = "192.0.2.5".parse().expect("an address");
        assert_eq!(
            silent,
            named
                .v4()
                .iter()
                .copied()
                .map(crate::model::ip::range::IpRange::V4)
                .collect::<Vec<_>>(),
            "the settled silent address is named, and only it"
        );
        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// **A record awaiting its verdict is in the findings once the phase keeps
    /// it.** An address the phase neither forgot nor heard from, one no route
    /// led to, is a finding when the sitting ends.
    #[tokio::test]
    async fn a_record_held_for_its_verdict_is_written_once_the_phase_keeps_it() {
        let root = scratch("unheard-kept");
        let map = plan("192.0.2.1-192.0.2.8", "80");
        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        ctx.await_verdicts();
        ctx.write_host(
            "192.0.2.5".parse::<std::net::IpAddr>().expect("an address"),
            |host| {
                *host = unheard("192.0.2.5");
                true
            },
        );
        let mut ticker = spawn_checkpoints(journal, ctx.progress());
        ticker.checkpointed().await;
        ctx.verdicts_reached();
        ticker.finish(&[]).await;

        let kept: Vec<_> = read_findings(&directory)
            .expect("reads")
            .iter()
            .map(Host::primary_ip)
            .collect();
        assert_eq!(
            kept,
            ["192.0.2.5".parse::<std::net::IpAddr>().expect("an address")]
        );
        std::fs::remove_dir_all(&root).ok();
    }

    /// The whole cycle: begin a scan, settle part of it, come back and continue
    /// from exactly where it stopped.
    #[test]
    fn a_scan_resumes_from_where_it_stopped() {
        let root = scratch("resume");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let directory = {
            let mut journal = begin(&root, &map);
            let settlements = Settlements::default();
            for position in [0, 1, 2, 5] {
                settlements.record(Outcome::Answered { position });
            }
            journal.checkpoint(&settlements).expect("checkpoints");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (_journal, checkpoint) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        assert_eq!(checkpoint.watermark, 3);
        let remaining: Vec<_> = checkpoint.remaining(map.iter()).collect();
        assert_eq!(remaining.len(), 4, "eight targets, four settled");
    }

    /// A job's options are written by its first sitting and read back by
    /// every later one, and nothing a later sitting runs under replaces them.
    ///
    /// Replaced, a sitting that changed its pace would become the record of
    /// what the job asked, and the one after it would restore the change.
    #[test]
    fn a_jobs_options_are_written_by_its_first_sitting_and_kept() {
        use crate::config::ZondConfig;

        let root = scratch("options");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");
        let first = ZondConfig {
            assume_up: true,
            traceroute: true,
            ..ZondConfig::default()
        };

        let directory = {
            let mut journal = begin(&root, &map);
            assert!(journal.options().is_none(), "no sitting has started");
            journal
                .record_options(JobOptions::of(&first))
                .expect("records");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (mut journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        assert_eq!(journal.options(), Some(&JobOptions::of(&first)));

        journal
            .record_options(JobOptions::of(&ZondConfig::default()))
            .expect("a second record is a no-op");
        journal.close().expect("closes");
        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        assert_eq!(journal.options(), Some(&JobOptions::of(&first)));
    }

    /// A journal an earlier sitting ran against without recording its options
    /// is continued without any: this sitting's are not what that one ran
    /// under, and recording them would say they were.
    #[test]
    fn a_journal_older_than_its_options_is_left_without_them() {
        use crate::config::ZondConfig;

        let root = scratch("options-older");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let directory = {
            let mut journal = begin(&root, &map);
            let settlements = Settlements::default();
            settlements.record(Outcome::Answered { position: 0 });
            journal.checkpoint(&settlements).expect("checkpoints");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (mut journal, checkpoint) = Journal::resume(&directory, &ports(&map), Privilege::Raw)
            .expect("an older journal resumes");
        assert_eq!(checkpoint.watermark, 1);
        journal
            .record_options(JobOptions::of(&ZondConfig::default()))
            .expect("records nothing");
        assert!(journal.options().is_none());
        assert!(!directory.join(OPTIONS).exists());
    }

    /// A plan edited between sittings renumbers every position past the edit, so
    /// the resume is refused rather than scanning the wrong targets.
    #[test]
    fn a_changed_plan_is_refused() {
        let root = scratch("changed-plan");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let widened = plan("192.0.2.1-192.0.2.9", "80,443");
        let refused = Journal::resume(&directory, &ports(&widened), Privilege::Raw)
            .expect_err("the plan moved");

        assert!(matches!(refused, OpenError::PlanChanged(_)), "{refused:?}");
    }

    /// A journal being written must not be resumed underneath its writer.
    /// A journal whose lock names a live process that stopped checkpointing
    /// is refused as it stands and can be taken over when asked.
    ///
    /// A crashed scan's number reissued to another process leaves exactly
    /// this, and the refusal says to take the journal over. With nothing to
    /// take it over by, the job could be continued only by deleting the lock
    /// by hand. This process stands in for the reissued number.
    #[test]
    fn a_journal_whose_lock_went_stale_can_be_taken_over() {
        let root = scratch("stale-lock");
        let map = plan("192.0.2.1", "80");
        let directory = {
            let journal = begin(&root, &map);
            journal.directory().to_path_buf()
        };
        let stale = super::super::lock::LockRecord {
            pid: std::process::id(),
            boot: super::super::lock::boot_identity(),
            started_at: SystemTime::now() - Duration::from_secs(3_600),
            heartbeat: SystemTime::now() - Duration::from_secs(600),
        };
        fs::write(
            directory.join(LOCK),
            serde_json::to_string(&stale).expect("json"),
        )
        .expect("writes");

        assert!(matches!(
            Journal::reopen(&directory, Privilege::Raw),
            Err(OpenError::Locked(LockRefused::Held(
                LockState::Stale { .. }
            )))
        ));
        let (journal, _, _) =
            Journal::take_over(&directory, Privilege::Raw).expect("takes the journal over");
        journal.close().expect("closes");

        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn a_live_journal_is_not_resumable() {
        let root = scratch("live");
        let map = plan("192.0.2.1", "80");

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let refused =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect_err("it is held");
        assert!(matches!(refused, OpenError::Locked(_)), "{refused:?}");

        // And released, it opens.
        journal.close().expect("closes");
        Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("now free");
    }

    /// Listing reports progress and liveness without taking the lock, so it
    /// never disturbs a running scan.
    #[test]
    fn listing_describes_journals_without_locking_them() {
        let root = scratch("list");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let mut journal = begin(&root, &map);
        let settlements = Settlements::default();
        for position in 0..4 {
            settlements.record(Outcome::Answered { position });
        }
        journal.checkpoint(&settlements).expect("checkpoints");

        let listed = list(&root).expect("lists");
        assert_eq!(listed.len(), 1);

        let entry = &listed[0];
        assert_eq!(entry.manifest.total_targets, 8);
        assert_eq!(entry.settled(), Some(4));
        assert!(!entry.is_complete());
        assert!(
            matches!(entry.lock, LockState::Held { .. }),
            "the scan is still running: {:?}",
            entry.lock
        );

        // Still writable, so the listing took nothing.
        journal
            .checkpoint(&settlements)
            .expect("still holds its lock");
    }

    /// A journal that covered its plan reads as complete.
    #[test]
    fn a_finished_journal_reads_as_complete() {
        let root = scratch("complete");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let mut journal = begin(&root, &map);
        let settlements = Settlements::default();
        for position in 0..8 {
            settlements.record(Outcome::Answered { position });
        }
        journal.checkpoint(&settlements).expect("checkpoints");
        journal.close().expect("closes");

        let listed = list(&root).expect("lists");
        assert!(listed[0].is_complete());
        assert_eq!(listed[0].settled(), Some(8));
    }

    /// A journal that stopped before its first checkpoint has settled nothing,
    /// which is a fresh cursor rather than an unreadable journal.
    #[test]
    fn a_journal_with_no_checkpoint_resumes_from_the_beginning() {
        let root = scratch("no-checkpoint");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let (_journal, checkpoint) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        assert_eq!(checkpoint, Checkpoint::default());
        assert_eq!(checkpoint.remaining(map.iter()).count(), 8);
    }

    /// Ids sort by creation time as text, which is what makes a listing orderable
    /// without reading every manifest.
    ///
    /// Timing to the millisecond is what buys that. Minted a fifth of a second
    /// apart, which is to say one after another, they still sort into the order
    /// they were made, and that is the pair a reader most needs told apart.
    #[test]
    fn ids_are_sortable_and_distinct() {
        let mut ids: Vec<String> = (0..64).map(|_| mint_id()).collect();

        assert!(ids.iter().all(|id| id.len() == ID_CHARS));
        let distinct: std::collections::BTreeSet<&String> = ids.iter().collect();
        assert_eq!(distinct.len(), ids.len(), "ids collided");

        let sorted = {
            ids.sort();
            ids.clone()
        };
        assert_eq!(ids, sorted, "ids minted in one burst lost their order");

        // And across milliseconds, where the clock rather than chance decides.
        let first = mint_id();
        std::thread::sleep(std::time::Duration::from_millis(3));
        let second = mint_id();
        assert!(first < second, "{first} should sort before {second}");
    }

    /// A listing skips what it cannot read rather than failing, so one damaged
    /// journal never hides the rest.
    #[test]
    fn an_unreadable_journal_does_not_hide_the_others() {
        let root = scratch("damaged");
        let map = plan("192.0.2.1", "80");
        begin(&root, &map).close().expect("closes");

        let damaged = root.join("01JUNREADABLEJUNREADABLE00");
        fs::create_dir_all(&damaged).expect("directory");
        fs::write(damaged.join(MANIFEST), "{not json").expect("writes");

        let listed = list(&root).expect("lists");
        assert_eq!(listed.len(), 1, "the readable one is still there");
    }

    /// Pruning removes a journal nobody is writing, and refuses one somebody is.
    #[test]
    fn pruning_refuses_a_journal_that_is_being_written() {
        let root = scratch("prune");
        let map = plan("192.0.2.1", "80");

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        assert!(matches!(remove(&directory), Err(OpenError::Locked(_))));

        journal.close().expect("closes");
        remove(&directory).expect("removes a free journal");
        assert!(list(&root).expect("lists").is_empty());
    }

    /// The ticker writes a final checkpoint and releases the lock, so a scan
    /// that finishes between two ticks still records what it did.
    #[tokio::test]
    async fn the_checkpoint_task_writes_a_final_cursor_and_releases() {
        let root = scratch("ticker");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");
        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        for position in 0..5 {
            ctx.record_outcome(Outcome::Answered { position });
        }

        // Finishes immediately, well inside one tick.
        spawn_checkpoints(journal, ctx.progress()).finish(&[]).await;

        let checkpoint = Checkpoint::read(&directory.join(CURSOR)).expect("a cursor was written");
        assert_eq!(checkpoint.watermark, 5);
        assert_eq!(
            super::super::lock::inspect(&directory.join(LOCK)),
            LockState::Free,
            "the lock outlived the scan and was then released"
        );
    }

    /// A resumed sitting that settles nothing must still write a cursor covering
    /// the first sitting's work.
    ///
    /// The failure this guards is silent: forget to seed the live cursor from
    /// the resume point and the second sitting's checkpoint erases the first's
    /// progress, so a third would re-scan everything while reporting success.
    #[test]
    fn a_resumed_cursor_carries_the_earlier_sittings_progress() {
        let root = scratch("carry-forward");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let directory = {
            let mut journal = begin(&root, &map);
            let settlements = Settlements::default();
            for position in 0..3 {
                settlements.record(Outcome::Answered { position });
            }
            journal.checkpoint(&settlements).expect("checkpoints");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (mut journal, checkpoint) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        // Seeded from the resume point, exactly as a scan does.
        let settlements = Settlements::resuming(&checkpoint);
        journal
            .checkpoint(&settlements)
            .expect("checkpoints having settled nothing new");
        journal.close().expect("closes");

        let carried = Checkpoint::read(&directory.join(CURSOR)).expect("reads");
        assert_eq!(
            carried.watermark, 3,
            "the second sitting must not roll the cursor back"
        );
    }

    /// Findings survive the journal, which is the point of writing them down.
    #[test]
    fn what_a_sitting_found_comes_back() {
        use crate::model::host::HostStatus;
        use crate::model::port::{Port, PortState, Protocol};

        let root = scratch("findings");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let directory = {
            let mut journal = begin(&root, &map);

            let mut host = Host::new("192.0.2.1".parse().expect("an address"));
            host.set_status(HostStatus::Up);
            host.set_hostname(Some("router.example".to_string()));
            host.add_port(Port::new(80, Protocol::Tcp, PortState::Open));

            journal.record_hosts(&[host]).expect("records");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        let restored = journal.restored();
        assert_eq!(restored.len(), 1);
        assert_eq!(restored[0].hostname(), Some("router.example"));
        assert_eq!(restored[0].port_count(), 1);
        assert!(restored[0].is_alive());
    }

    /// A detection run's tape survives being written to the journal and read back,
    /// so a recorded scan can be replayed offline. Its own file, so it never
    /// disturbs the hosts a resume reads.
    #[test]
    fn detection_run_tapes_survive_a_journal_round_trip() {
        use crate::detect::compute::{CapTape, CapTapeRecord, DetectionRunRecord, SpeakExchange};
        use crate::model::finding::{DetectionId, Version};
        use crate::record::DetectionIdRecord;

        let root = scratch("detections");
        let map = plan("192.0.2.1", "80");

        let tape = CapTape {
            speaks: vec![SpeakExchange {
                sent: b"PING\r\n".to_vec(),
                reply: Ok(b"+PONG\r\n".to_vec()),
            }],
            nows: vec![7],
            ..CapTape::default()
        };
        let detection = DetectionId::new("redis-unauth", Version::new(1, 0, 0), "abc").unwrap();
        let run = DetectionRunRecord {
            host: "192.0.2.1".to_string(),
            host_name: None,
            port: 80,
            protocol: "tcp".to_string(),
            detection: DetectionIdRecord::from(&detection),
            responses: vec!["+PONG\r\n".to_string()],
            tape: CapTapeRecord::from(&tape),
        };

        let directory = {
            let mut journal = begin(&root, &map);
            journal
                .record_detections(std::slice::from_ref(&run))
                .expect("records the run");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let read = read_detections(&directory).expect("reads the runs back");
        assert_eq!(
            read,
            vec![run],
            "a detection run did not survive the journal"
        );
        assert_eq!(
            read[0].tape.rebuild(),
            tape,
            "the tape did not rebuild to what was recorded"
        );
    }

    /// A run over `port` of 192.0.2.1 by the passive detection `id`, which
    /// read `responses` and spoke to nothing.
    fn passive_run(
        id: &str,
        port: u16,
        responses: &[&str],
    ) -> crate::detect::compute::DetectionRunRecord {
        use crate::detect::compute::{CapTape, CapTapeRecord, DetectionRunRecord};
        use crate::model::finding::{DetectionId, Version};
        use crate::record::DetectionIdRecord;

        let detection = DetectionId::new(id, Version::new(1, 0, 0), "abc").expect("an id");
        DetectionRunRecord {
            host: "192.0.2.1".to_string(),
            host_name: None,
            port,
            protocol: "tcp".to_string(),
            detection: DetectionIdRecord::from(&detection),
            responses: responses
                .iter()
                .map(|response| response.to_string())
                .collect(),
            tape: CapTapeRecord::from(&CapTape::default()),
        }
    }

    /// Every passive detection that matches a service reads the same
    /// responses the scan gathered at its port, a dozen of them for any HTTP
    /// port. Written with each run, those responses, up to kilobytes apiece,
    /// would fill the file a dozen times over, so a port's are written once
    /// and every run over it reads them back.
    #[test]
    fn a_ports_responses_are_written_once_however_many_runs_read_them() {
        let root = scratch("tapes-once");
        let map = plan("192.0.2.1", "80");
        let page = "HTTP/1.1 200 OK\r\nServer: a-distinctive-server\r\n\r\n";

        let runs: Vec<_> = (0..13)
            .map(|n| passive_run(&format!("http-{n}"), 80, &[page]))
            .chain([passive_run("ssh-banner", 22, &["SSH-2.0-x\r\n"])])
            .collect();

        let directory = {
            let mut journal = begin(&root, &map);
            journal.record_detections(&runs).expect("records the runs");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let written = fs::read_to_string(directory.join(DETECTIONS)).expect("reads the file");
        assert_eq!(written.matches("a-distinctive-server").count(), 1);
        assert_eq!(read_detections(&directory).expect("reads back"), runs);
    }

    /// A journal written one run to a line, each with its own copy of what it
    /// read, is still replayed: its runs come back beside those written a port
    /// to a line.
    #[test]
    fn tapes_written_one_run_to_a_line_still_read_back() {
        use std::io::Write;

        let root = scratch("tapes-legacy");
        let map = plan("192.0.2.1", "80");
        let grouped = passive_run("http-title", 80, &["HTTP/1.1 200 OK\r\n\r\n"]);
        let alone = passive_run("ssh-banner", 22, &["SSH-2.0-x\r\n"]);

        let directory = {
            let mut journal = begin(&root, &map);
            journal
                .record_detections(std::slice::from_ref(&grouped))
                .expect("records the run");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };
        let mut file = fs::OpenOptions::new()
            .append(true)
            .open(directory.join(DETECTIONS))
            .expect("opens the file");
        let line = serde_json::to_string(&alone).expect("serialises");
        writeln!(file, "{line}").expect("appends a run on its own");

        assert_eq!(
            read_detections(&directory).expect("reads back"),
            [grouped, alone]
        );
    }

    /// A host written more than once comes back whole rather than as its last
    /// record alone: the scan that found it and the scan that classified its
    /// ports both wrote, and both readings matter.
    #[test]
    fn repeated_records_for_one_host_are_folded_together() {
        use crate::model::host::HostStatus;
        use crate::model::port::{Port, PortState, Protocol};

        let root = scratch("folded");
        let map = plan("192.0.2.1", "80");
        let ip: std::net::IpAddr = "192.0.2.1".parse().expect("an address");

        let directory = {
            let mut journal = begin(&root, &map);

            let mut found = Host::new(ip);
            found.set_status(HostStatus::Up);
            journal.record_hosts(&[found]).expect("the host answered");

            let mut classified = Host::new(ip);
            classified.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
            journal
                .record_hosts(&[classified])
                .expect("and then its ports");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        let restored = journal.restored();
        assert_eq!(restored.len(), 1, "one address is one host");
        assert!(restored[0].is_alive(), "the first record's status survived");
        assert_eq!(restored[0].port_count(), 1, "the second record's port too");
    }

    /// `fe80::1` is a different machine on every link, so two gateways found
    /// under that one number on two interfaces are two hosts. Folded by the
    /// bare address, a resume would restore one of them and a report read back
    /// from the journal would list fewer hosts than the scan found, where the
    /// live report and a diff of it keep both.
    #[test]
    fn link_locals_on_two_interfaces_come_back_as_two_hosts() {
        use crate::model::host::HostStatus;
        use crate::model::ip::scoped::Zone;

        let root = scratch("zones");
        let map = plan("192.0.2.1", "80");
        let ip: std::net::IpAddr = "fe80::1".parse().expect("an address");

        let directory = {
            let mut journal = begin(&root, &map);
            let hosts: Vec<Host> = [Zone::new(4, "en0"), Zone::new(9, "en7")]
                .into_iter()
                .map(|zone| {
                    let mut host = Host::new(ip);
                    host.set_status(HostStatus::Up);
                    host.set_zone(zone);
                    host
                })
                .collect();
            journal.record_hosts(&hosts).expect("records both");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        assert_eq!(report(&directory).expect("reads").host_count(), 2);

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        let mut zones: Vec<&str> = journal
            .restored()
            .iter()
            .filter_map(|host| host.zone().map(Zone::name))
            .collect();
        zones.sort_unstable();
        assert_eq!(zones, ["en0", "en7"], "each restored on its own link");
    }

    /// A journal that stopped before it found anything reads as no findings, not
    /// as a failure.
    #[test]
    fn a_journal_with_no_findings_restores_nothing() {
        let root = scratch("no-findings");
        let map = plan("192.0.2.1", "80");

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");
        assert!(journal.restored().is_empty());
    }

    /// The whole of `zond journal report`: a finished scan comes back out of
    /// its journal as the report it produced. Everything the end of a run
    /// prints is drawn from the hosts and the phases, so if either fails to
    /// survive the round trip the record is a summary rather than the scan.
    #[test]
    fn a_journal_reads_back_as_the_report_its_scan_produced() {
        let root = scratch("replay");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");
        let original = crate::export::fixture::report();

        let directory = {
            let mut journal = begin(&root, &map);
            let hosts: Vec<Host> = original.hosts().cloned().collect();
            journal.record_hosts(&hosts).expect("records hosts");
            journal
                .record_phases(original.phases())
                .expect("records phases");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let replayed = report(&directory).expect("reads");

        assert_eq!(replayed.host_count(), original.host_count());
        assert_eq!(replayed.phases().len(), original.phases().len());
        assert_eq!(
            replayed.summary().hosts_alive,
            original.summary().hosts_alive
        );
        assert_eq!(replayed.summary().ports_open, original.summary().ports_open);

        // A phase carries what the run covered and how it went, which is what
        // the closing lines of a run are drawn from.
        let (before, after) = (&original.phases()[0], &replayed.phases()[0]);
        assert_eq!(after.kind(), before.kind());
        assert_eq!(after.privilege(), before.privilege());
        assert_eq!(after.failures().len(), before.failures().len());
        assert_eq!(
            replayed.is_partial(),
            original.is_partial(),
            "a scan that left ground uncovered has to still say so"
        );
    }

    /// A report read back names the engine that ran the scan, not the one
    /// reading it. The two differ the moment somebody upgrades, and a record
    /// that quietly restamps itself is a record of the wrong thing.
    #[test]
    fn a_replayed_report_names_the_engine_that_ran_the_scan() {
        let root = scratch("replay-version");
        let map = plan("192.0.2.1", "80");

        let directory = {
            let journal = begin(&root, &map);
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // The manifest as a build before this one would have left it.
        let path = directory.join(MANIFEST);
        let mut manifest: JournalManifest =
            serde_json::from_str(&fs::read_to_string(&path).expect("reads")).expect("parses");
        manifest.engine_version = "0.1.0".to_string();
        fs::write(&path, serde_json::to_vec(&manifest).expect("encodes")).expect("writes");

        let replayed = report(&directory).expect("reads");

        assert_eq!(replayed.engine_version(), "0.1.0");
        assert_ne!(
            replayed.engine_version(),
            crate::report::ENGINE_VERSION,
            "this build's version must not have been stamped over the record's"
        );
    }

    /// A cursor that exists and cannot be read is not a scan that settled
    /// nothing.
    ///
    /// This is what a `sudo` scan leaves behind if its cursor is not handed over
    /// with the rest: a journal in the invoking user's home whose cursor stays
    /// root's. Reported as zero, every finished scan would list as untouched
    /// and offer itself to be continued. Reported as unknown, a reader is told
    /// to go and look.
    #[cfg(unix)]
    #[test]
    fn a_cursor_that_cannot_be_read_is_not_a_scan_that_settled_nothing() {
        use std::os::unix::fs::PermissionsExt;

        let root = scratch("unreadable-cursor");
        let map = plan("192.0.2.1-192.0.2.4", "80");

        let directory = {
            let mut journal = begin(&root, &map);
            let settlements = Settlements::default();
            settlements.record(Outcome::Answered { position: 0 });
            journal.checkpoint(&settlements).expect("checkpoints");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // Readable first, so the difference below is about the permission and
        // not about the file's contents.
        let listed = list(&root).expect("lists");
        assert_eq!(listed[0].settled(), Some(1));

        fs::set_permissions(directory.join(CURSOR), fs::Permissions::from_mode(0o000))
            .expect("removes every permission");

        let listed = list(&root).expect("a journal it cannot read must not hide the rest");
        assert_eq!(listed.len(), 1, "the journal still lists");
        assert_eq!(
            listed[0].settled(),
            None,
            "unreadable is not zero: zero is a claim about the scan"
        );
        assert!(
            !listed[0].is_complete(),
            "and nothing that cannot be read may be called finished"
        );

        // Left readable, so a failure here does not leave a file the next run
        // of this test cannot clean up.
        let _ = fs::set_permissions(directory.join(CURSOR), fs::Permissions::from_mode(0o600));
    }

    /// What a scan learns after its last checkpoint has to reach the file.
    ///
    /// The enrichment passes, meaning OS identification and the echo probe and
    /// traceroute, run at the end of a scan, often after the last timer
    /// checkpoint has drained what changed. If the closing write misses them, a
    /// replayed report is quieter than the run that made it, with a protocol
    /// missing from the evidence or a round trip with no spread. Nothing errors,
    /// so only a test comparing the two would notice.
    #[tokio::test]
    async fn what_a_scan_learns_after_a_checkpoint_still_reaches_the_file() {
        use crate::model::host::{HostStatus, StatusProtocol, StatusReason};

        let root = scratch("late-findings");
        let map = plan("192.0.2.1", "80");
        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let (_session, ctx) = crate::scanner::session::ScanSession::new();
        let mut ticker = spawn_checkpoints(journal, ctx.progress());

        // What the liveness pass found.
        let ip: std::net::IpAddr = "192.0.2.1".parse().expect("an address");
        ctx.update_host(ip, |host| {
            host.set_status(HostStatus::Up);
            host.record_evidence(
                HostStatus::Up,
                StatusReason::new(StatusProtocol::Arp, "answered"),
            );
        });

        // A checkpoint lands, taking that and leaving nothing behind.
        ticker.checkpointed().await;

        // And then the enrichment finds something else, as it does.
        ctx.update_host(ip, |host| {
            host.record_evidence(
                HostStatus::Up,
                StatusReason::new(StatusProtocol::IcmpEcho, "echo answered"),
            );
        });

        ticker.finish(&[]).await;

        let restored = read_findings(&directory).expect("reads");
        assert_eq!(restored.len(), 1, "one host was scanned");

        let protocols: Vec<_> = restored[0]
            .reasons()
            .iter()
            .map(|reason| reason.protocol.clone())
            .collect();
        assert!(
            protocols.contains(&StatusProtocol::IcmpEcho),
            "what the scan learned last was lost: {protocols:?}"
        );
    }

    fn aged(id: &str, created_at: SystemTime, settled: u64, total: u128) -> Entry {
        Entry {
            directory: PathBuf::from(id),
            manifest: JournalManifest {
                links: Vec::new(),
                journal_version: crate::journal::JOURNAL_VERSION,
                id: id.to_string(),
                engine_version: "0.0.0".to_string(),
                created_at,
                kind: crate::record::wire::scan_kind_name(ScanKind::PortScan).to_owned(),
                plan: crate::journal::manifest::PlanFingerprint::of(
                    &ports(&plan("192.0.2.1", "80")),
                    Privilege::Raw,
                ),
                targets: crate::record::PlanRecord::from(&plan("192.0.2.1", "80")),
                technique: TcpScanTechnique::Syn.name().to_owned(),
                sweep: false,
                privilege: Privilege::Raw,
                total_targets: total,
                order_seed: None,
                summary: String::new(),
            },
            checkpoint: Some(Checkpoint {
                watermark: settled,
                settled_above: Vec::new(),
                walked: None,
            }),
            lock: LockState::Free,
        }
    }

    fn ago(seconds: u64) -> SystemTime {
        now() - Duration::from_secs(seconds)
    }

    fn now() -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000)
    }

    /// Finished journals age out; unfinished ones do not, because they are the
    /// only copy of work somebody may still mean to continue.
    #[test]
    fn age_removes_finished_journals_and_keeps_unfinished_ones() {
        let entries = vec![
            aged("finished-old", ago(100), 1, 1),
            aged("unfinished-old", ago(100), 0, 1),
            aged("finished-new", ago(1), 1, 1),
        ];

        let retention = Retention {
            completed_for: Some(Duration::from_secs(50)),
            incomplete_for: None,
            keep_at_most: None,
        };

        assert_eq!(retention.expired(&entries, now()), vec![0]);
    }

    /// A journal something is writing is never selected, however old.
    #[test]
    fn a_live_journal_is_never_pruned() {
        let mut entries = vec![aged("held", ago(10_000), 1, 1)];
        entries[0].lock = LockState::Held {
            pid: 1,
            last_beat: Duration::from_secs(1),
        };

        let retention = Retention {
            completed_for: Some(Duration::from_secs(1)),
            incomplete_for: Some(Duration::from_secs(1)),
            keep_at_most: Some(0),
        };

        assert!(retention.expired(&entries, now()).is_empty());
    }

    /// The cap takes finished journals before unfinished ones, and the oldest
    /// first within each, so a directory is bounded without losing work somebody
    /// has not finished.
    #[test]
    fn the_cap_removes_duplicates_before_unfinished_work() {
        // `list` yields newest first.
        let entries = vec![
            aged("finished-new", ago(1), 1, 1),
            aged("unfinished-mid", ago(2), 0, 1),
            aged("finished-old", ago(3), 1, 1),
        ];

        let retention = Retention {
            completed_for: None,
            incomplete_for: None,
            keep_at_most: Some(2),
        };

        let removed = retention.expired(&entries, now());
        assert_eq!(removed, vec![2], "the older of the two finished ones");

        // Tighter still, and the unfinished one is the last to go.
        let retention = Retention {
            keep_at_most: Some(1),
            ..retention
        };
        let removed = retention.expired(&entries, now());
        assert_eq!(
            removed,
            vec![0, 2],
            "both finished ones, the unfinished kept"
        );
    }

    /// Keeping everything keeps everything.
    #[test]
    fn keeping_everything_removes_nothing() {
        let entries = vec![
            aged("ancient", ago(900_000), 1, 1),
            aged("also-ancient", ago(900_000), 0, 1),
        ];

        assert!(
            Retention::keep_everything()
                .expired(&entries, now())
                .is_empty()
        );
    }

    /// The default keeps an unfinished scan whatever its age, and lets a
    /// finished one go after a month.
    #[test]
    fn the_default_favours_unfinished_work() {
        let two_months = Duration::from_secs(60 * 24 * 60 * 60);
        let created = now() - two_months;

        let entries = vec![
            aged("finished", created, 1, 1),
            aged("unfinished", created, 0, 1),
        ];

        assert_eq!(Retention::default().expired(&entries, now()), vec![0]);
    }

    /// End to end: a prune removes what the policy chose and says which.
    #[test]
    fn pruning_removes_what_the_policy_selected() {
        let root = scratch("retention");
        let map = plan("192.0.2.1", "80");

        // Finished, so the default lets it go once it is old enough.
        let mut journal = begin(&root, &map);
        let settlements = Settlements::default();
        settlements.record(Outcome::Answered { position: 0 });
        journal.checkpoint(&settlements).expect("checkpoints");
        let id = journal.manifest().id.clone();
        journal.close().expect("closes");

        // Nothing is old enough for the default yet.
        let untouched = prune(&root, &Retention::default()).expect("prunes");
        assert!(untouched.removed.is_empty());
        assert_eq!(list(&root).expect("lists").len(), 1);

        // A policy that keeps nothing finished takes it, and names it.
        let swept = prune(
            &root,
            &Retention {
                completed_for: Some(Duration::ZERO),
                ..Retention::default()
            },
        )
        .expect("prunes");

        assert_eq!(swept.removed, vec![id]);
        assert!(swept.held.is_empty());
        assert!(list(&root).expect("lists").is_empty());

        std::fs::remove_dir_all(&root).ok();
    }

    /// A host whose primary address is promoted mid-scan is still one host.
    ///
    /// Local discovery calls `Host::consider_primary_ip` when a better address
    /// turns up, so the same machine can be written once under a link-local
    /// address and again under a global one. Keyed on the primary alone, those
    /// come back as two hosts that were never two.
    #[test]
    fn a_host_written_under_two_addresses_comes_back_as_one() {
        use crate::model::host::HostStatus;

        let root = scratch("promoted");
        let map = plan("192.0.2.1", "80");
        let link_local: std::net::IpAddr = "fe80::1".parse().expect("an address");
        let global: std::net::IpAddr = "2001:db8::1".parse().expect("an address");

        let directory = {
            let mut journal = begin(&root, &map);

            // Found over its link-local address first.
            let mut early = Host::new(link_local);
            early.set_status(HostStatus::Up);
            journal.record_hosts(&[early]).expect("records");

            // Then a global address arrives and takes the primary slot.
            let mut promoted = Host::new(link_local);
            promoted.add_ip(global);
            assert!(
                promoted.consider_primary_ip(global),
                "the global address should lead"
            );
            promoted.set_hostname(Some("router.example".to_string()));
            journal.record_hosts(&[promoted]).expect("records again");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        let restored = journal.restored();
        assert_eq!(
            restored.len(),
            1,
            "one machine, written twice: {:?}",
            restored.iter().map(Host::primary_ip).collect::<Vec<_>>()
        );
        assert!(restored[0].is_alive(), "the first record's status survived");
        assert_eq!(restored[0].hostname(), Some("router.example"));
    }

    /// A journal holds the addresses an engagement was pointed at and what was
    /// found there. Nobody else on the machine has business reading it.
    #[cfg(unix)]
    #[test]
    fn every_file_a_journal_writes_is_private() {
        use std::os::unix::fs::PermissionsExt;

        let root = scratch("modes");
        let map = plan("192.0.2.1", "80");

        let mut journal = begin(&root, &map);
        let settlements = Settlements::default();
        settlements.record(Outcome::Answered { position: 0 });
        journal
            .record(
                &[Host::new("192.0.2.1".parse().expect("an address"))],
                &settlements,
            )
            .expect("records");
        let directory = journal.directory().to_path_buf();

        let mode_of = |path: &Path| {
            fs::metadata(path)
                .unwrap_or_else(|e| panic!("{path:?}: {e}"))
                .permissions()
                .mode()
                & 0o777
        };

        assert_eq!(mode_of(&directory), 0o700, "the directory");
        for name in [MANIFEST, CURSOR, HOSTS, PHASES, LOCK] {
            assert_eq!(mode_of(&directory.join(name)), 0o600, "{name}");
        }

        // And again after a heartbeat, which replaces the lock file.
        journal.checkpoint(&settlements).expect("beats");
        assert_eq!(mode_of(&directory.join(LOCK)), 0o600, "after a heartbeat");

        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// The two files a scan appends to are opened the way every other journal
    /// file is: refusing a link standing where the file should be.
    ///
    /// `file` makes the whole argument for `O_NOFOLLOW` and
    /// `a_link_where_a_journal_file_should_be_is_refused` proves its three
    /// openers honour it, and for a while neither reached here: `record_hosts`
    /// and `record_phases` opened by path. The journal directory belongs to the
    /// *invoking* user by design and the writing process is usually root, so a
    /// link planted under a fixed name inside it is a root process appending an
    /// engagement's addresses to whatever the link points at.
    #[cfg(unix)]
    #[test]
    fn appending_refuses_a_link_where_a_journal_file_should_be() {
        let root = scratch("nofollow");
        let map = plan("192.0.2.1", "80");
        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        let elsewhere = root.join("not-the-journals-to-touch");
        fs::write(&elsewhere, b"untouched").expect("writes");

        for name in [HOSTS, PHASES] {
            fs::remove_file(directory.join(name)).expect("removes");
            std::os::unix::fs::symlink(&elsewhere, directory.join(name)).expect("links");
        }

        let phases = crate::export::fixture::report().phases().to_vec();
        assert!(
            journal
                .record_hosts(&[Host::new("192.0.2.1".parse().expect("an address"))])
                .is_err(),
            "a link was appended to as the findings file"
        );
        assert!(
            journal.record_phases(&phases).is_err(),
            "a link was appended to as the phases file"
        );
        assert_eq!(
            fs::read(&elsewhere).expect("reads"),
            b"untouched",
            "the file behind the link was written through"
        );

        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// A host recorded more than once reads back with the round trips its
    /// last record holds, not with every record's added together.
    ///
    /// Each record carries the host's whole window of round trips as it stood
    /// then, so a later one repeats what an earlier one held. Folded in as
    /// new samples, the repeats count the early round trips twice: a resumed
    /// job's report moved its average while its fastest and slowest, which a
    /// repeat cannot move, stayed where they were.
    #[test]
    fn a_host_recorded_twice_keeps_the_round_trips_its_last_record_holds() {
        use std::time::Duration;

        let root = scratch("latency");
        let mut journal = begin(&root, &plan("192.0.2.1", "80"));
        let mut host = Host::new("192.0.2.1".parse().expect("an address"));
        host.add_rtts([Duration::from_millis(1), Duration::from_millis(2)]);
        journal.record_hosts(&[host.clone()]).expect("records");
        host.add_rtts([Duration::from_millis(6), Duration::from_millis(7)]);
        journal
            .record_hosts(&[host.clone()])
            .expect("records again");
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let read = report(&directory).expect("reads");
        std::fs::remove_dir_all(&root).ok();
        let [restored] = read.hosts().collect::<Vec<_>>()[..] else {
            panic!("one host on record");
        };
        let figures = |host: &Host| (host.min_rtt(), host.average_rtt(), host.max_rtt());
        assert_eq!(figures(restored), figures(&host), "min, average, max");
        assert_eq!(
            restored.telemetry().history().len(),
            host.telemetry().history().len(),
            "round trips held"
        );
    }

    /// **A host written down at every checkpoint reads back as the host it
    /// is, every field of it.** Each record repeats its host's fields as they
    /// stood, so a field folded as though each record brought something new
    /// counts the repeats, as the round trips once did. Held over everything
    /// a record keeps, for the hosts the schema can say the most about, grown
    /// between checkpoints as a scan grows them, with a port changing at each
    /// so its record repeats too.
    #[test]
    fn a_host_recorded_at_every_checkpoint_reads_back_as_the_host_it_is() {
        use crate::model::confidence::Confidence;
        use crate::model::finding::{DetectionClass, DetectionId, Finding, Severity, Version};
        use crate::model::host::{OsEvidence, OsSource};

        let root = scratch("repeated");
        let mut journal = begin(&root, &plan("203.0.113.1-203.0.113.9", "22,80,443,445"));
        let mut hosts: Vec<Host> = crate::export::fixture::report().hosts().cloned().collect();
        for checkpoint in 0..3u64 {
            let finding = Finding::new(
                DetectionId::new(format!("check-{checkpoint}"), Version::new(1, 0, 0), "")
                    .expect("an id"),
                "A check",
                Severity::Low,
                Confidence::Certain,
                DetectionClass::Passive,
            )
            .expect("a finding");
            for host in &mut hosts {
                host.add_rtt(Duration::from_micros(700 + 100 * checkpoint));
                host.record_os_evidence(OsEvidence {
                    source: OsSource::ServiceBanner,
                    family: Some("Linux".to_string()),
                    device: None,
                    vendor: None,
                    product: None,
                    version: None,
                    kernel: None,
                    arch: None,
                    cpe: None,
                    confidence: 0.5,
                    evidence: format!("banner read at checkpoint {checkpoint}"),
                });
                host.add_finding(finding.clone());
                let first = host
                    .ports()
                    .next()
                    .map(|port| (port.number(), port.protocol()));
                if let Some((number, protocol)) = first {
                    host.add_port_finding(number, protocol, finding.clone());
                }
            }
            journal.record_hosts(&hosts).expect("records");
        }
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let mut read = read_findings(&directory).expect("reads");
        std::fs::remove_dir_all(&root).ok();
        read.sort_by_key(Host::primary_ip);
        hosts.sort_by_key(Host::primary_ip);
        let as_recorded = |hosts: &[Host]| {
            hosts
                .iter()
                .map(|host| serde_json::to_value(HostRecord::from(host)).expect("serialises"))
                .collect::<Vec<_>>()
        };
        assert_eq!(as_recorded(&read), as_recorded(&hosts));
    }

    /// **A link standing in a root of journals is not listed as a journal.**
    /// Every journal is a directory this crate made, so a link there is none,
    /// as a link at a journal file's name is none. Looked at as what it
    /// points to, it would list a record somewhere else as one of this
    /// root's, and under `sudo` have root look wherever it leads.
    #[cfg(unix)]
    #[test]
    fn a_link_in_a_root_of_journals_is_not_listed() {
        let root = scratch("listed-link");
        let elsewhere = scratch("listed-link-elsewhere");
        let journal = begin(&elsewhere, &plan("192.0.2.1", "80"));
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");
        std::os::unix::fs::symlink(&directory, root.join("06LINKED00000000")).expect("links");

        let listed = list(&root).expect("lists").len();
        let where_it_is = list(&elsewhere).expect("lists").len();
        std::fs::remove_dir_all(&root).ok();
        std::fs::remove_dir_all(&elsewhere).ok();
        assert_eq!(listed, 0, "the link was listed as a journal");
        assert_eq!(where_it_is, 1, "the journal itself lists");
    }

    /// Reading a journal refuses a link standing where one of its files
    /// should be, and says so, rather than reading what it points to.
    ///
    /// The journal directory is the invoking user's and the process reading
    /// it to resume a scan is usually root, so a link planted at a fixed name
    /// would have root read whatever the user chose: another job's plan
    /// continued as this one's, or a file only root may read taken for a
    /// journal's. No writer here ever leaves a link at those names, so one is
    /// a job that cannot be read, named as such rather than read as damaged.
    #[cfg(unix)]
    #[test]
    fn reading_refuses_a_link_where_a_journal_file_should_be() {
        let root = scratch("read-nofollow");
        let mut ours = begin(&root, &plan("192.0.2.1", "80"));
        ours.record_hosts(&[Host::new("192.0.2.1".parse().expect("an address"))])
            .expect("records");
        ours.write_cursor(&Checkpoint::default())
            .expect("checkpoints");
        let directory = ours.directory().to_path_buf();
        ours.close().expect("closes");

        let mut theirs = begin(&root, &plan("198.51.100.7", "80"));
        theirs
            .record_hosts(&[Host::new("198.51.100.7".parse().expect("an address"))])
            .expect("records");
        theirs
            .write_cursor(&Checkpoint::new(1, []))
            .expect("checkpoints");
        let elsewhere = theirs.directory().to_path_buf();
        theirs.close().expect("closes");
        let text = root.join("not-a-journal-file");
        fs::write(&text, b"somebody else's bytes").expect("writes");

        let refused = |name: &str, error: String| {
            assert!(
                error.contains("is a link"),
                "{name}: refused, but not as a link: {error}"
            );
        };
        for name in [MANIFEST, CURSOR, HOSTS, PHASES] {
            let kept = directory.join(format!("{name}.kept"));
            fs::rename(directory.join(name), &kept).expect("moves aside");
            std::os::unix::fs::symlink(elsewhere.join(name), directory.join(name)).expect("links");

            match Journal::reopen(&directory, Privilege::Raw) {
                Ok(_) => panic!("{name}: resumed through a link"),
                Err(error) => refused(name, error.to_string()),
            }
            if matches!(name, MANIFEST | HOSTS | PHASES) {
                match report(&directory) {
                    Ok(_) => panic!("{name}: reported through a link"),
                    Err(error) => refused(name, error.to_string()),
                }
            }

            fs::remove_file(directory.join(name)).expect("removes the link");
            fs::rename(&kept, directory.join(name)).expect("restores");
        }

        // The files read after a job's start are refused the same way, where
        // what the link reaches would otherwise have read as nothing recorded.
        let journal = begin(&root, &plan("192.0.2.2", "80"));
        for name in [DETECTIONS, FINISHED] {
            std::os::unix::fs::symlink(&text, journal.directory().join(name)).expect("links");
        }
        match read_detections(journal.directory()) {
            Ok(runs) => panic!("detections read through a link: {runs:?}"),
            Err(error) => refused(DETECTIONS, error.to_string()),
        }
        match journal.finished_hosts() {
            Ok(hosts) => panic!("finished hosts read through a link: {hosts:?}"),
            Err(error) => refused(FINISHED, error.to_string()),
        }
        journal.close().expect("closes");

        std::fs::remove_dir_all(&root).ok();
    }

    /// A cursor naming positions the watermark has already passed does not make
    /// the scan look more finished than it is.
    ///
    /// `Checkpoint::read` keeps below-watermark entries on purpose, because the
    /// read is shared and `Cursor::from_checkpoint` is what filters them. This
    /// counted them, so the same file read two ways gave two answers, and the
    /// inflated one is what `is_complete` reads, which is what a retention
    /// sweep deletes on.
    #[test]
    fn a_cursor_repeating_settled_positions_does_not_inflate_the_count() {
        let root = scratch("inflated-cursor");
        let map = plan("192.0.2.1-192.0.2.4", "80,443");

        let directory = {
            let journal = begin(&root, &map);
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // Four of the eight targets settled, and a list that names three of them
        // again. A writer here never produces this; a damaged file does.
        let checkpoint = Checkpoint {
            watermark: 4,
            settled_above: vec![0, 1, 2, 6],
            walked: None,
        };
        checkpoint
            .write_atomically(&directory.join(CURSOR))
            .expect("writes");

        let entry = list(&root)
            .expect("lists")
            .into_iter()
            .next()
            .expect("one journal");

        assert_eq!(
            entry.settled(),
            Some(5),
            "the watermark plus the one position genuinely above it"
        );
        assert!(
            !entry.is_complete(),
            "eight targets, five settled: a retention sweep must not take this"
        );
    }

    /// The failure the torn-tail policy exists to survive, arriving one append
    /// later.
    ///
    /// `format` promises a torn final line is discarded rather than an error,
    /// and its reader keeps that promise only while the tear is *last*. A
    /// resumed sitting appends directly after the torn bytes under `O_APPEND`,
    /// so the tear becomes the prefix of the next record's line, and that line
    /// is newline-terminated, which makes it corruption by the reader's own
    /// rule. Without the mend, every read of the file from that moment fails
    /// with `Malformed`, so the journal can be neither read back nor resumed
    /// again, and everything in front of the tear is stranded.
    ///
    /// `format`'s `a_torn_final_line_ends_the_journal_without_an_error` reads a
    /// tear. This is the sequence that appends past one.
    #[test]
    fn an_append_after_a_torn_tail_leaves_the_journal_readable() {
        let root = scratch("torn-tail-append");
        let map = plan("192.0.2.1-192.0.2.4", "80");
        let first: std::net::IpAddr = "192.0.2.1".parse().expect("an address");
        let second: std::net::IpAddr = "192.0.2.2".parse().expect("an address");

        let directory = {
            let mut journal = begin(&root, &map);
            journal.record_hosts(&[Host::new(first)]).expect("records");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // The crash: a record that reached the file without its newline.
        {
            use std::io::Write;
            let mut file = fs::OpenOptions::new()
                .append(true)
                .open(directory.join(HOSTS))
                .expect("opens");
            file.write_all(br#"{"ip":"192.0.2.9","stat"#)
                .expect("tears");
        }

        let (mut journal, _) = Journal::resume(&directory, &ports(&map), Privilege::Raw)
            .expect("resumes past the tear");
        journal.record_hosts(&[Host::new(second)]).expect("records");
        journal.close().expect("closes");

        let restored = read_findings(&directory).expect("the journal still reads");
        let addresses: Vec<_> = restored.iter().map(Host::primary_ip).collect();
        assert_eq!(
            addresses,
            vec![first, second],
            "the whole record before the tear and the one after it both survive"
        );
    }

    /// The header write that did not land, and the sitting that would otherwise
    /// disappear into the file it leaves.
    ///
    /// `open_findings` creates the file and writes its header as two steps, so a
    /// process killed between them leaves a zero-length file. Appending into that
    /// writes records under no header: every later read is `NotAJournal`, which
    /// the resume path maps back to "found nothing", while the cursor keeps
    /// advancing and reports the ground covered. Silent, and total.
    #[test]
    fn an_append_to_a_findings_file_whose_header_never_landed_mends_it() {
        let root = scratch("headerless-append");
        let map = plan("192.0.2.1", "80");
        let address: std::net::IpAddr = "192.0.2.1".parse().expect("an address");

        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        fs::write(directory.join(HOSTS), b"").expect("empties");

        journal
            .record_hosts(&[Host::new(address)])
            .expect("records");
        journal.close().expect("closes");

        let restored = read_findings(&directory).expect("reads");
        assert_eq!(
            restored.len(),
            1,
            "a record appended under no header is a record nothing reads back"
        );
    }

    /// The other half of that check: a file this engine did not write is refused
    /// rather than given a header.
    ///
    /// Mending an empty file completes an interrupted write of our own. Mending
    /// a file with content in it would be something else, it would turn a
    /// stranger's lines into records this engine claims to have written. The
    /// refusal has to leave the file exactly as it found it, which is why the
    /// header is checked before anything is truncated.
    #[test]
    fn an_append_to_a_file_this_engine_did_not_write_is_refused() {
        let root = scratch("foreign-append");
        let map = plan("192.0.2.1", "80");

        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        // Complete lines, so nothing here is a torn tail, just not a journal.
        let foreign: &[u8] = b"{\"not\":\"a journal\"}\n{\"still\":\"not\"}";
        fs::write(directory.join(HOSTS), foreign).expect("plants");

        assert!(
            journal
                .record_hosts(&[Host::new("192.0.2.1".parse().expect("an address"))])
                .is_err(),
            "a file with no header was appended to"
        );
        assert_eq!(
            fs::read(directory.join(HOSTS)).expect("reads"),
            foreign,
            "the file was edited before it was refused"
        );

        journal.close().expect("closes");
    }

    /// A journal written under an older format reads, and is refused a resume by
    /// name rather than reported as a plan that moved.
    ///
    /// The fingerprint derivation belongs to the format version, so a journal
    /// from an earlier one carries a value this build cannot recompute. Saying
    /// "the plan changed" about it would be false, and it is the one message
    /// that must never be wrong: it is what tells somebody their targets were
    /// edited between two sittings.
    #[test]
    fn a_journal_from_an_older_format_reads_but_does_not_resume() {
        let root = scratch("older-format");
        let map = plan("192.0.2.1-192.0.2.4", "80");

        let directory = {
            let mut journal = begin(&root, &map);
            journal
                .record_hosts(&[Host::new("192.0.2.1".parse().expect("an address"))])
                .expect("records");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // Aged by hand, since no build that wrote the old format is around to do
        // it. Only the manifest's version moves; everything else it says stands.
        let path = directory.join(MANIFEST);
        let mut manifest: JournalManifest =
            serde_json::from_str(&fs::read_to_string(&path).expect("reads")).expect("parses");
        manifest.journal_version = super::super::JOURNAL_VERSION - 1;
        fs::write(&path, serde_json::to_vec(&manifest).expect("encodes")).expect("writes");

        assert_eq!(
            report(&directory).expect("reads back").host_count(),
            1,
            "an older journal still reads as the report its scan produced"
        );
        assert_eq!(
            list(&root).expect("lists").len(),
            1,
            "and still appears in a listing"
        );

        match Journal::resume(&directory, &ports(&map), Privilege::Raw) {
            Err(OpenError::VersionTooOld { found, understood }) => {
                assert_eq!(found, super::super::JOURNAL_VERSION - 1);
                assert_eq!(understood, super::super::JOURNAL_VERSION);
            }
            other => panic!("expected a refusal naming the format, got {other:?}"),
        }

        std::fs::remove_dir_all(&root).ok();
    }

    /// A journal that could not take its lock leaves nothing behind, rather than
    /// a directory that reads as a scan which found nothing.
    #[test]
    fn a_journal_that_cannot_be_locked_leaves_no_directory() {
        let root = scratch("unlockable");
        let map = plan("192.0.2.1", "80");

        // A file where the scan directory would go: the create cannot proceed,
        // and whatever it did get to must be undone.
        let before = list(&root).expect("lists").len();
        assert_eq!(before, 0);

        let journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();

        // Held by this process, so a second journal over the same directory is
        // refused by the path a real contention takes.
        assert!(matches!(
            Journal::resume(&directory, &ports(&map), Privilege::Raw),
            Err(OpenError::Locked(_))
        ));
        assert!(directory.exists(), "the held journal is untouched");

        journal.close().expect("closes");
        std::fs::remove_dir_all(&root).ok();
    }

    /// A host written again carries only the ports that changed, and reads
    /// back whole.
    ///
    /// A host scanned on every port holds tens of thousands of them. Written
    /// whole each checkpoint in which anything about it changed, a journal of
    /// one such host grew by megabytes every few seconds to record one port
    /// opening, and compaction, counted in records, waited for hundreds of
    /// them.
    #[test]
    fn a_host_written_again_carries_only_what_changed_in_it() {
        use crate::model::port::{Port, PortState, Protocol};

        let root = scratch("delta");
        let map = plan("192.0.2.1", "1-400");
        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        let length = || fs::metadata(directory.join(HOSTS)).expect("stats").len();

        let ip: std::net::IpAddr = "192.0.2.1".parse().expect("an address");
        let mut host = Host::new(ip);
        for number in 1..=400 {
            host.add_port(Port::new(number, Protocol::Tcp, PortState::Closed));
        }
        let before = length();
        journal
            .record_hosts(std::slice::from_ref(&host))
            .expect("records");
        let first = length() - before;

        host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
        let before = length();
        journal
            .record_hosts(std::slice::from_ref(&host))
            .expect("records");
        let second = length() - before;

        assert!(
            second * 20 < first,
            "one port opening appended {second} bytes against the host's {first}"
        );
        journal.close().expect("closes");

        let restored = read_findings(&directory).expect("reads");
        assert_eq!(restored.len(), 1);
        assert_eq!(restored[0].port_count(), 400, "every port read back");
        let open: Vec<u16> = restored[0]
            .ports()
            .filter(|port| port.state() == PortState::Open)
            .map(|port| port.number())
            .collect();
        assert_eq!(open, [22], "the change read back over what it changed");
        std::fs::remove_dir_all(&root).ok();
    }

    /// What a record supersedes is counted: the host's own fields of the record
    /// before it, and the earlier record of each port it writes again, and
    /// nothing a first record of a port adds.
    ///
    /// The count is what decides compaction, so one that missed what was
    /// superseded would let the file grow without bound, and one that counted
    /// new findings would rewrite a file with nothing in it to drop.
    #[test]
    fn a_record_counts_what_it_supersedes_and_not_what_it_adds() {
        use crate::model::port::{Port, PortState, Protocol};

        let ip: std::net::IpAddr = "192.0.2.1".parse().expect("an address");
        let mut host = Host::new(ip);
        host.add_port(Port::new(22, Protocol::Tcp, PortState::Closed));
        let mut written = Written::default();

        let (_, first) = written.delta(&host).expect("measures").expect("new");
        let (rest, port) = (
            u64::from(first.rest.length),
            u64::from(first.ports[0].1.length),
        );
        written.update(first);
        assert_eq!(written.superseded, 0, "a first record supersedes nothing");

        host.add_port(Port::new(80, Protocol::Tcp, PortState::Closed));
        let (_, second) = written.delta(&host).expect("measures").expect("a new port");
        assert_eq!(second.ports.len(), 1, "only the new port is written");
        written.update(second);
        assert_eq!(written.superseded, rest, "the host's own fields, again");

        host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
        let (_, third) = written
            .delta(&host)
            .expect("measures")
            .expect("a moved port");
        let rest_again = written.hosts[&host.scoped_ip()]
            .rest
            .map_or(0, |mark| u64::from(mark.length));
        written.update(third);
        assert_eq!(
            written.superseded,
            rest + rest_again + port,
            "and port 22's closed record under its open one"
        );
    }

    /// A compaction that fails leaves no partial copy behind and is not tried
    /// again at the next checkpoint.
    ///
    /// What stops one, usually a disk with no room for a second copy of the
    /// findings, stops the next, and one is due every checkpoint once the file
    /// has outgrown itself. Left behind, the partial copy held whatever room
    /// the disk had; retried, it was written again every few seconds. The
    /// rename is refused here by a directory standing where the findings file
    /// goes, which fails the compaction at its last step.
    #[test]
    fn a_failed_compaction_leaves_nothing_behind_and_waits_before_trying_again() {
        let root = scratch("failed-compaction");
        let map = plan("192.0.2.1", "80");
        let mut journal = begin(&root, &map);
        let directory = journal.directory().to_path_buf();
        let host = Host::new("192.0.2.1".parse().expect("an address"));
        journal
            .record_hosts(std::slice::from_ref(&host))
            .expect("records");

        // As if the file had grown mostly superseded.
        journal.written.superseded = 3 * COMPACT_FLOOR;
        journal.length = 4 * COMPACT_FLOOR;
        assert!(journal.should_compact());

        fs::remove_file(directory.join(HOSTS)).expect("removes the findings");
        fs::create_dir_all(directory.join(HOSTS).join("occupied")).expect("blocks the name");
        assert!(journal.compact(std::slice::from_ref(&host)).is_err());

        assert!(
            !directory.join(HOSTS).with_extension("jsonl-tmp").exists(),
            "the partial copy is left holding the disk's room"
        );
        assert!(
            !journal.should_compact(),
            "a compaction that just failed is due again at once"
        );
        journal.written.superseded += 2 * COMPACT_FLOOR;
        assert!(
            journal.should_compact(),
            "and again once as much is superseded"
        );

        drop(journal);
        std::fs::remove_dir_all(&root).ok();
    }

    /// A findings file is rewritten once what later records superseded in it
    /// outgrows the rest, and not while it is small or merely growing.
    ///
    /// Counted in bytes: a count of records said nothing about either what a
    /// compaction costs or what it recovers, and one record can be a host's
    /// every port. And counted as what was superseded: a file that grew by a
    /// host's every port the first time it was written holds nothing a
    /// rewrite would drop, and rewriting it is the cost this bounds.
    #[test]
    fn a_findings_file_is_compacted_by_what_it_superseded() {
        const MIB: u64 = 1024 * 1024;

        assert!(
            !outgrown(60 * MIB, 0),
            "a file that grew by what the scan found holds nothing to drop"
        );
        assert!(!outgrown(6 * MIB, 3 * MIB), "a small file is left alone");
        assert!(outgrown(9 * MIB, 5 * MIB), "past the floor it is rewritten");
        assert!(
            !outgrown(50 * MIB, 20 * MIB),
            "twenty superseded beside thirty live is not yet worth it"
        );
        assert!(
            outgrown(50 * MIB, 26 * MIB),
            "twenty-six beside twenty-four is"
        );
    }

    /// A long scan appends a host each interval anything about it changes, so
    /// the findings file grows with the scan's duration rather than with what it
    /// found. Compaction bounds it, and must lose nothing doing so.
    #[test]
    fn compaction_bounds_the_findings_file_without_losing_a_host() {
        use crate::model::host::HostStatus;
        use crate::model::port::{Port, PortState, Protocol};

        let root = scratch("compaction");
        let map = plan("192.0.2.1-192.0.2.4", "80");
        let addresses: Vec<std::net::IpAddr> = (1..=4)
            .map(|last| format!("192.0.2.{last}").parse().expect("an address"))
            .collect();

        let directory = {
            let mut journal = begin(&root, &map);

            // Four hosts, rewritten many times over, as a long scan does.
            let mut live: Vec<Host> = addresses.iter().map(|ip| Host::new(*ip)).collect();
            for round in 0..70 {
                for host in &mut live {
                    host.set_status(HostStatus::Up);
                    host.add_port(Port::new(1000 + round, Protocol::Tcp, PortState::Open));
                }
                journal.record_hosts(&live).expect("records");
            }

            journal.compact(&live).expect("compacts");
            assert!(!journal.should_compact(), "a file just written whole");

            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        // The file now holds one record per host.
        let lines = std::fs::read_to_string(directory.join(HOSTS))
            .expect("reads")
            .lines()
            .count();
        assert_eq!(lines, 1 + 4, "a header and one record each");

        // And nothing was lost.
        let (journal, _) =
            Journal::resume(&directory, &ports(&map), Privilege::Raw).expect("resumes");

        let restored = journal.restored();
        assert_eq!(restored.len(), 4);
        for host in restored {
            assert!(host.is_alive());
            assert_eq!(host.port_count(), 70, "every round's port survived");
        }

        std::fs::remove_dir_all(&root).ok();
    }

    /// A scan can be continued knowing nothing but its id.
    ///
    /// The plan comes back as it was written down. Without this a resume has to
    /// be told the targets and ports again, which is both a chore and a trap:
    /// what somebody types the second time is not necessarily what ran the
    /// first.
    #[test]
    fn a_journal_gives_back_the_plan_it_recorded() {
        let root = scratch("reopen");
        let map = plan("192.0.2.1-192.0.2.4", "80,443,u:53");

        let directory = {
            let journal = Journal::create(
                &root,
                &Plan::port_scan(&map, &Exclusions::none(), TcpScanTechnique::Fin),
                Privilege::Raw,
                "test",
            )
            .expect("creates");
            let directory = journal.directory().to_path_buf();
            journal.close().expect("closes");
            directory
        };

        let (journal, _checkpoint, recovered) =
            Journal::reopen(&directory, Privilege::Raw).expect("reopens");

        let recovered = recovered.targets().expect("a port scan's plan");
        assert_eq!(
            recovered.iter().collect::<Vec<_>>(),
            map.iter().collect::<Vec<_>>(),
            "the same targets, in the same order, so positions still mean what they did"
        );
        assert_eq!(journal.manifest().technique(), TcpScanTechnique::Fin);
    }

    /// Continuing a scan under different privileges is refused: the raw and
    /// connect paths answer different questions, and a journal half of each
    /// would be counting two things.
    #[test]
    fn a_journal_will_not_be_continued_under_different_privileges() {
        let root = scratch("reopen-privilege");
        let map = plan("192.0.2.1", "80");

        let journal =
            Journal::create(&root, &ports(&map), Privilege::Raw, "test").expect("creates");
        let directory = journal.directory().to_path_buf();
        journal.close().expect("closes");

        let refused =
            Journal::reopen(&directory, Privilege::Connect).expect_err("privileges differ");
        assert!(matches!(refused, OpenError::PlanChanged(_)), "{refused:?}");
    }

    /// The root is created, which is the half of this call that is not the
    /// chown.
    ///
    /// The chown cannot be exercised here, since it needs a real elevated process
    /// with a real invoking user and is a no-op without one. What this pins is
    /// that the call is the one a caller makes and that it produces a directory
    /// `Journal::create` can then claim inside.
    #[test]
    fn preparing_a_root_creates_the_whole_path_to_it() {
        let root = scratch("prepare-root")
            .join("state")
            .join("zond")
            .join("journals");
        assert!(!root.exists());

        prepare_root(&root).expect("the path is created");
        assert!(root.is_dir());

        // And again on a root that is already there, which is the repair path:
        // it must not fail for finding its own work.
        prepare_root(&root).expect("an existing root is not an error");

        let plan = Plan::listen(vec![crate::model::ip::scoped::Zone::new(3, "en0")]);
        Journal::create(&root, &plan, Privilege::Connect, "listening")
            .expect("a journal is created inside it")
            .close()
            .expect("it closes");
    }

    /// Everything a first run under `sudo` creates on the way to its journals
    /// is given to the user who ran it, not only the two directories at the
    /// end. A user with no `~/.local/state` who ran one scan would otherwise
    /// own neither it nor `~/.local`, and every other program that keeps state
    /// there would find it refused.
    ///
    /// A directory on the way that was already there is given back only if
    /// root owns it, which is how an elevated run that gave nothing back left
    /// it; one somebody else owns belongs to them. The home itself, and
    /// anything above it, is never the run's to give.
    #[test]
    fn preparing_a_root_gives_away_what_it_created_and_repairs_what_root_left() {
        use Hand::{Give, Reclaim};

        let home = scratch("prepare-root-home");
        let root = home.join(".local/state/zond/journals");
        let prepared = |root: &Path, own: bool, home: Option<&Path>| {
            let mut claimed = Vec::new();
            prepare_root_with(root, own, home, |path, hand| {
                claimed.push((path.to_path_buf(), hand));
            })
            .expect("the path is created");
            claimed
        };
        let under = |pairs: &[(&str, Hand)]| -> Vec<(PathBuf, Hand)> {
            pairs
                .iter()
                .map(|(below, hand)| (home.join(below), *hand))
                .collect()
        };

        assert_eq!(
            prepared(&root, true, Some(&home)),
            under(&[
                (".local", Give),
                (".local/state", Give),
                (".local/state/zond", Give),
                (".local/state/zond/journals", Give),
            ]),
            "a directory created for the journal was left to root"
        );

        // With `~/.local/state` already there, it and `~/.local` are looked
        // at for a repair, and the two directories this crate owns are given
        // regardless.
        fs::remove_dir_all(home.join(".local/state/zond")).expect("removes");
        assert_eq!(
            prepared(&root, true, Some(&home)),
            under(&[
                (".local", Reclaim),
                (".local/state", Reclaim),
                (".local/state/zond", Give),
                (".local/state/zond/journals", Give),
            ])
        );

        // A run on nobody else's behalf has no home to repair up to.
        assert_eq!(
            prepared(&root, true, None),
            under(&[
                (".local/state/zond", Give),
                (".local/state/zond/journals", Give)
            ])
        );

        // A location the caller named is where to write, not everything above
        // it: only the root itself is claimed.
        let named = home.join("elsewhere/journals");
        assert_eq!(
            prepared(&named, false, Some(&home)),
            [(named.clone(), Give)]
        );

        let _ = fs::remove_dir_all(&home);
    }

    /// A watch is never finished, so a journal of one always offers a resume and
    /// a retention sweep never takes it as done.
    ///
    /// Read by the arithmetic the other two phases use it would be complete the
    /// moment it was created: it enumerated nothing, so its total is zero, and
    /// zero settled is not fewer than zero.
    #[test]
    fn a_watch_is_never_complete_however_long_it_ran() {
        use crate::model::ip::scoped::Zone;

        let root = scratch("watch-never-complete");
        let plan = Plan::listen(vec![Zone::new(3, "en0")]);
        let journal = Journal::create(&root, &plan, Privilege::Raw, "listening on en0")
            .expect("a journal is created");
        journal.close().expect("it closes");

        let entries = list(&root).expect("the root lists");
        let entry = entries.first().expect("the watch is there");

        assert_eq!(entry.kind(), ScanKind::Listen);
        assert!(
            !entry.is_complete(),
            "another sitting can always be appended to a watch"
        );
    }
}