rightkit-daemon 0.5.3

One discovery/auth convention for Right Suite local services: service.json, ranking and takeover, current-user-only Unix socket / named pipe, per-app request allowlist.
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
//! The per-app data root `<platform data dir>/Orthic Labs/<App>`, next to `Orthic Labs/shared`.
//!
//! [`AppRoot`] is built from a [`Suite`], so it honours exactly the root rules the suite already
//! has (`Suite::resolve`, `per_user_default`, `resolve_ignoring_env_overrides`, `at`,
//! `per_run_temp`); it adds no environment selector. When the suite root is the canonical
//! `.../Orthic Labs/shared`, the app root is the sibling `.../Orthic Labs/<App>`. For any other
//! suite root (an override, a test, a per-run temp) it is `<suite root>/apps/<App>`, so isolation
//! is preserved.
//!
//! Also here: path-escape-proof subpaths, a single-writer lock, and a restart-safe
//! copy-verify-commit migration from an old root. The old root is never modified. Migration is
//! strict by default (symlinks, junctions and special files are refused); [`MigrateOptions`] opts
//! in to copying symlinks as links, skipping sockets and FIFOs, and skipping (never following)
//! Windows junctions and other reparse points.
//!
//! # Completion states and markers
//!
//! A migration is in one of three [`MigrationState`]s, written in the versioned state file
//! [`MIGRATION_STATE`] (version 2; the unversioned `{source, files, bytes}` marker is version 1):
//!
//! * `Incomplete`: written before the destination is first touched and left in place by any
//!   interruption or failure. The old root stays the authority; the destination is not usable. A
//!   rerun verifies and finishes the whole copy.
//! * `ReadyWithOmissions`: every required entry is in place; only entries the caller declared
//!   disposable were omitted (optional links that could not be created, reparse points skipped on
//!   request). Every omission is recorded. A rerun retries the omitted links only; it does not
//!   re-verify files the app may have changed since.
//! * `Ready`: everything migrated.
//!
//! The historical marker [`MIGRATION_MARKER`] is written only for `Ready`, after the state file, so
//! a reader of an earlier version never takes an incomplete or partial destination for a finished
//! move.

use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Component, Path, PathBuf};

use rightkit_fs::{AtomicWriteOptions, AtomicWriter, FsError, ReplaceMode};

use crate::discovery::{try_lock_exclusive, LockedFile};
use crate::suite::{make_private_dir, Suite, SuiteError};

/// The longest app name accepted, in bytes.
pub const MAX_APP_NAME_LEN: usize = 64;
/// The historical commit marker written at the app root once a migration is fully verified. Only a
/// whole-tree [`MigrationState::Ready`] migration writes it; readers look only at `source`.
pub const MIGRATION_MARKER: &str = ".rightkit-migrated.json";
/// The versioned completion state of a migration (`Ready`, `ReadyWithOmissions` or `Incomplete`),
/// written at the app root before the destination is first touched and rewritten when the run
/// ends. Read it with [`AppRoot::migration_state`].
pub const MIGRATION_STATE: &str = ".rightkit-migration-state.json";
/// Version of the [`MIGRATION_STATE`] file. Version 1 is the unversioned marker.
const STATE_VERSION: u64 = 2;
const SELECTED_STATE_VERSION: u64 = 3;
const WRITER_LOCK: &str = ".writer.lock";

const WINDOWS_RESERVED: [&str; 22] = [
    "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
    "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];

/// Whether `s` is an app name: 1..=[`MAX_APP_NAME_LEN`] bytes of ASCII letters, digits, `-`, `_`
/// and `.`; starts and ends with a letter or digit (so no `.`, `..`, hidden or trailing-dot
/// names); no separators; not a Windows reserved device name (with or without an extension).
/// Case is preserved on disk but is significant for identity on every platform: two names that
/// differ only by case are refused as conflicting by [`AppRoot::new`] when one already exists.
pub fn valid_app_name(s: &str) -> bool {
    let b = s.as_bytes();
    if b.is_empty() || b.len() > MAX_APP_NAME_LEN {
        return false;
    }
    if !b
        .iter()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.'))
    {
        return false;
    }
    if !b[0].is_ascii_alphanumeric() || !b[b.len() - 1].is_ascii_alphanumeric() || s.contains("..")
    {
        return false;
    }
    // `shared` is the suite's shared-resources directory, a sibling of every app root.
    if s.eq_ignore_ascii_case("shared") {
        return false;
    }
    let stem = s.split('.').next().unwrap_or(s).to_ascii_uppercase();
    !WINDOWS_RESERVED.contains(&stem.as_str())
}

#[derive(Debug)]
pub enum AppRootError {
    InvalidName(String),
    /// A subpath was absolute, had `..`, `.`, a prefix, was empty, or resolved outside the root.
    PathEscape(String),
    /// An existing sibling differs from the requested app name only by case.
    CaseConflict {
        requested: String,
        existing: String,
    },
    /// Another process holds the single-writer lock.
    WriterBusy(PathBuf),
    /// The source tree holds a symlink, junction or other reparse point, or special file that this
    /// migration mode refuses (strict mode refuses every one; an opt-in mode still refuses
    /// devices and other specials, and a junction or reparse point unless
    /// [`MigrateOptions::skip_reparse_points`] is on).
    UnsupportedSource(PathBuf),
    /// A destination file exists with different content; nothing is overwritten.
    Collision(PathBuf),
    /// Source and destination are the same tree or nested in each other.
    Overlap(PathBuf),
    /// Post-copy verification found a difference.
    VerifyFailed(PathBuf),
    /// The folder the peer process resolved is not this app root
    /// ([`AppRoot::verify_peer_dir`]). Names neither path: a handshake mismatch must not become
    /// a way to read where the other process looks.
    PeerDirMismatch,
    Suite(SuiteError),
    Io(io::Error),
}

impl fmt::Display for AppRootError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidName(n) => write!(f, "invalid app name: {n:?}"),
            Self::PathEscape(p) => write!(f, "path escapes the app root: {p}"),
            Self::CaseConflict {
                requested,
                existing,
            } => write!(
                f,
                "app root {requested:?} conflicts with existing {existing:?} (differs only by case)"
            ),
            Self::WriterBusy(p) => write!(f, "another writer holds {}", p.display()),
            Self::UnsupportedSource(p) => {
                write!(
                    f,
                    "refusing symlink or special file in source: {}",
                    p.display()
                )
            }
            Self::Collision(p) => write!(f, "destination differs from source: {}", p.display()),
            Self::Overlap(p) => write!(f, "source and destination overlap: {}", p.display()),
            Self::VerifyFailed(p) => write!(f, "verification failed: {}", p.display()),
            Self::PeerDirMismatch => {
                write!(
                    f,
                    "the peer process uses a different data folder than this one"
                )
            }
            Self::Suite(e) => write!(f, "{e}"),
            Self::Io(e) => write!(f, "{e}"),
        }
    }
}
impl std::error::Error for AppRootError {}

impl AppRootError {
    /// The typed link failure carried by an [`AppRootError::Io`], if that is what this is: a
    /// symlink the destination could not create (Windows without the symlink privilege or
    /// Developer Mode, or a filesystem without links) during an opt-in migration. Read the link,
    /// its original target and the target that would have been written from [`LinkNotCreated`].
    pub fn link_not_created(&self) -> Option<&LinkNotCreated> {
        match self {
            Self::Io(e) => e.get_ref()?.downcast_ref::<LinkNotCreated>(),
            _ => None,
        }
    }

    /// True when trying again can succeed without changing the request: a link the destination
    /// could not create yet ([`AppRootError::link_not_created`]) or a busy writer lock.
    pub fn is_retryable(&self) -> bool {
        self.link_not_created().is_some() || matches!(self, Self::WriterBusy(_))
    }
}

/// A required symlink that the destination could not create. Carried inside
/// [`AppRootError::Io`]; read it with [`AppRootError::link_not_created`].
///
/// Retryable: it is returned before the completion marker is written, so the destination is not
/// treated as migrated, the old tree is untouched and still usable, and a later call (after the
/// privilege is granted) resumes and completes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LinkNotCreated {
    /// Path of the link relative to the migrated tree.
    pub link: PathBuf,
    /// The link's target text in the old tree.
    pub target: PathBuf,
    /// The target that would have been written (absolute for a rewritten external link).
    pub resolved: PathBuf,
    /// The operating system's reason.
    pub reason: String,
}

impl fmt::Display for LinkNotCreated {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "cannot create symlink {} -> {} in the app root: {}",
            self.link.display(),
            self.target.display(),
            self.reason
        )
    }
}
impl std::error::Error for LinkNotCreated {}

impl From<io::Error> for AppRootError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}
impl From<SuiteError> for AppRootError {
    fn from(e: SuiteError) -> Self {
        Self::Suite(e)
    }
}

/// Held while this process is the single writer of an app root. Released on drop or process
/// death (OS lock).
pub struct WriterLock {
    _file: LockedFile,
}

/// What [`AppRoot::migrate_from`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MigrationOutcome {
    /// Copied and verified; the marker was committed.
    Migrated { files: u64, bytes: u64 },
    /// The marker already records this source; nothing was touched.
    AlreadyMigrated,
    /// The source does not exist; nothing to do and no marker written.
    NothingToMigrate,
}

/// How far a migration into an app root got. Recorded in the versioned state file
/// ([`MIGRATION_STATE`]); read it with [`AppRoot::migration_state`] or
/// [`MigrationReport::state`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MigrationState {
    /// Everything in the recorded scope was migrated & verified. Whole-tree scope also writes
    /// the historical marker [`MIGRATION_MARKER`].
    Ready,
    /// Every required entry is in place. Only entries the caller declared disposable are missing,
    /// and each is recorded (optional links that could not be created, reparse points skipped on
    /// request). The destination is usable. The historical marker is not written, so a reader of
    /// an earlier version does not take it for a complete move; a rerun retries the omitted links.
    ReadyWithOmissions,
    /// The copy was started and not finished (interrupted, or stopped by a failure such as a
    /// required link the destination cannot create). The destination is not usable: the old root
    /// stays the authority. A rerun verifies and finishes the copy. No historical marker exists.
    Incomplete,
}

impl MigrationState {
    /// The name written in the state file: `ready`, `ready_with_omissions` or `incomplete`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ready => "ready",
            Self::ReadyWithOmissions => "ready_with_omissions",
            Self::Incomplete => "incomplete",
        }
    }

    /// True when the destination may be used as the app's data root (`Ready` or
    /// `ReadyWithOmissions`).
    pub fn is_usable(self) -> bool {
        !matches!(self, Self::Incomplete)
    }

    fn parse(s: &str) -> Option<Self> {
        match s {
            "ready" => Some(Self::Ready),
            "ready_with_omissions" => Some(Self::ReadyWithOmissions),
            "incomplete" => Some(Self::Incomplete),
            _ => None,
        }
    }
}

/// Persisted scope of a migration; selected roots include directory descendants.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MigrationScope {
    /// Historical whole-tree migration.
    All,
    /// Canonical relative roots, including an explicit empty selection.
    Roots(Vec<PathBuf>),
}

/// Read-only migration state & its persisted scope for one canonical source.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MigrationStatus {
    state: MigrationState,
    scope: MigrationScope,
}

impl MigrationStatus {
    /// Completion state recorded for this scope.
    pub fn state(&self) -> MigrationState {
        self.state
    }
    /// Exact persisted scope; observation alone does not prove another scope complete.
    pub fn scope(&self) -> &MigrationScope {
        &self.scope
    }
}

/// What [`AppRoot::migrate_from_with`] did: the [`MigrationOutcome`] plus what an opt-in
/// migration did with links, special files and reparse points. The lists describe this call's
/// work only (they are empty when the outcome is `NothingToMigrate`; the state file holds the
/// record of an earlier call). The one exception is a rerun that retries the omissions of a
/// `ReadyWithOmissions` migration: its `migrated_links` are the links created now, and
/// `omitted_optional_links` and `skipped_reparse_points` are what is still unresolved.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MigrationReport {
    outcome: MigrationOutcome,
    migrated_links: Vec<MigratedLink>,
    skipped_specials: Vec<SkippedSpecial>,
    omitted_optional_links: Vec<OmittedLink>,
    skipped_reparse_points: Vec<SkippedReparsePoint>,
    state: MigrationState,
}

impl MigrationReport {
    fn bare(outcome: MigrationOutcome, state: MigrationState) -> Self {
        Self {
            outcome,
            migrated_links: Vec::new(),
            skipped_specials: Vec::new(),
            omitted_optional_links: Vec::new(),
            skipped_reparse_points: Vec::new(),
            state,
        }
    }

    /// How far the migration got. A returned report is `Ready` or `ReadyWithOmissions`; an
    /// incomplete migration is an error, and its state is read with [`AppRoot::migration_state`].
    pub fn state(&self) -> MigrationState {
        self.state
    }

    /// Junctions and other Windows reparse points skipped on request (see
    /// [`MigrateOptions::skip_reparse_points`]). None is ever followed, copied or recreated.
    pub fn skipped_reparse_points(&self) -> &[SkippedReparsePoint] {
        &self.skipped_reparse_points
    }

    /// The same value `migrate_from` returns.
    pub fn outcome(&self) -> &MigrationOutcome {
        &self.outcome
    }

    pub fn into_outcome(self) -> MigrationOutcome {
        self.outcome
    }

    /// Symlinks recreated in the app root (as link entries, never followed).
    pub fn migrated_links(&self) -> &[MigratedLink] {
        &self.migrated_links
    }

    /// Sockets and FIFOs skipped (see [`MigrateOptions::skip_ephemeral_specials`]).
    pub fn skipped_specials(&self) -> &[SkippedSpecial] {
        &self.skipped_specials
    }

    /// Links the caller's policy marked optional and that could not be created. A required link
    /// that cannot be created is an error instead ([`AppRootError::link_not_created`]).
    pub fn omitted_optional_links(&self) -> &[OmittedLink] {
        &self.omitted_optional_links
    }

    /// True only for [`MigrationState::Ready`]: false when an optional link was omitted or a
    /// reparse point was skipped. Skipped ephemeral specials (sockets, FIFOs) do not make a
    /// migration incomplete. For `AlreadyMigrated` this is the value the earlier state recorded.
    pub fn complete(&self) -> bool {
        self.state == MigrationState::Ready
    }
}

/// A symlink recreated by a link-preserving migration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MigratedLink {
    /// Path of the link relative to the migrated tree.
    pub path: PathBuf,
    /// The link's target text in the old tree, exactly as `read_link` returned it.
    pub original_target: PathBuf,
    /// The target text written to the new link.
    pub written_target: PathBuf,
    /// True when a relative link leaving the tree was rewritten to an absolute path to its
    /// original target.
    pub rewritten: bool,
}

/// The kind of ephemeral special file skipped by a migration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpecialKind {
    Socket,
    Fifo,
}

impl SpecialKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Socket => "socket",
            Self::Fifo => "fifo",
        }
    }
}

/// A socket or FIFO that was skipped (not opened, not copied).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkippedSpecial {
    /// Path relative to the migrated tree.
    pub path: PathBuf,
    pub kind: SpecialKind,
}

/// The kind of Windows reparse point skipped by a migration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReparseKind {
    /// A junction (mount point) or volume mount point. Std reports it as a directory symlink, but
    /// it is not one: it is never recreated as a symlink, because that would change what it is.
    Junction,
    /// Any other reparse point that is not a symlink or an `AF_UNIX` socket (cloud placeholders,
    /// WSL links, app execution aliases, deduplicated files, ...).
    Other,
}

impl ReparseKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Junction => "junction",
            Self::Other => "other",
        }
    }
}

/// A reparse point that was skipped (never followed, opened, copied or recreated). Windows only:
/// see [`MigrateOptions::skip_reparse_points`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SkippedReparsePoint {
    /// Path relative to the migrated tree.
    pub path: PathBuf,
    pub kind: ReparseKind,
    /// The reparse tag (`IO_REPARSE_TAG_*`).
    pub tag: u32,
    /// Why it was skipped.
    pub reason: String,
}

/// An optional link that the destination could not hold and the caller's policy allowed to omit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OmittedLink {
    /// Path of the link relative to the migrated tree.
    pub path: PathBuf,
    /// The link's target text in the old tree.
    pub original_target: PathBuf,
    /// The target that would have been written (absolute for a rewritten external link).
    pub resolved_target: PathBuf,
    /// Why the link could not be created.
    pub reason: String,
}

type OptionalLinkPolicy = std::sync::Arc<dyn Fn(&Path) -> bool + Send + Sync>;

/// Opt-in behaviour for [`AppRoot::migrate_from_with`]. The default is strict and identical to
/// [`AppRoot::migrate_from`]: any symlink or special file in the source is refused.
///
/// The type is `#[non_exhaustive]`; build it with [`MigrateOptions::strict`] and the builders.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct MigrateOptions {
    links: bool,
    ephemeral_specials: bool,
    reparse_points: bool,
    optional_link: Option<OptionalLinkPolicy>,
    excluded: Vec<PathBuf>,
    pub(crate) included: Option<Vec<PathBuf>>,
}

impl fmt::Debug for MigrateOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MigrateOptions")
            .field("links", &self.links)
            .field("ephemeral_specials", &self.ephemeral_specials)
            .field("reparse_points", &self.reparse_points)
            .field("optional_link_policy", &self.optional_link.is_some())
            .field("excluded", &self.excluded)
            .field("included", &self.included)
            .finish()
    }
}

impl MigrateOptions {
    /// Restrict migration to these relative roots, including each directory's descendants.
    /// An empty list selects nothing; the default selects the whole tree.
    /// Selected migrations always revalidate source & destination, retain previously selected
    /// roots for retries of the same source, & use versioned scope-aware state without writing
    /// a historical whole-tree completion marker.
    pub fn include_roots(mut self, roots: Vec<PathBuf>) -> Result<Self, AppRootError> {
        self.included = Some(normalize_roots(roots)?);
        Ok(self)
    }

    fn selection(&self, rel: &Path) -> Result<bool, AppRootError> {
        let Some(roots) = &self.included else {
            return Ok(true);
        };
        for root in roots {
            if rel.starts_with(root) || root.starts_with(rel) {
                return Ok(true);
            }
            let a: Vec<_> = rel.components().collect();
            let b: Vec<_> = root.components().collect();
            if a.iter()
                .zip(&b)
                .all(|(x, y)| folded_component(*x) == folded_component(*y))
            {
                return Err(AppRootError::UnsupportedSource(rel.to_path_buf()));
            }
        }
        Ok(false)
    }

    fn scope_state(&self, mut body: serde_json::Value) -> serde_json::Value {
        if let Some(roots) = &self.included {
            body["version"] = serde_json::json!(SELECTED_STATE_VERSION);
            body["selected_roots"] = serde_json::json!(roots);
        }
        body
    }

    /// Refuse every symlink and special file (the default).
    pub fn strict() -> Self {
        Self::default()
    }

    /// Copy symlinks as link entries, never traversing them. A relative link that stays inside
    /// the tree keeps its text; a relative link that leaves the tree becomes an absolute link to
    /// its original target (resolved lexically against the link's old location); an absolute or
    /// dangling link is copied as it is. If the destination cannot create a link the migration
    /// fails with the retryable [`AppRootError::link_not_created`] error before any marker is written,
    /// unless [`MigrateOptions::optional_links`] marks that link omittable.
    pub fn preserve_links(mut self, on: bool) -> Self {
        self.links = on;
        self
    }

    /// Skip sockets and FIFOs (never opened) and report them. Device nodes and any other special
    /// file are still refused. On Windows an `AF_UNIX` socket file (a reparse point) counts as a
    /// socket.
    pub fn skip_ephemeral_specials(mut self, on: bool) -> Self {
        self.ephemeral_specials = on;
        self
    }

    /// Windows reparse-point policy. A junction (mount point) or any other reparse point that is
    /// neither a symlink nor an `AF_UNIX` socket is never followed, opened, copied or recreated:
    /// the migration cannot tell whether it leads out of the root, and recreating a junction as a
    /// symlink would change what it is. By default (and in strict mode) such an entry refuses the
    /// migration with [`AppRootError::UnsupportedSource`], before anything is written. With this
    /// option the entry is skipped and reported ([`MigrationReport::skipped_reparse_points`], and
    /// in the state file), and the result is [`MigrationState::ReadyWithOmissions`], never `Ready`:
    /// the caller has declared the entry disposable and the omission stays on record. A directory
    /// reparse point is never recursed into. No effect on other platforms (they have none).
    pub fn skip_reparse_points(mut self, on: bool) -> Self {
        self.reparse_points = on;
        self
    }

    /// Caller policy naming links that may be omitted when the destination cannot create them.
    /// The predicate receives the link's path relative to the migrated tree. It only matters
    /// together with [`MigrateOptions::preserve_links`], and only for a link whose creation
    /// failed; every other link is migrated normally. Omissions are reported in the outcome and
    /// in the marker, separately from required links.
    pub fn optional_links(
        mut self,
        is_optional: impl Fn(&Path) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.optional_link = Some(std::sync::Arc::new(is_optional));
        self
    }

    /// Leave the entry at `rel` (a path relative to the migrated tree) and everything below it out
    /// of the copy. For state a lifecycle participant moves by its own means (an encrypted
    /// database and its key, moved by [`RootCutover`](crate::RootCutover) through the participant
    /// that owns it): copying such files as plain bytes would race the owner's relocation and
    /// collide with its destination. An excluded path is not planned, copied, verified or
    /// recorded; it is neither an omission nor a reason for the state to be `ReadyWithOmissions`,
    /// so the caller that excludes a path owns moving it. Exclusions match exact components;
    /// differently spelled case aliases are refused rather than silently skipped. `rel` must be relative and made only of
    /// normal components; anything else is ignored (it can match no entry).
    pub fn exclude(mut self, rel: impl Into<PathBuf>) -> Self {
        let rel = rel.into();
        if rel.components().next().is_some()
            && rel.components().all(|c| matches!(c, Component::Normal(_)))
        {
            self.excluded.push(rel);
        }
        self
    }

    pub fn links(&self) -> bool {
        self.links
    }

    pub fn ephemeral_specials(&self) -> bool {
        self.ephemeral_specials
    }

    pub fn reparse_points(&self) -> bool {
        self.reparse_points
    }

    fn is_strict(&self) -> bool {
        !self.links
            && !self.ephemeral_specials
            && !self.reparse_points
            && self.optional_link.is_none()
    }

    fn is_optional(&self, rel: &Path) -> bool {
        self.optional_link.as_ref().is_some_and(|f| f(rel))
    }

    /// Exact component exclusions preserve distinct names on case-sensitive volumes.
    /// Differently spelled case aliases fail closed rather than silently omitting material.
    fn is_excluded(&self, rel: &Path) -> Result<bool, AppRootError> {
        for ex in &self.excluded {
            if rel.starts_with(ex) {
                return Ok(true);
            }
            let mut have = rel.components();
            let ambiguous = ex.components().all(|want| match (want, have.next()) {
                (Component::Normal(w), Some(Component::Normal(h))) => {
                    w.to_string_lossy().to_lowercase() == h.to_string_lossy().to_lowercase()
                }
                _ => false,
            });
            if ambiguous {
                return Err(AppRootError::UnsupportedSource(rel.to_path_buf()));
            }
        }
        Ok(false)
    }
}

pub(crate) fn normalize_roots(mut roots: Vec<PathBuf>) -> Result<Vec<PathBuf>, AppRootError> {
    for root in &roots {
        if root.as_os_str().is_empty()
            || root.to_str().is_none()
            || !root.components().all(|c| matches!(c, Component::Normal(_)))
            || root
                .components()
                .any(|c| c.as_os_str().to_string_lossy().contains(['\\', ':', '\0']))
            || root
                .to_string_lossy()
                .split(['/', '\\'])
                .any(|part| part.is_empty() || part == "." || part == "..")
            || [MIGRATION_STATE, MIGRATION_MARKER, WRITER_LOCK]
                .iter()
                .any(|reserved| roots_overlap(root, Path::new(reserved)))
        {
            return Err(AppRootError::PathEscape(root.display().to_string()));
        }
    }
    roots.sort();
    roots.dedup();
    for (i, root) in roots.iter().enumerate() {
        for other in &roots[..i] {
            let a: Vec<_> = root.components().collect();
            let b: Vec<_> = other.components().collect();
            for (x, y) in a.iter().zip(&b) {
                if x == y {
                    continue;
                }
                if folded_component(*x) == folded_component(*y) {
                    return Err(AppRootError::PathEscape(root.display().to_string()));
                }
                break;
            }
        }
    }
    let all = roots.clone();
    roots.retain(|root| {
        !all.iter()
            .any(|other| root != other && root.starts_with(other))
    });
    Ok(roots)
}

fn folded_component(component: Component<'_>) -> String {
    component.as_os_str().to_string_lossy().to_lowercase()
}

pub(crate) fn roots_overlap(a: &Path, b: &Path) -> bool {
    a.components()
        .zip(b.components())
        .all(|(x, y)| folded_component(x) == folded_component(y))
}

/// `<Orthic Labs>/<App>`, created private.
#[derive(Debug, Clone)]
pub struct AppRoot {
    name: String,
    root: PathBuf,
}

impl Suite {
    /// The per-app root for `app`, created private. See [`AppRoot`].
    pub fn app_root(&self, app: &str) -> Result<AppRoot, AppRootError> {
        AppRoot::new(self, app)
    }
}

impl AppRoot {
    pub fn new(suite: &Suite, app: &str) -> Result<AppRoot, AppRootError> {
        if !valid_app_name(app) {
            return Err(AppRootError::InvalidName(app.to_string()));
        }
        let parent = suite.app_parent();
        if let Ok(rd) = fs::read_dir(&parent) {
            for e in rd.flatten() {
                let n = e.file_name().to_string_lossy().into_owned();
                if n != app && n.eq_ignore_ascii_case(app) {
                    return Err(AppRootError::CaseConflict {
                        requested: app.to_string(),
                        existing: n,
                    });
                }
            }
        }
        let root = parent.join(app);
        make_private_dir(&root)?;
        Ok(AppRoot {
            name: app.to_string(),
            root,
        })
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Child-side (or parent-side) check that two processes resolved the same data folder
    /// (rightkit#989): `peer` is the folder the other process sent in its handshake, and it must
    /// be this app root, by file identity (device and inode on Unix; the canonical path compared
    /// without case on Windows), so a different spelling, a symlink or a case variant of the same
    /// folder passes and another folder does not. A path that does not exist or cannot be
    /// resolved is a mismatch. The refusal, [`AppRootError::PeerDirMismatch`], names neither
    /// path. The handshake payload that carries `peer` stays app code.
    pub fn verify_peer_dir(&self, peer: &Path) -> Result<(), AppRootError> {
        let ours = fs::canonicalize(&self.root)?;
        let theirs = fs::canonicalize(peer).map_err(|_| AppRootError::PeerDirMismatch)?;
        if same_directory(&ours, &theirs) {
            Ok(())
        } else {
            Err(AppRootError::PeerDirMismatch)
        }
    }

    /// `<app root>/<rel>` without creating anything. `rel` must be relative and made only of
    /// normal components (no `..`, `.`, root, prefix or empty); any existing ancestor that is a
    /// symlink must still resolve inside the app root.
    pub fn path(&self, rel: impl AsRef<Path>) -> Result<PathBuf, AppRootError> {
        self.path_checked(rel.as_ref(), true)
    }

    /// [`AppRoot::path`]; with `follow_leaf` false only the ancestors are validated and the final
    /// component may be a symlink (a link entry being placed) that is never resolved.
    fn path_checked(&self, rel: &Path, follow_leaf: bool) -> Result<PathBuf, AppRootError> {
        let bad = || AppRootError::PathEscape(rel.display().to_string());
        let mut any = false;
        for c in rel.components() {
            match c {
                Component::Normal(n) => {
                    any = true;
                    // `:` is a Windows stream/drive separator and a reserved char elsewhere.
                    if n.to_string_lossy().contains(['\\', ':', '\0']) {
                        return Err(bad());
                    }
                }
                _ => return Err(bad()),
            }
        }
        if !any {
            return Err(bad());
        }
        let full = self.root.join(rel);
        let canon_root = fs::canonicalize(&self.root)?;
        let mut probe = if follow_leaf {
            full.as_path()
        } else {
            full.parent().unwrap_or(&self.root)
        };
        loop {
            match fs::canonicalize(probe) {
                Ok(c) => {
                    if !c.starts_with(&canon_root) {
                        return Err(bad());
                    }
                    break;
                }
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    // A dangling symlink is NotFound for canonicalize but must not be followed.
                    if fs::symlink_metadata(probe).is_ok() {
                        return Err(bad());
                    }
                    match probe.parent() {
                        Some(p) if p.starts_with(&self.root) => probe = p,
                        _ => return Err(bad()),
                    }
                }
                Err(e) => return Err(e.into()),
            }
        }
        Ok(full)
    }

    /// A private directory at `<app root>/<rel>`, created if absent.
    pub fn data_dir(&self, rel: impl AsRef<Path>) -> Result<PathBuf, AppRootError> {
        let d = self.path(rel)?;
        make_private_dir(&d)?;
        // Re-check after creation: nothing created may resolve outside the root.
        self.path(d.strip_prefix(&self.root).unwrap_or(&d))?;
        Ok(d)
    }

    /// Take the single-writer lock for this app root. `Err(WriterBusy)` if another holder lives.
    pub fn lock_writer(&self) -> Result<WriterLock, AppRootError> {
        let p = self.root.join(WRITER_LOCK);
        match try_lock_exclusive(&p)? {
            Some(f) => Ok(WriterLock { _file: f }),
            None => Err(AppRootError::WriterBusy(p)),
        }
    }

    /// Copy the old root `src` into this app root, verify every byte, then commit. Restart-safe:
    /// files land under a temporary name and are renamed only when fully written; a rerun after
    /// any interruption re-copies missing or partial files, accepts files already identical, and
    /// refuses (never overwrites) a differing destination file. Directories, including empty
    /// ones, are migrated. The versioned state ([`MIGRATION_STATE`]) is `Incomplete` from before
    /// the destination is first touched until the copy is verified; the historical marker
    /// ([`MIGRATION_MARKER`]) is written last, and once present for this source the call is a
    /// no-op. `src` is never changed or deleted. Symlinks, junctions and special files in `src` are
    /// refused (strict); use [`AppRoot::migrate_from_with`] to opt in to links, ephemeral specials
    /// and skipped reparse points. Takes the writer lock.
    pub fn migrate_from(&self, src: &Path) -> Result<MigrationOutcome, AppRootError> {
        Ok(self
            .migrate_from_with(src, MigrateOptions::strict())?
            .into_outcome())
    }

    /// [`AppRoot::migrate_from`] with opt-in behaviour. Lock, restart, collision handling and the
    /// marker-last ordering are the same in every mode; `MigrateOptions::strict()` is exactly
    /// `migrate_from`. See [`MigrateOptions`] for how links, ephemeral specials and reparse points
    /// are handled. Returns a [`MigrationReport`] (its `outcome()` is what `migrate_from`
    /// returns).
    ///
    /// A required link that the destination cannot create returns the retryable
    /// [`AppRootError::link_not_created`] error and leaves the state `Incomplete`: the old tree is
    /// untouched, no historical marker exists, and the incomplete destination is never treated as
    /// migrated by this or an earlier version. A rerun finishes the copy. When the state is
    /// `ReadyWithOmissions` a rerun retries only the omitted links; it neither re-verifies files
    /// nor fails on files the app changed since.
    pub fn migrate_from_with(
        &self,
        src: &Path,
        opts: MigrateOptions,
    ) -> Result<MigrationReport, AppRootError> {
        self.migrate_impl(src, &opts, &make_link)
    }

    /// The completion state of the migration of `src` into this app root: `None` when no migration
    /// of `src` has started here (or `src` does not exist), otherwise what the last run left.
    /// `Incomplete` means the destination must not be used and the old root stays the authority. A
    /// historical marker written by an earlier version counts as `Ready` (as `ReadyWithOmissions`
    /// when it records `"complete": false`). A state file written by a newer version is an error
    /// (`AppRootError::Io`, `InvalidData`). Malformed metadata also fails rather than falling
    /// back to a historical marker. Takes no lock and changes nothing.
    pub fn migration_state(&self, src: &Path) -> Result<Option<MigrationState>, AppRootError> {
        Ok(self.migration_status(src)?.map(|status| status.state()))
    }

    /// Read persisted state & scope without taking a lock or changing files. Missing source or
    /// metadata returns `None`; valid metadata for another source also returns `None`.
    /// Malformed, unknown-version or invalid-scope metadata is an error, never evidence that a
    /// destination is untracked. A historical marker is consulted only when state is absent.
    pub fn migration_status(&self, src: &Path) -> Result<Option<MigrationStatus>, AppRootError> {
        if !src.is_absolute() || src.components().any(|c| c == Component::ParentDir) {
            return Err(AppRootError::PathEscape(src.display().to_string()));
        }
        let csrc = match fs::canonicalize(src) {
            Ok(c) => c,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        let invalid = |detail: &str| {
            AppRootError::Io(io::Error::new(
                io::ErrorKind::InvalidData,
                detail.to_string(),
            ))
        };
        let valid_source = |source: &str| {
            let path = Path::new(source);
            path.is_absolute() && !path.components().any(|part| part == Component::ParentDir)
        };
        let read = |path: &Path| -> Result<Option<serde_json::Value>, AppRootError> {
            let text = match fs::read_to_string(path) {
                Ok(text) => text,
                Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
                Err(error) => return Err(error.into()),
            };
            serde_json::from_str(&text)
                .map(Some)
                .map_err(|_| invalid("invalid migration metadata JSON"))
        };
        if let Some(value) = read(&self.root.join(MIGRATION_STATE))? {
            let source = value
                .get("source")
                .and_then(serde_json::Value::as_str)
                .ok_or_else(|| invalid("missing migration source"))?;
            if !valid_source(source) {
                return Err(invalid("invalid migration source"));
            }
            let state = value
                .get("state")
                .and_then(serde_json::Value::as_str)
                .and_then(MigrationState::parse)
                .ok_or_else(|| invalid("unknown migration state"))?;
            let scope = match value.get("version").and_then(serde_json::Value::as_u64) {
                Some(1) | Some(STATE_VERSION) if value.get("selected_roots").is_none() => {
                    MigrationScope::All
                }
                Some(SELECTED_STATE_VERSION) => {
                    let roots: Vec<PathBuf> = serde_json::from_value(
                        value
                            .get("selected_roots")
                            .cloned()
                            .ok_or_else(|| invalid("missing selected scope"))?,
                    )
                    .map_err(|_| invalid("invalid selected scope"))?;
                    if normalize_roots(roots.clone())
                        .map_err(|_| invalid("invalid selected scope"))?
                        != roots
                    {
                        return Err(invalid("noncanonical selected scope"));
                    }
                    MigrationScope::Roots(roots)
                }
                _ => return Err(invalid("unknown migration version or scope")),
            };
            return Ok((Some(source) == csrc.to_str()).then_some(MigrationStatus { state, scope }));
        }
        let Some(marker) = read(&self.root.join(MIGRATION_MARKER))? else {
            return Ok(None);
        };
        let source = marker
            .get("source")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| invalid("missing historical migration source"))?;
        if !valid_source(source) {
            return Err(invalid("invalid historical migration source"));
        }
        let complete = match marker.get("complete") {
            None => true,
            Some(value) => value
                .as_bool()
                .ok_or_else(|| invalid("invalid historical completion flag"))?,
        };
        Ok((Some(source) == csrc.to_str()).then_some(MigrationStatus {
            state: if complete {
                MigrationState::Ready
            } else {
                MigrationState::ReadyWithOmissions
            },
            scope: MigrationScope::All,
        }))
    }

    /// The state file when it records `csrc` as its source. An unreadable or unversioned file is
    /// not ours and counts as absent; a file of a newer version, or with a state this version does
    /// not know, is refused rather than guessed at.
    fn read_state(
        &self,
        csrc: &Path,
    ) -> Result<Option<(MigrationState, serde_json::Value)>, AppRootError> {
        let path = self.root.join(MIGRATION_STATE);
        let text = match fs::read_to_string(&path) {
            Ok(t) => t,
            Err(e)
                if matches!(
                    e.kind(),
                    io::ErrorKind::NotFound | io::ErrorKind::InvalidData
                ) =>
            {
                return Ok(None)
            }
            Err(e) => return Err(e.into()),
        };
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else {
            return Ok(None);
        };
        let Some(version) = v.get("version").and_then(|n| n.as_u64()) else {
            return Ok(None);
        };
        if v.get("source").and_then(|s| s.as_str()) != csrc.to_str() {
            return Ok(None);
        }
        let state = v
            .get("state")
            .and_then(|s| s.as_str())
            .and_then(MigrationState::parse);
        match state {
            Some(state) if version <= SELECTED_STATE_VERSION => {
                if version < SELECTED_STATE_VERSION && v.get("selected_roots").is_some() {
                    return Err(AppRootError::PathEscape("legacy state cannot carry selected scope".into()));
                }
                if version == SELECTED_STATE_VERSION {
                    let roots: Vec<PathBuf> = serde_json::from_value(v.get("selected_roots").cloned().ok_or_else(|| AppRootError::PathEscape("missing selected scope".into()))?)
                        .map_err(|_| AppRootError::PathEscape("invalid selected scope".into()))?;
                    if normalize_roots(roots.clone())? != roots {
                        return Err(AppRootError::PathEscape("noncanonical selected scope".into()));
                    }
                }
                Ok(Some((state, v)))
            },
            _ => Err(AppRootError::Io(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "{} was written by a newer version or holds an unknown state; refusing to guess",
                    path.display()
                ),
            ))),
        }
    }

    /// `Some(complete)` when the historical marker records `csrc` as its source.
    fn legacy_marker(&self, csrc: &Path) -> Option<bool> {
        let text = fs::read_to_string(self.root.join(MIGRATION_MARKER)).ok()?;
        let v = serde_json::from_str::<serde_json::Value>(&text).ok()?;
        if v.get("source").and_then(|s| s.as_str()) != csrc.to_str() {
            return None;
        }
        Some(v.get("complete").and_then(|c| c.as_bool()).unwrap_or(true))
    }

    fn write_state(&self, body: &serde_json::Value) -> Result<(), AppRootError> {
        write_json_atomic(&self.root.join(MIGRATION_STATE), body)?;
        Ok(())
    }

    fn migrate_impl(
        &self,
        src: &Path,
        opts: &MigrateOptions,
        maker: LinkMaker<'_>,
    ) -> Result<MigrationReport, AppRootError> {
        self.migrate_current(src, opts, maker, false)
    }

    /// Cutover must compare current authoritative bytes even if a previous copy was Ready.
    pub(crate) fn migrate_for_cutover(
        &self,
        src: &Path,
        opts: &MigrateOptions,
    ) -> Result<MigrationReport, AppRootError> {
        self.migrate_current(src, opts, &make_link, true)
    }

    fn migrate_current(
        &self,
        src: &Path,
        opts: &MigrateOptions,
        maker: LinkMaker<'_>,
        revalidate: bool,
    ) -> Result<MigrationReport, AppRootError> {
        if !src.is_absolute() || src.components().any(|c| c == Component::ParentDir) {
            return Err(AppRootError::PathEscape(src.display().to_string()));
        }
        let md = match fs::symlink_metadata(src) {
            Ok(m) => m,
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                return Ok(MigrationReport::bare(
                    MigrationOutcome::NothingToMigrate,
                    MigrationState::Ready,
                ))
            }
            Err(e) => return Err(e.into()),
        };
        if !md.is_dir() {
            return Err(AppRootError::UnsupportedSource(src.to_path_buf()));
        }
        let csrc = fs::canonicalize(src)?;
        let cdst = fs::canonicalize(&self.root)?;
        if csrc.starts_with(&cdst) || cdst.starts_with(&csrc) {
            return Err(AppRootError::Overlap(src.to_path_buf()));
        }
        let _lock = self.lock_writer()?;
        let prior = self.read_state(&csrc)?;
        let prior_selected = prior
            .as_ref()
            .is_some_and(|(_, state)| state.get("selected_roots").is_some());
        let mut effective = opts.clone();
        if let (Some(roots), Some((_, state))) = (&mut effective.included, &prior) {
            if let Some(previous) = state.get("selected_roots") {
                let previous: Vec<PathBuf> = serde_json::from_value(previous.clone())
                    .map_err(|_| AppRootError::PathEscape("invalid selected scope".into()))?;
                roots.extend(previous);
                *roots = normalize_roots(std::mem::take(roots))?;
            }
        }
        let opts = &effective;
        let revalidate = revalidate || opts.included.is_some() || prior_selected;
        match prior {
            Some((MigrationState::Ready, state)) if !revalidate => {
                self.repair_marker(&csrc, &state);
                return Ok(MigrationReport::bare(
                    MigrationOutcome::AlreadyMigrated,
                    MigrationState::Ready,
                ));
            }
            Some((MigrationState::ReadyWithOmissions, state)) if !revalidate => {
                return self.retry_unresolved(&csrc, &state, maker);
            }
            // An earlier run did not finish: do the whole copy again.
            Some(_) => {}
            None => {
                if let Some(complete) = self.legacy_marker(&csrc).filter(|_| !revalidate) {
                    let state = if complete {
                        MigrationState::Ready
                    } else {
                        MigrationState::ReadyWithOmissions
                    };
                    return Ok(MigrationReport::bare(
                        MigrationOutcome::AlreadyMigrated,
                        state,
                    ));
                }
            }
        }
        // Plan first: a source this mode refuses fails here, before the destination is touched.
        let mut entries = Vec::new();
        collect(&csrc, Path::new(""), opts, &mut entries)?;
        if revalidate {
            // Old root remains authoritative until switch. A file removed there after an earlier
            // copy must not survive silently in the selected tree; preserve it and refuse cutover.
            let current: std::collections::BTreeSet<_> = entries.iter().map(Entry::rel).collect();
            let mut destination = Vec::new();
            let destination_opts = opts.clone().exclude(WRITER_LOCK);
            collect(&cdst, Path::new(""), &destination_opts, &mut destination)?;
            for entry in &destination {
                if !current.contains(entry.rel()) {
                    return Err(AppRootError::Collision(cdst.join(entry.rel())));
                }
            }
        }
        // Record the pending state before the first destination write, so that any interruption
        // (a crash included) leaves `Incomplete` on disk and never a state that reads as done.
        self.write_state(&opts.scope_state(state_json(
            MigrationState::Incomplete,
            csrc.to_str(),
            &Lists::default(),
            None,
        )))?;
        match self.copy_entries(&csrc, &entries, opts, maker) {
            Ok(done) => self.commit(&csrc, opts, done),
            Err(e) => {
                self.record_failure(&csrc, opts, &e);
                Err(e)
            }
        }
    }

    /// Copy and verify every planned entry. Nothing here writes a marker or a completed state.
    fn copy_entries(
        &self,
        csrc: &Path,
        entries: &[Entry],
        opts: &MigrateOptions,
        maker: LinkMaker<'_>,
    ) -> Result<Lists, AppRootError> {
        let mut done = Lists::default();
        // (relative path, written target, is a directory link) for verification.
        let mut created: Vec<(PathBuf, PathBuf, bool)> = Vec::new();
        for entry in entries {
            match entry {
                Entry::Dir { rel } => {
                    // Validate the parent chain only: the leaf must be a real directory and is
                    // never followed if it is a link.
                    let to = self.path_checked(rel, false)?;
                    match fs::symlink_metadata(&to) {
                        Ok(m) if m.file_type().is_dir() => make_private_dir(&to)?,
                        Ok(_) => return Err(AppRootError::Collision(to)),
                        Err(e) if e.kind() == io::ErrorKind::NotFound => make_private_dir(&to)?,
                        Err(e) => return Err(e.into()),
                    }
                }
                Entry::File { rel, len } => {
                    done.files += 1;
                    done.bytes += len;
                    let from = csrc.join(rel);
                    let to = self.path(rel)?;
                    if let Some(parent) = to.parent() {
                        make_private_dir(parent)?;
                    }
                    match fs::symlink_metadata(&to) {
                        Ok(m) if regular_entry(&m) && same_content(&from, &to)? => {
                            continue;
                        }
                        Ok(_) => return Err(AppRootError::Collision(to)),
                        Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                        Err(e) => return Err(e.into()),
                    }
                    let mut writer =
                        AtomicWriter::create_new_private(&to).map_err(io::Error::other)?;
                    let mut source =
                        rightkit_fs::open_read_nofollow(&from, &rightkit_fs::ReadOptions::new())
                            .map_err(io::Error::other)?;
                    io::copy(&mut source, writer.file_mut())?;
                    commit_migration_file(writer, &from, &to)?;
                }
                Entry::Link { rel, target, dir } => {
                    let (written, rewritten) = plan_link(csrc, rel, target);
                    // Validate the parent chain only: the leaf is a link and is never followed.
                    let to = self.path_checked(rel, false)?;
                    if let Some(parent) = to.parent() {
                        make_private_dir(parent)?;
                    }
                    match fs::symlink_metadata(&to) {
                        Ok(m) => {
                            if !(m.file_type().is_symlink()
                                && same_link_target(&fs::read_link(&to)?, &written))
                            {
                                return Err(AppRootError::Collision(to));
                            }
                        }
                        Err(e) if e.kind() == io::ErrorKind::NotFound => {
                            if let Err(e) = maker(&written, &to, *dir) {
                                if !link_unavailable(&e) {
                                    return Err(e.into());
                                }
                                if opts.is_optional(rel) {
                                    done.omitted.push(OmittedLink {
                                        path: rel.clone(),
                                        original_target: target.clone(),
                                        resolved_target: written,
                                        reason: e.to_string(),
                                    });
                                    continue;
                                }
                                return Err(AppRootError::Io(io::Error::other(LinkNotCreated {
                                    link: rel.clone(),
                                    target: target.clone(),
                                    resolved: written,
                                    reason: e.to_string(),
                                })));
                            }
                        }
                        Err(e) => return Err(e.into()),
                    }
                    created.push((rel.clone(), written.clone(), *dir));
                    done.links.push(MigratedLink {
                        path: rel.clone(),
                        original_target: target.clone(),
                        written_target: written,
                        rewritten,
                    });
                }
                Entry::Special { rel, kind } => done.specials.push(SkippedSpecial {
                    path: rel.clone(),
                    kind: *kind,
                }),
                Entry::Reparse { rel, kind, tag } => done.reparse.push(SkippedReparsePoint {
                    path: rel.clone(),
                    kind: *kind,
                    tag: *tag,
                    reason: reparse_reason(*kind, *tag),
                }),
            }
        }
        for entry in entries {
            match entry {
                Entry::File { rel, .. } => {
                    let to = self.path(rel)?;
                    if !same_content(&csrc.join(rel), &to)? {
                        return Err(AppRootError::VerifyFailed(to));
                    }
                }
                Entry::Dir { rel } => {
                    let to = self.path_checked(rel, false)?;
                    if !fs::symlink_metadata(&to).is_ok_and(|m| m.file_type().is_dir()) {
                        return Err(AppRootError::VerifyFailed(to));
                    }
                }
                _ => {}
            }
        }
        for (rel, written, dir) in &created {
            // Compare with read_link only; a link is never followed.
            let to = self.path_checked(rel, false)?;
            if !link_ok(&to, written, *dir) {
                return Err(AppRootError::VerifyFailed(to));
            }
        }
        Ok(done)
    }

    /// The copy is verified: write the final state, then (only for `Ready`) the historical marker.
    /// The state goes first, so a crash between the two leaves a state new readers trust and no
    /// marker an old reader could mistake; the next call repairs the marker.
    fn commit(
        &self,
        csrc: &Path,
        opts: &MigrateOptions,
        done: Lists,
    ) -> Result<MigrationReport, AppRootError> {
        let state = done.state();
        self.write_state(&opts.scope_state(state_json(state, csrc.to_str(), &done, None)))?;
        if state == MigrationState::Ready && opts.included.is_none() {
            let body = marker_json(
                csrc.to_str(),
                done.files,
                done.bytes,
                opts,
                &done.links,
                &done.specials,
                &done.omitted,
            );
            write_json_atomic(&self.root.join(MIGRATION_MARKER), &body)?;
        }
        Ok(MigrationReport {
            outcome: MigrationOutcome::Migrated {
                files: done.files,
                bytes: done.bytes,
            },
            migrated_links: done.links,
            skipped_specials: done.specials,
            omitted_optional_links: done.omitted,
            skipped_reparse_points: done.reparse,
            state,
        })
    }

    /// Best effort: leave `Incomplete` on disk with the reason, and the link that blocked it.
    fn record_failure(&self, csrc: &Path, opts: &MigrateOptions, e: &AppRootError) {
        let mut body = opts.scope_state(state_json(
            MigrationState::Incomplete,
            csrc.to_str(),
            &Lists::default(),
            Some(&e.to_string()),
        ));
        if let (Some(l), Some(obj)) = (e.link_not_created(), body.as_object_mut()) {
            obj.insert(
                "unresolved".into(),
                serde_json::json!([{"path": lossy(&l.link), "kind": "link", "reason": l.reason}]),
            );
        }
        let _ = self.write_state(&body);
    }

    /// A `Ready` state without its historical marker (a crash between the two writes): write it.
    fn repair_marker(&self, csrc: &Path, state: &serde_json::Value) {
        let path = self.root.join(MIGRATION_MARKER);
        if path.exists() {
            return;
        }
        let l = Lists::from_state(state);
        let opts = MigrateOptions::strict().preserve_links(true);
        let body = marker_json(
            csrc.to_str(),
            l.files,
            l.bytes,
            &opts,
            &l.links,
            &l.specials,
            &l.omitted,
        );
        let _ = write_json_atomic(&path, &body);
    }

    /// Rerun of a `ReadyWithOmissions` migration: retry the omitted links only. Files are not
    /// compared again (the app has been running on the destination and may have changed them), and
    /// a link that still cannot be created, or whose destination path is now occupied, stays
    /// omitted. Skipped reparse points stay skipped. When nothing is left unresolved the state
    /// becomes `Ready` and the historical marker is written.
    fn retry_unresolved(
        &self,
        csrc: &Path,
        state: &serde_json::Value,
        maker: LinkMaker<'_>,
    ) -> Result<MigrationReport, AppRootError> {
        let prior = Lists::from_state(state);
        let mut next = Lists {
            files: prior.files,
            bytes: prior.bytes,
            links: prior.links,
            specials: prior.specials,
            omitted: Vec::new(),
            reparse: prior.reparse,
        };
        let mut created = Vec::new();
        for o in prior.omitted {
            match self.retry_link(csrc, &o, maker)? {
                Ok(link) => {
                    created.push(link.clone());
                    next.links.push(link);
                }
                Err(reason) => next.omitted.push(OmittedLink { reason, ..o }),
            }
        }
        let now = next.state();
        if !created.is_empty() || now == MigrationState::Ready {
            self.write_state(&state_json(now, csrc.to_str(), &next, None))?;
            if now == MigrationState::Ready {
                let opts = MigrateOptions::strict().preserve_links(true);
                let body = marker_json(
                    csrc.to_str(),
                    next.files,
                    next.bytes,
                    &opts,
                    &next.links,
                    &next.specials,
                    &next.omitted,
                );
                write_json_atomic(&self.root.join(MIGRATION_MARKER), &body)?;
            }
        }
        Ok(MigrationReport {
            outcome: MigrationOutcome::AlreadyMigrated,
            migrated_links: created,
            skipped_specials: Vec::new(),
            omitted_optional_links: next.omitted,
            skipped_reparse_points: next.reparse,
            state: now,
        })
    }

    /// Retry one omitted link. `Ok(Ok(link))` it exists now (created, or already identical),
    /// `Ok(Err(reason))` it stays omitted, `Err` a fault that is not about links being unavailable.
    fn retry_link(
        &self,
        csrc: &Path,
        o: &OmittedLink,
        maker: LinkMaker<'_>,
    ) -> Result<Result<MigratedLink, String>, AppRootError> {
        let from = csrc.join(&o.path);
        let md = match fs::symlink_metadata(&from) {
            Ok(m) if m.file_type().is_symlink() => m,
            Ok(_) => return Ok(Err("the source entry is no longer a link".to_string())),
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                return Ok(Err("the source link no longer exists".to_string()))
            }
            Err(e) => return Err(e.into()),
        };
        let target = fs::read_link(&from)?;
        let dir = link_is_dir(&md.file_type());
        let (written, rewritten) = plan_link(csrc, &o.path, &target);
        let to = self.path_checked(&o.path, false)?;
        match fs::symlink_metadata(&to) {
            Ok(m) => {
                let same = m.file_type().is_symlink()
                    && fs::read_link(&to).is_ok_and(|t| same_link_target(&t, &written));
                if !same {
                    return Ok(Err("the destination path is occupied".to_string()));
                }
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                if let Some(parent) = to.parent() {
                    make_private_dir(parent)?;
                }
                if let Err(e) = maker(&written, &to, dir) {
                    if link_unavailable(&e) {
                        return Ok(Err(e.to_string()));
                    }
                    return Err(e.into());
                }
            }
            Err(e) => return Err(e.into()),
        }
        if !link_ok(&to, &written, dir) {
            return Err(AppRootError::VerifyFailed(to));
        }
        Ok(Ok(MigratedLink {
            path: o.path.clone(),
            original_target: target,
            written_target: written,
            rewritten,
        }))
    }
}

type LinkMaker<'a> = &'a dyn Fn(&Path, &Path, bool) -> io::Result<()>;

/// One thing found under the source tree.
enum Entry {
    /// A directory (recorded before its contents), so an empty one is migrated too.
    Dir {
        rel: PathBuf,
    },
    File {
        rel: PathBuf,
        len: u64,
    },
    /// A symlink, recorded without following it. `dir` is true for a Windows directory link.
    Link {
        rel: PathBuf,
        target: PathBuf,
        dir: bool,
    },
    Special {
        rel: PathBuf,
        kind: SpecialKind,
    },
    /// A Windows junction or other reparse point, recorded without following it. Only built on
    /// Windows.
    #[cfg_attr(not(windows), allow(dead_code))]
    Reparse {
        rel: PathBuf,
        kind: ReparseKind,
        tag: u32,
    },
}

impl Entry {
    fn rel(&self) -> &Path {
        match self {
            Self::Dir { rel }
            | Self::File { rel, .. }
            | Self::Link { rel, .. }
            | Self::Special { rel, .. }
            | Self::Reparse { rel, .. } => rel,
        }
    }
}

/// What a migration did or found, as it is recorded in the state file. `Default` is the empty
/// state of a run that has just started.
#[derive(Default)]
struct Lists {
    files: u64,
    bytes: u64,
    links: Vec<MigratedLink>,
    specials: Vec<SkippedSpecial>,
    omitted: Vec<OmittedLink>,
    reparse: Vec<SkippedReparsePoint>,
}

impl Lists {
    /// `Ready` unless a link was omitted or a reparse point skipped. Skipped ephemeral specials
    /// are recorded but do not count.
    fn state(&self) -> MigrationState {
        if self.omitted.is_empty() && self.reparse.is_empty() {
            MigrationState::Ready
        } else {
            MigrationState::ReadyWithOmissions
        }
    }

    /// Read the lists back from a state file (entries that do not parse are dropped).
    fn from_state(v: &serde_json::Value) -> Self {
        let text =
            |o: &serde_json::Value, k: &str| o.get(k).and_then(|s| s.as_str()).map(PathBuf::from);
        let items = |k: &str| {
            v.get(k)
                .and_then(|a| a.as_array())
                .cloned()
                .unwrap_or_default()
        };
        Self {
            files: v.get("files").and_then(|n| n.as_u64()).unwrap_or(0),
            bytes: v.get("bytes").and_then(|n| n.as_u64()).unwrap_or(0),
            links: items("links")
                .iter()
                .filter_map(|o| {
                    Some(MigratedLink {
                        path: text(o, "path")?,
                        original_target: text(o, "original_target")?,
                        written_target: text(o, "written_target")?,
                        rewritten: o
                            .get("rewritten")
                            .and_then(|b| b.as_bool())
                            .unwrap_or(false),
                    })
                })
                .collect(),
            specials: items("skipped_specials")
                .iter()
                .filter_map(|o| {
                    let kind = match o.get("kind").and_then(|k| k.as_str())? {
                        "socket" => SpecialKind::Socket,
                        "fifo" => SpecialKind::Fifo,
                        _ => return None,
                    };
                    Some(SkippedSpecial {
                        path: text(o, "path")?,
                        kind,
                    })
                })
                .collect(),
            omitted: items("omitted_optional_links")
                .iter()
                .filter_map(|o| {
                    Some(OmittedLink {
                        path: text(o, "path")?,
                        original_target: text(o, "original_target")?,
                        resolved_target: text(o, "resolved_target")?,
                        reason: o.get("reason").and_then(|r| r.as_str())?.to_string(),
                    })
                })
                .collect(),
            reparse: items("skipped_reparse_points")
                .iter()
                .filter_map(|o| {
                    let kind = match o.get("kind").and_then(|k| k.as_str())? {
                        "junction" => ReparseKind::Junction,
                        _ => ReparseKind::Other,
                    };
                    Some(SkippedReparsePoint {
                        path: text(o, "path")?,
                        kind,
                        tag: o.get("tag").and_then(|t| t.as_u64()).unwrap_or(0) as u32,
                        reason: o.get("reason").and_then(|r| r.as_str())?.to_string(),
                    })
                })
                .collect(),
        }
    }
}

/// The names the migration itself owns at the root of the source: a marker or state file of an
/// earlier migration of that root must not be copied over this root's own.
fn is_reserved_root_name(name: &std::ffi::OsStr) -> bool {
    let n = name.to_string_lossy();
    n == MIGRATION_MARKER || n == MIGRATION_STATE
}

/// Every directory, regular file, and under `opts` every symlink, ephemeral special and skipped
/// reparse point, below `base/rel`. Directories are entries too (before their contents), so an
/// empty directory is migrated. A symlink, junction or reparse point is never traversed. Without
/// the matching option a symlink, junction, reparse point or special file is refused. The
/// migration's own marker and state names are not entries at the root of the source.
fn collect(
    base: &Path,
    rel: &Path,
    opts: &MigrateOptions,
    out: &mut Vec<Entry>,
) -> Result<(), AppRootError> {
    let mut entries: Vec<_> = fs::read_dir(base.join(rel))?.collect::<Result<_, _>>()?;
    entries.sort_by_key(|e| e.file_name());
    for e in entries {
        let name = e.file_name();
        if rel.as_os_str().is_empty() && is_reserved_root_name(&name) {
            continue;
        }
        let r = rel.join(&name);
        if !opts.selection(&r)? || opts.is_excluded(&r)? {
            continue;
        }
        // Windows: classify a reparse point before anything else. `DirEntry::file_type` reports a
        // junction as a directory symlink and an `AF_UNIX` socket file as a plain file; neither
        // may be treated as what std calls it.
        #[cfg(windows)]
        {
            if let Some(kind) = reparse_of(&e, &base.join(&r))? {
                if opts
                    .included
                    .as_ref()
                    .is_some_and(|roots| !roots.iter().any(|root| r.starts_with(root)))
                {
                    return Err(AppRootError::UnsupportedSource(base.join(&r)));
                }
                match kind {
                    Reparse::Symlink => {}
                    Reparse::Socket => {
                        if opts.ephemeral_specials {
                            out.push(Entry::Special {
                                rel: r,
                                kind: SpecialKind::Socket,
                            });
                            continue;
                        }
                        return Err(AppRootError::UnsupportedSource(base.join(&r)));
                    }
                    Reparse::Junction | Reparse::Other(_) => {
                        if opts.reparse_points {
                            let (kind, tag) = match kind {
                                Reparse::Other(tag) => (ReparseKind::Other, tag),
                                _ => (ReparseKind::Junction, IO_REPARSE_TAG_MOUNT_POINT),
                            };
                            out.push(Entry::Reparse { rel: r, kind, tag });
                            continue;
                        }
                        return Err(AppRootError::UnsupportedSource(base.join(&r)));
                    }
                }
            }
        }
        // DirEntry::file_type does not follow symlinks.
        let ft = e.file_type()?;
        if opts
            .included
            .as_ref()
            .is_some_and(|roots| !roots.iter().any(|root| r.starts_with(root)))
            && !ft.is_dir()
        {
            return Err(AppRootError::UnsupportedSource(base.join(&r)));
        }
        if ft.is_symlink() {
            if !opts.links {
                return Err(AppRootError::UnsupportedSource(base.join(&r)));
            }
            let target = fs::read_link(base.join(&r))?;
            out.push(Entry::Link {
                dir: link_is_dir(&ft),
                rel: r,
                target,
            });
        } else if ft.is_dir() {
            out.push(Entry::Dir { rel: r.clone() });
            collect(base, &r, opts, out)?;
        } else if ft.is_file() {
            out.push(Entry::File {
                len: e.metadata()?.len(),
                rel: r,
            });
        } else {
            match special_kind(&ft) {
                // Never opened, never copied.
                Some(kind) if opts.ephemeral_specials => out.push(Entry::Special { rel: r, kind }),
                _ => return Err(AppRootError::UnsupportedSource(base.join(&r))),
            }
        }
    }
    Ok(())
}

/// How a Windows entry that carries `FILE_ATTRIBUTE_REPARSE_POINT` is classified by its tag.
#[cfg(windows)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reparse {
    /// `IO_REPARSE_TAG_SYMLINK`: handled as a link (`preserve_links`) like any other symlink.
    Symlink,
    /// `IO_REPARSE_TAG_MOUNT_POINT`: a junction or volume mount point.
    Junction,
    /// `IO_REPARSE_TAG_AF_UNIX`: an `AF_UNIX` socket file.
    Socket,
    /// Any other tag.
    Other(u32),
}

#[cfg(windows)]
const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000_000C;
#[cfg(windows)]
const IO_REPARSE_TAG_MOUNT_POINT: u32 = 0xA000_0003;
#[cfg(windows)]
const IO_REPARSE_TAG_AF_UNIX: u32 = 0x8000_0023;

#[cfg(windows)]
fn classify_reparse_tag(tag: u32) -> Reparse {
    match tag {
        IO_REPARSE_TAG_SYMLINK => Reparse::Symlink,
        IO_REPARSE_TAG_MOUNT_POINT => Reparse::Junction,
        IO_REPARSE_TAG_AF_UNIX => Reparse::Socket,
        other => Reparse::Other(other),
    }
}

/// `None` when the entry is not a reparse point. `DirEntry::metadata` does not follow reparse
/// points, so the attribute is the entry's own; the tag is read without opening the entry.
#[cfg(windows)]
fn reparse_of(e: &fs::DirEntry, full: &Path) -> io::Result<Option<Reparse>> {
    use std::os::windows::fs::MetadataExt;
    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
    if e.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 {
        return Ok(None);
    }
    Ok(Some(classify_reparse_tag(reparse_tag(full)?)))
}

/// The reparse tag of the entry at `path` (`WIN32_FIND_DATAW::dwReserved0` of `FindFirstFileW`,
/// which describes the entry itself and does not follow it).
#[cfg(windows)]
fn reparse_tag(path: &Path) -> io::Result<u32> {
    use std::os::windows::ffi::OsStrExt;
    use windows::core::PCWSTR;
    use windows::Win32::Storage::FileSystem::{FindClose, FindFirstFileW, WIN32_FIND_DATAW};
    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let mut data = WIN32_FIND_DATAW::default();
    // SAFETY: `wide` is NUL-terminated and outlives the call, and `data` is a valid out pointer.
    let handle =
        unsafe { FindFirstFileW(PCWSTR(wide.as_ptr()), &mut data) }.map_err(io::Error::other)?;
    // SAFETY: `handle` came from `FindFirstFileW` above and is closed exactly once.
    let _ = unsafe { FindClose(handle) };
    Ok(data.dwReserved0)
}

fn reparse_reason(kind: ReparseKind, tag: u32) -> String {
    match kind {
        ReparseKind::Junction => {
            "junction or volume mount point: never followed, copied or recreated".to_string()
        }
        ReparseKind::Other => {
            format!("reparse point (tag {tag:#010x}): never followed, opened, copied or recreated")
        }
    }
}

#[cfg(unix)]
fn special_kind(ft: &fs::FileType) -> Option<SpecialKind> {
    use std::os::unix::fs::FileTypeExt;
    if ft.is_socket() {
        Some(SpecialKind::Socket)
    } else if ft.is_fifo() {
        Some(SpecialKind::Fifo)
    } else {
        None
    }
}

/// Windows has no socket or FIFO file type that std can name; every special stays refused.
#[cfg(not(unix))]
fn special_kind(_ft: &fs::FileType) -> Option<SpecialKind> {
    None
}

#[cfg(windows)]
fn link_is_dir(ft: &fs::FileType) -> bool {
    use std::os::windows::fs::FileTypeExt;
    ft.is_symlink_dir()
}

#[cfg(not(windows))]
fn link_is_dir(_ft: &fs::FileType) -> bool {
    false
}

#[cfg(windows)]
fn link_kind_matches(ft: &fs::FileType, dir: bool) -> bool {
    use std::os::windows::fs::FileTypeExt;
    ft.is_symlink_dir() == dir
}

#[cfg(not(windows))]
fn link_kind_matches(_ft: &fs::FileType, _dir: bool) -> bool {
    true
}

/// The text to write for the link at `rel` whose old target text is `target`, and whether it was
/// rewritten. A target with a root or prefix is absolute and copied as it is. A relative target
/// that never climbs above the tree root keeps its text. A relative target that does climb out is
/// resolved lexically against the link's old location (`csrc/<parent of rel>`) and written as an
/// absolute path, so it keeps pointing at the original target. A target that leaves the tree and
/// comes back (`../<tree name>/x`) counts as leaving: the same text would mean something else
/// under the new root.
fn plan_link(csrc: &Path, rel: &Path, target: &Path) -> (PathBuf, bool) {
    if target
        .components()
        .any(|c| matches!(c, Component::Prefix(_) | Component::RootDir))
    {
        return (target.to_path_buf(), false);
    }
    let parent_rel = rel.parent().unwrap_or_else(|| Path::new(""));
    let mut depth = parent_rel.components().count();
    let mut inside = true;
    let mut abs = csrc.to_path_buf();
    if depth > 0 {
        abs.push(parent_rel);
    }
    for c in target.components() {
        match c {
            Component::Normal(n) => {
                abs.push(n);
                depth += 1;
            }
            Component::ParentDir => {
                if depth == 0 {
                    inside = false;
                } else {
                    depth -= 1;
                }
                abs.pop();
            }
            _ => {}
        }
    }
    if inside {
        (target.to_path_buf(), false)
    } else {
        (strip_verbatim(abs), true)
    }
}

/// `\\?\C:\x` becomes `C:\x` and `\\?\UNC\h\s` becomes `\\h\s`, so a rewritten link is a plain
/// path. Other platforms and other forms are returned unchanged.
#[cfg(windows)]
fn strip_verbatim(p: PathBuf) -> PathBuf {
    let s = p.to_string_lossy().into_owned();
    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
        PathBuf::from(format!(r"\\{rest}"))
    } else if let Some(rest) = s.strip_prefix(r"\\?\") {
        if rest.len() >= 2 && rest.as_bytes()[1] == b':' {
            return PathBuf::from(rest);
        }
        p
    } else {
        p
    }
}

#[cfg(not(windows))]
fn strip_verbatim(p: PathBuf) -> PathBuf {
    p
}

/// Whether two link target texts name the same target. Exact on Unix. On Windows the stored text
/// may come back with `/` as `\`, a verbatim prefix or another case, so those are normalised.
fn same_link_target(a: &Path, b: &Path) -> bool {
    if a == b {
        return true;
    }
    #[cfg(windows)]
    {
        fn norm(p: &Path) -> String {
            let s = p.to_string_lossy().replace('/', "\\");
            let s = s
                .strip_prefix(r"\\?\UNC\")
                .map(|r| format!(r"\\{r}"))
                .or_else(|| s.strip_prefix(r"\\?\").map(str::to_string))
                .or_else(|| s.strip_prefix(r"\??\").map(str::to_string))
                .unwrap_or(s);
            s.to_lowercase()
        }
        norm(a) == norm(b)
    }
    #[cfg(not(windows))]
    {
        false
    }
}

/// Create a symlink at `to` pointing at `target`. `dir` selects `symlink_dir` on Windows.
fn make_link(target: &Path, to: &Path, dir: bool) -> io::Result<()> {
    #[cfg(unix)]
    {
        let _ = dir;
        std::os::unix::fs::symlink(target, to)
    }
    #[cfg(windows)]
    {
        if dir {
            std::os::windows::fs::symlink_dir(target, to)
        } else {
            std::os::windows::fs::symlink_file(target, to)
        }
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = (target, to, dir);
        Err(io::Error::from(io::ErrorKind::Unsupported))
    }
}

/// Whether a link-creation error means the destination cannot hold links (Windows without
/// SeCreateSymbolicLink or Developer Mode; a filesystem without symlinks) rather than a fault
/// that should surface as plain I/O. On Windows every error except `AlreadyExists` counts.
fn link_unavailable(e: &io::Error) -> bool {
    #[cfg(windows)]
    {
        e.kind() != io::ErrorKind::AlreadyExists
    }
    #[cfg(not(windows))]
    {
        matches!(
            e.kind(),
            io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
        )
    }
}

fn lossy(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

fn links_json(links: &[MigratedLink]) -> serde_json::Value {
    serde_json::Value::Array(
        links
            .iter()
            .map(|l| {
                serde_json::json!({
                    "path": lossy(&l.path),
                    "original_target": lossy(&l.original_target),
                    "written_target": lossy(&l.written_target),
                    "rewritten": l.rewritten,
                })
            })
            .collect(),
    )
}

fn specials_json(specials: &[SkippedSpecial]) -> serde_json::Value {
    serde_json::Value::Array(
        specials
            .iter()
            .map(|s| serde_json::json!({"path": lossy(&s.path), "kind": s.kind.as_str()}))
            .collect(),
    )
}

fn omitted_json(omitted: &[OmittedLink]) -> serde_json::Value {
    serde_json::Value::Array(
        omitted
            .iter()
            .map(|o| {
                serde_json::json!({
                    "path": lossy(&o.path),
                    "original_target": lossy(&o.original_target),
                    "resolved_target": lossy(&o.resolved_target),
                    "reason": o.reason,
                })
            })
            .collect(),
    )
}

fn reparse_json(reparse: &[SkippedReparsePoint]) -> serde_json::Value {
    serde_json::Value::Array(
        reparse
            .iter()
            .map(|r| {
                serde_json::json!({
                    "path": lossy(&r.path),
                    "kind": r.kind.as_str(),
                    "tag": r.tag,
                    "reason": r.reason,
                })
            })
            .collect(),
    )
}

/// The historical commit marker body, written only for a `Ready` migration. A strict migration
/// writes exactly the historical shape (`source`, `files`, `bytes`); an opt-in one adds `links`,
/// `skipped_specials`, `omitted_optional_links` and `complete`. Readers of the old shape look only
/// at `source`, so both shapes stay readable by both versions. (`omitted_optional_links` is
/// empty and `complete` true whenever the real flow writes it; the completion state with
/// omissions lives in the state file.)
fn marker_json(
    source: Option<&str>,
    files: u64,
    bytes: u64,
    opts: &MigrateOptions,
    links: &[MigratedLink],
    specials: &[SkippedSpecial],
    omitted: &[OmittedLink],
) -> serde_json::Value {
    let mut body = serde_json::json!({
        "source": source,
        "files": files,
        "bytes": bytes,
    });
    if opts.is_strict() {
        return body;
    }
    let obj = body.as_object_mut().expect("object");
    obj.insert("links".into(), links_json(links));
    obj.insert("skipped_specials".into(), specials_json(specials));
    obj.insert("omitted_optional_links".into(), omitted_json(omitted));
    obj.insert(
        "complete".into(),
        serde_json::Value::Bool(omitted.is_empty()),
    );
    body
}

/// The versioned state file body (see [`MIGRATION_STATE`]): `version`, `state`, `source`, the
/// counts, every list, and `unresolved` (the omitted links and skipped reparse points, with their
/// reasons). `error` is the reason an `Incomplete` run stopped, when it stopped on one.
fn state_json(
    state: MigrationState,
    source: Option<&str>,
    l: &Lists,
    error: Option<&str>,
) -> serde_json::Value {
    let mut unresolved: Vec<serde_json::Value> = l
        .omitted
        .iter()
        .map(|o| serde_json::json!({"path": lossy(&o.path), "kind": "link", "reason": o.reason}))
        .collect();
    unresolved.extend(l.reparse.iter().map(|r| {
        serde_json::json!({"path": lossy(&r.path), "kind": "reparse_point", "reason": r.reason})
    }));
    let mut body = serde_json::json!({
        "version": STATE_VERSION,
        "state": state.as_str(),
        "source": source,
        "files": l.files,
        "bytes": l.bytes,
        "links": links_json(&l.links),
        "skipped_specials": specials_json(&l.specials),
        "omitted_optional_links": omitted_json(&l.omitted),
        "skipped_reparse_points": reparse_json(&l.reparse),
        "unresolved": unresolved,
    });
    if let (Some(e), Some(obj)) = (error, body.as_object_mut()) {
        obj.insert("error".into(), e.into());
    }
    body
}

/// Publish a copy without replacing a contender. An equal regular file permits a retry.
fn commit_migration_file(
    writer: AtomicWriter,
    source: &Path,
    target: &Path,
) -> Result<(), AppRootError> {
    match writer.commit() {
        Ok(()) => Ok(()),
        Err(FsError::AlreadyExists(_)) => {
            if regular_entry(&fs::symlink_metadata(target)?) && same_content(source, target)? {
                Ok(())
            } else {
                Err(AppRootError::Collision(target.to_path_buf()))
            }
        }
        Err(e) => Err(io::Error::other(e).into()),
    }
}

fn regular_entry(metadata: &fs::Metadata) -> bool {
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        if metadata.file_attributes() & 0x400 != 0 {
            return false;
        }
    }
    metadata.file_type().is_file()
}

/// The migration owns these regular metadata leaves, never a link or special file.
/// Returns whether a validated target already exists.
fn validate_metadata_target(path: &Path) -> io::Result<bool> {
    match fs::symlink_metadata(path) {
        Ok(m) if regular_entry(&m) => Ok(true),
        Ok(_) => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "migration metadata is not a regular file: {}",
                path.display()
            ),
        )),
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e),
    }
}

/// Write owned metadata through exclusive staging; never open a fixed temporary name.
pub(crate) fn write_json_atomic(path: &Path, body: &serde_json::Value) -> io::Result<()> {
    let replacing = validate_metadata_target(path)?;
    let mut writer = AtomicWriter::create_with(
        path,
        AtomicWriteOptions {
            private: true,
            replace: if replacing {
                ReplaceMode::Rename
            } else {
                ReplaceMode::NoReplace
            },
            ..Default::default()
        },
    )
    .map_err(io::Error::other)?;
    writer
        .write_all(body.to_string().as_bytes())
        .map_err(io::Error::other)?;
    writer
        .commit_checked(|_| validate_metadata_target(path).map(|_| ()))
        .map_err(io::Error::other)
}

/// Whether `to` is a link (never followed) with the written target text and, on Windows, the
/// right file or directory kind.
fn link_ok(to: &Path, written: &Path, dir: bool) -> bool {
    match fs::symlink_metadata(to) {
        Ok(m) => {
            m.file_type().is_symlink()
                && fs::read_link(to).is_ok_and(|t| same_link_target(&t, written))
                && link_kind_matches(&m.file_type(), dir)
        }
        Err(_) => false,
    }
}

/// Byte-for-byte equality (stronger than a digest compare).
pub(crate) fn same_content(a: &Path, b: &Path) -> Result<bool, AppRootError> {
    let mut fa = rightkit_fs::open_read_nofollow(a, &rightkit_fs::ReadOptions::new())
        .map_err(io::Error::other)?;
    let mut fb = rightkit_fs::open_read_nofollow(b, &rightkit_fs::ReadOptions::new())
        .map_err(io::Error::other)?;
    if fa.metadata()?.len() != fb.metadata()?.len() {
        return Ok(false);
    }
    let (mut ba, mut bb) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]);
    loop {
        let na = read_full(&mut fa, &mut ba)?;
        let nb = read_full(&mut fb, &mut bb)?;
        if na != nb || ba[..na] != bb[..nb] {
            return Ok(false);
        }
        if na == 0 {
            return Ok(true);
        }
    }
}

fn read_full(f: &mut File, buf: &mut [u8]) -> io::Result<usize> {
    let mut n = 0;
    while n < buf.len() {
        match f.read(&mut buf[n..])? {
            0 => break,
            k => n += k,
        }
    }
    Ok(n)
}

/// Do two canonical directory paths name one directory? Unix: the same device and inode.
/// Windows: the same path ignoring ASCII case (the canonical form resolves links and `..`).
fn same_directory(a: &Path, b: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        match (fs::metadata(a), fs::metadata(b)) {
            (Ok(x), Ok(y)) => x.dev() == y.dev() && x.ino() == y.ino(),
            _ => false,
        }
    }
    #[cfg(not(unix))]
    {
        a.to_string_lossy()
            .eq_ignore_ascii_case(&b.to_string_lossy())
    }
}