text-mirror 0.6.0

Converts binary and rich files into text and builds a replica text-mirror tree beside a manifest recording the source, hash, and converter behind every artifact
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
//! The end-to-end pipeline behind the CLI verbs.
//!
//! `run` is incremental and idempotent. The manifest is the
//! checkpoint. A prior terminal record whose key of source path,
//! source hash, converter version, and rules version matches the
//! current pass, and whose artifact still hashes to the recorded
//! text hash, becomes a `skipped_unchanged` record with no work done.
//! Failed and unsupported sources are re-evaluated every run, so their
//! terminal records keep the current reason and the enumerated
//! remainder stays visible.
//!
//! Per-source problems, meaning IO errors, converter errors, and
//! mirror write failures, become `failed` records and the run
//! continues. Only run-level problems abort: a walk failure, a rules
//! failure, an invalid layout, or a manifest open or append failure.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;

use crate::convert::{self, Registry};
use crate::detect::{self, Detection, FormatTable, UNKNOWN_FORMAT};
use crate::hash::{self, CanonicalArtifact, DedupIndex};
use crate::manifest::{self, ArtifactKind, ManifestSchema, ManifestWriter, Record, Status};
use crate::mirror;
use crate::report::{
    DivisionStatus, ExplainEntry, FormatCount, RunReport, ScanReport, SizeOutlier, StatusCounts,
    StatusReport,
};
use crate::segments;
use crate::walk::{self, EntryKind, WalkOptions};
use crate::{Error, Result};

/// The detected format recorded for a symlink entry.
pub const SYMLINK_FORMAT: &str = "symlink";

/// The detected format recorded in scan output for FIFOs and sockets.
pub const SPECIAL_FORMAT: &str = "special";

/// The rules files loaded for one run.
///
/// The format table and the converter registry must declare the same
/// version. That shared version is recorded in every record as
/// `rules_version`.
pub struct Rules {
    /// The format table from `rules/formats.toml`.
    pub table: FormatTable,
    /// The converter registry from `rules/converters.toml`.
    pub registry: Registry,
}

impl Rules {
    /// The rules compiled into the binary.
    pub fn builtin() -> Result<Self> {
        let table = FormatTable::builtin()?;
        let registry = Registry::builtin()?;
        if table.version() != registry.version() {
            return Err(Error::Rules {
                name: "rules".to_string(),
                message: format!(
                    "formats.toml version {:?} does not match converters.toml version {:?}",
                    table.version(),
                    registry.version()
                ),
            });
        }
        Ok(Rules { table, registry })
    }

    /// The shared rules version.
    pub fn version(&self) -> &str {
        self.table.version()
    }
}

/// Options for one conversion run.
pub struct RunOptions<'a> {
    /// The division root to walk.
    pub root: &'a Path,
    /// The mirror tree root.
    pub mirror_root: &'a Path,
    /// The directory holding manifest shards.
    pub manifest_dir: &'a Path,
    /// The division name, also the shard file stem.
    pub division: &'a str,
    /// Traversal options.
    pub walk: WalkOptions,
}

/// Inventories a division root without converting anything.
///
/// A file is a size outlier when it is at least 1 MiB and at least ten
/// times the mean file size of the tree. Symlinks appear under the
/// `symlink` format and FIFOs and sockets under `special`.
pub fn scan(root: &Path, rules: &Rules, options: &WalkOptions) -> Result<ScanReport> {
    let entries = walk::walk_division(root, options)?;
    let mut inventory: Vec<(String, u64, String)> = Vec::new();
    for entry in &entries {
        let absolute = root.join(&entry.path);
        let (size, format) = match entry.kind {
            EntryKind::File => {
                let size = absolute
                    .metadata()
                    .map_err(|e| Error::io("stat", &absolute, e))?
                    .len();
                let detection = detect::detect_file(&absolute, &rules.table)?;
                (size, detection.detected)
            }
            EntryKind::Symlink => {
                let size = fs::symlink_metadata(&absolute)
                    .map_err(|e| Error::io("stat", &absolute, e))?
                    .len();
                (size, SYMLINK_FORMAT.to_string())
            }
            EntryKind::Other => (0, SPECIAL_FORMAT.to_string()),
        };
        inventory.push((entry.path.to_string_lossy().into_owned(), size, format));
    }

    let mut by_format: BTreeMap<String, (u64, u64)> = BTreeMap::new();
    let mut total_bytes = 0u64;
    for (_, size, format) in &inventory {
        let entry = by_format.entry(format.clone()).or_insert((0, 0));
        entry.0 += 1;
        entry.1 += size;
        total_bytes += size;
    }

    let mean = if inventory.is_empty() {
        0.0
    } else {
        total_bytes as f64 / inventory.len() as f64
    };
    let mut outliers: Vec<SizeOutlier> = inventory
        .iter()
        .filter(|(_, size, _)| *size >= 1_048_576 && *size as f64 >= 10.0 * mean)
        .map(|(path, size, format)| SizeOutlier {
            path: path.clone(),
            bytes: *size,
            format: format.clone(),
        })
        .collect();
    outliers.sort_by(|a, b| b.bytes.cmp(&a.bytes).then(a.path.cmp(&b.path)));

    Ok(ScanReport {
        root: root.display().to_string(),
        rules_version: rules.version().to_string(),
        files: inventory.len() as u64,
        bytes: total_bytes,
        formats: by_format
            .into_iter()
            .map(|(format, (files, bytes))| FormatCount {
                format,
                files,
                bytes,
            })
            .collect(),
        outliers,
    })
}

pub(crate) fn validate_division(name: &str) -> Result<()> {
    let usable = !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if usable {
        Ok(())
    } else {
        Err(Error::Division {
            name: name.to_string(),
        })
    }
}

/// Resolves a path for containment checks without creating anything.
///
/// Existing prefixes canonicalize, so symlinks resolve. Components
/// past the first missing one cannot be symlinks, so they resolve
/// lexically, and a parent component pops a base that is already
/// symlink-free.
fn resolve_for_check(path: &Path) -> Result<PathBuf> {
    use std::path::Component;
    let absolute = std::path::absolute(path).map_err(|e| Error::io("absolutize", path, e))?;
    let mut resolved = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::Prefix(_) | Component::RootDir => resolved.push(component),
            Component::CurDir => {}
            Component::ParentDir => {
                resolved.pop();
            }
            Component::Normal(name) => {
                resolved.push(name);
                if let Ok(canonical) = resolved.canonicalize() {
                    resolved = canonical;
                }
            }
        }
    }
    Ok(resolved)
}

/// Refuses a layout that nests the division root and an output root
/// either way, so outputs can never become next-run sources and
/// artifacts can never land inside the source tree.
///
/// Every path resolves without touching the filesystem state, and the
/// output directories are created only after the layout is approved,
/// so a refusal leaves the division root untouched.
fn check_layout(root: &Path, mirror_root: &Path, manifest_dir: &Path) -> Result<()> {
    let root_resolved = resolve_for_check(root)?;
    for (name, dir) in [
        ("mirror root", mirror_root),
        ("manifest directory", manifest_dir),
    ] {
        let dir_resolved = resolve_for_check(dir)?;
        if dir_resolved.starts_with(&root_resolved) {
            return Err(Error::Layout {
                message: format!(
                    "{name} {} lies inside the division root {}",
                    dir.display(),
                    root.display()
                ),
            });
        }
        if root_resolved.starts_with(&dir_resolved) {
            return Err(Error::Layout {
                message: format!(
                    "division root {} lies inside the {name} {}",
                    root.display(),
                    dir.display()
                ),
            });
        }
    }
    fs::create_dir_all(mirror_root).map_err(|e| Error::io("create_dir", mirror_root, e))?;
    fs::create_dir_all(manifest_dir).map_err(|e| Error::io("create_dir", manifest_dir, e))?;
    Ok(())
}

fn new_record(
    source_path: &str,
    source_hash: &str,
    source_size: u64,
    detection: &Detection,
    rules_version: &str,
    status: Status,
) -> Record {
    Record {
        schema: ManifestSchema,
        source_path: source_path.to_string(),
        source_hash: source_hash.to_string(),
        source_size,
        declared_format: detection.declared.clone(),
        detected_format: detection.detected.clone(),
        format_mismatch: detection.mismatch,
        status,
        text_path: None,
        text_hash: None,
        artifact_kind: None,
        converter_id: None,
        converter_version: None,
        tool_version: None,
        rules_version: rules_version.to_string(),
        media: None,
        parent_source: None,
        dedup_of: None,
        warnings: Vec::new(),
        error: None,
        duration_ms: None,
    }
}

fn elapsed_ms(started: Instant) -> u64 {
    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

fn terminal_by_path(records: Vec<Record>) -> HashMap<String, Record> {
    let mut terminal = HashMap::new();
    for record in records {
        terminal.insert(record.source_path.clone(), record);
    }
    terminal
}

/// Seeds the dedup index from prior terminal records.
///
/// Only records whose converter version and rules version match the
/// current run are eligible, so a rules bump never propagates stale
/// artifacts. Candidates are visited sorted by source path, and the
/// first insert per hash wins, so the canonical choice is
/// deterministic.
fn seed_dedup(terminal: &HashMap<String, Record>, rules: &Rules, dedup: &mut DedupIndex) {
    let mut candidates: Vec<&Record> = terminal.values().collect();
    candidates.sort_by(|a, b| a.source_path.cmp(&b.source_path));
    for record in candidates {
        let canonical_status = record.status == Status::Converted
            || (record.status == Status::SkippedUnchanged && record.dedup_of.is_none());
        if !canonical_status || record.rules_version != rules.version() {
            continue;
        }
        let (Some(text_path), Some(text_hash), Some(converter_id), Some(converter_version)) = (
            &record.text_path,
            &record.text_hash,
            &record.converter_id,
            &record.converter_version,
        ) else {
            continue;
        };
        let current = rules.registry.converter_for(&record.detected_format);
        let versions_match =
            current.is_some_and(|c| c.id() == converter_id && c.version() == converter_version);
        if !versions_match {
            continue;
        }
        dedup.insert(
            &record.source_hash,
            CanonicalArtifact {
                source_path: record.source_path.clone(),
                text_path: text_path.clone(),
                text_hash: text_hash.clone(),
                converter_id: converter_id.clone(),
                converter_version: converter_version.clone(),
                artifact_kind: record.artifact_kind,
                warnings: record.warnings.clone(),
            },
        );
    }
}

fn record_outcome(
    writer: &mut ManifestWriter,
    terminal: &mut HashMap<String, Record>,
    counts: &mut StatusCounts,
    record: Record,
) -> Result<()> {
    writer.append(&record)?;
    match record.status {
        Status::Converted => counts.converted += 1,
        Status::Failed => counts.failed += 1,
        Status::Unsupported => counts.unsupported += 1,
        Status::SkippedUnchanged => counts.skipped_unchanged += 1,
        Status::Dedup => counts.dedup += 1,
    }
    terminal.insert(record.source_path.clone(), record);
    Ok(())
}

/// Removes any artifact and segments file left behind for a source
/// whose terminal outcome carries no text, so the mirror never
/// contradicts the manifest.
fn remove_stale_artifact(text_absolute: &Path, segments_absolute: &Path, record: &mut Record) {
    for stale in [text_absolute, segments_absolute] {
        match fs::remove_file(stale) {
            Ok(()) => {}
            Err(e)
                if e.kind() == std::io::ErrorKind::NotFound
                    || e.kind() == std::io::ErrorKind::NotADirectory => {}
            Err(e) => record
                .warnings
                .push(format!("stale_artifact_not_removed: {e}")),
        }
    }
}

/// True when an artifact and its sidecar still match the recorded
/// hash: the text bytes hash to `text_hash` and the sidecar parses as
/// segments@1 and validates against the text.
fn envelope_intact(artifact: &Path, text_hash: &str, segments_path: &Path) -> bool {
    let Ok(text) = fs::read_to_string(artifact) else {
        return false;
    };
    if hash::hash_bytes(text.as_bytes()) != text_hash {
        return false;
    }
    let Ok(sidecar) = fs::read_to_string(segments_path) else {
        return false;
    };
    segments::parse_jsonl(&sidecar).is_ok_and(|segs| segments::validate(&segs, &text).is_ok())
}

fn source_front(
    absolute: &Path,
    table: &FormatTable,
) -> Result<(String, u64, Detection, Vec<String>)> {
    let source_hash = hash::hash_file(absolute)?;
    let source_size = absolute
        .metadata()
        .map_err(|e| Error::io("stat", absolute, e))?
        .len();
    let (detection, warnings) = detect::detect_file_with_warnings(absolute, table)?;
    Ok((source_hash, source_size, detection, warnings))
}

/// Identity of one source, container child or top-level file alike.
struct Meta {
    source_path: String,
    parent_source: Option<String>,
    source_hash: String,
    source_size: u64,
    detection: Detection,
    detect_warnings: Vec<String>,
}

/// Where a unit's bytes come from. A top-level file reads from disk
/// after the skip and dedup decisions, so an unchanged file never
/// pays a second read. A container member already holds its bytes.
enum UnitBytes {
    Disk(PathBuf),
    Mem(Vec<u8>),
}

impl UnitBytes {
    fn load(self, expected_hash: &str) -> std::result::Result<Vec<u8>, String> {
        match self {
            UnitBytes::Mem(bytes) => Ok(bytes),
            UnitBytes::Disk(path) => {
                let bytes = fs::read(&path).map_err(|e| format!("source_io_error: read: {e}"))?;
                if hash::hash_bytes(&bytes) != expected_hash {
                    return Err(
                        "source_changed_during_run: bytes changed between hash and conversion"
                            .to_string(),
                    );
                }
                Ok(bytes)
            }
        }
    }
}

/// One unit of conversion work: a top-level source or a container
/// member.
struct Unit {
    meta: Meta,
    bytes: UnitBytes,
    depth: usize,
    /// Container hashes on this unit's chain, for the quine guard.
    ancestors: Vec<String>,
}

/// Which container family a detected format belongs to, if any.
enum ContainerKind {
    Zip,
    Eml,
}

/// True when a container member's hash repeats a container already on
/// its chain, which is the zip-quine signature. Kills a quine before
/// it spends the depth budget.
fn hash_on_chain(hash: &str, ancestors: &[String]) -> bool {
    ancestors.iter().any(|ancestor| ancestor == hash)
}

/// Case-folded, NFC-normalized key for a child source path, so two
/// members whose paths differ only by case or Unicode form collide.
fn collision_key(source_path: &str) -> String {
    use unicode_normalization::UnicodeNormalization;
    source_path.nfc().collect::<String>().to_lowercase()
}

/// The synthetic derived-child path an image's metadata leg writes to.
fn metadata_child_path(source_path: &str) -> String {
    format!("{source_path}.d/#image-metadata")
}

/// The claimed-path state for one top-level container's whole
/// expansion, so members cannot alias each other's paths and a
/// re-expansion can retire the descendants a shrunken member set
/// dropped.
struct ClaimState {
    /// `<container>.d/`, the namespace every descendant path begins
    /// with.
    prefix: String,
    /// Collision keys already claimed this expansion.
    claimed: std::collections::HashSet<String>,
    /// Actual descendant source paths recorded this expansion.
    emitted: std::collections::HashSet<String>,
    /// Counter for synthetic collision-child paths.
    collisions: usize,
}

/// Reason recorded when a re-expanded container no longer holds a
/// member its prior manifest still named.
const REMOVED_MEMBER_REASON: &str = "container-member-removed";

fn container_kind(detected: &str) -> Option<ContainerKind> {
    match detected {
        "zip" => Some(ContainerKind::Zip),
        "eml" => Some(ContainerKind::Eml),
        _ => None,
    }
}

/// Shared run state for the recursive conversion of one division.
struct Expander<'a> {
    rules: &'a Rules,
    mirror_root: &'a Path,
    division: &'a str,
    walked: &'a std::collections::HashSet<String>,
    limits: &'a convert::ContainerLimits,
    writer: &'a mut ManifestWriter,
    terminal: &'a mut HashMap<String, Record>,
    counts: &'a mut StatusCounts,
    dedup: &'a mut DedupIndex,
    /// Set while a top-level container expands, tracking claimed and
    /// emitted descendant paths for aliasing and reconciliation.
    claim: Option<ClaimState>,
}

impl Expander<'_> {
    fn artifact_paths(&self, source_path: &str) -> (PathBuf, PathBuf, String) {
        let relative = Path::new(source_path);
        (
            mirror::mirror_path(self.mirror_root, self.division, relative),
            segments::segments_path(self.mirror_root, self.division, relative),
            mirror::recorded_text_path(self.division, source_path),
        )
    }

    fn emit(&mut self, record: Record) -> Result<()> {
        if let Some(claim) = &mut self.claim
            && record.source_path.starts_with(&claim.prefix)
        {
            claim.emitted.insert(record.source_path.clone());
        }
        record_outcome(self.writer, self.terminal, self.counts, record)
    }

    fn base_record(&self, meta: &Meta, status: Status) -> Record {
        let mut record = new_record(
            &meta.source_path,
            &meta.source_hash,
            meta.source_size,
            &meta.detection,
            self.rules.version(),
            status,
        );
        record.parent_source.clone_from(&meta.parent_source);
        record.warnings.clone_from(&meta.detect_warnings);
        record
    }

    /// Emits a failed record for a whole unit and clears any stale
    /// artifact.
    fn fail(&mut self, meta: &Meta, reason: String, started: Instant) -> Result<()> {
        let (text_absolute, segments_absolute, _) = self.artifact_paths(&meta.source_path);
        let mut record = self.base_record(meta, Status::Failed);
        record.error = Some(reason);
        record.duration_ms = Some(elapsed_ms(started));
        remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
        self.emit(record)
    }

    /// True when a real walked source already occupies this
    /// container's expansion namespace, which would collide two
    /// artifacts on one mirror path.
    fn expansion_collides(&self, source_path: &str) -> bool {
        let prefix = format!("{source_path}.d/");
        self.walked.iter().any(|walked| walked.starts_with(&prefix))
    }

    /// Processes one unit: checkpoint, dedup, then conversion or
    /// container expansion, appending one record per source.
    fn process(&mut self, unit: Unit, started: Instant, expanded: &mut u64) -> Result<()> {
        let Unit {
            meta,
            bytes,
            depth,
            ancestors,
        } = unit;
        let (text_absolute, segments_absolute, text_relative) =
            self.artifact_paths(&meta.source_path);
        let kind = container_kind(&meta.detection.detected);
        let converter = self.rules.registry.converter_for(&meta.detection.detected);
        let current_version = match kind {
            Some(ContainerKind::Zip) => Some(convert::CONTAINER_ZIP_VERSION),
            _ => converter.map(|c| c.version()),
        };

        // An image carrier whose metadata leg runs owns a derived child
        // the way a container owns members: the checkpoint and dedup
        // decisions below account for that child.
        let metadata_leg = self.metadata_leg_applies(&meta.detection.detected);
        let has_children = kind.is_some() || metadata_leg;

        // Checkpoint: an unchanged source with an intact artifact
        // skips, containers included. A skipped container leaves its
        // children untouched, and their prior records stay terminal.
        if let Some(previous) = self.terminal.get(&meta.source_path) {
            let key_matches = previous.source_hash == meta.source_hash
                && previous.rules_version == self.rules.version()
                && previous.converter_version.as_deref() == current_version;
            let has_text = matches!(
                previous.status,
                Status::Converted | Status::Dedup | Status::SkippedUnchanged
            );
            // A prior record from a build without the metadata converter
            // never had its metadata leg run. Once the converter is
            // present that record is not skippable, so the child is
            // minted on the first build that can produce it.
            let leg_never_ran = metadata_leg
                && previous
                    .warnings
                    .iter()
                    .any(|w| w == convert::image_metadata::IMAGE_METADATA_NOT_BUILT);
            if key_matches && has_text && !leg_never_ran {
                let intact = match (&previous.text_path, &previous.text_hash) {
                    (Some(text_path), Some(text_hash)) => {
                        mirror::resolve_recorded_path(self.mirror_root, text_path).is_ok_and(
                            |artifact| envelope_intact(&artifact, text_hash, &segments_absolute),
                        )
                    }
                    _ => false,
                };
                // A container's members, and an image's metadata child,
                // are reachable only through their parent, so an intact
                // parent envelope is not enough: every text-bearing
                // descendant must still hash to its record, or the
                // parent re-runs.
                let descendants_ok = !has_children || self.descendants_intact(&meta.source_path);
                if intact && descendants_ok {
                    // A nested container, or an image carrier, that
                    // skips inside a re-expanding parent just validated
                    // its whole subtree intact, so every prior descendant
                    // under it is kept: the owner's reconciliation must
                    // not retire them as removed. A kept metadata child
                    // also keeps its claim on its path, so a later
                    // literal member cannot write over it.
                    if has_children && self.claim.is_some() {
                        let prefix = format!("{}.d/", meta.source_path);
                        let kept: Vec<String> = self
                            .terminal
                            .keys()
                            .filter(|path| path.starts_with(&prefix))
                            .cloned()
                            .collect();
                        if let Some(claim) = &mut self.claim {
                            if metadata_leg {
                                for path in &kept {
                                    claim.claimed.insert(collision_key(path));
                                }
                            }
                            claim.emitted.extend(kept);
                        }
                    }
                    let mut record = previous.clone();
                    record.status = Status::SkippedUnchanged;
                    record.error = None;
                    record.duration_ms = Some(elapsed_ms(started));
                    return self.emit(record);
                }
            }
        }

        // Container guards, before any expansion. A container past the
        // depth cap or one whose bytes repeat an ancestor container is
        // a failed child, unexpanded.
        if kind.is_some() {
            if depth > self.limits.max_depth {
                return self.fail(&meta, "container-depth-exceeded".to_string(), started);
            }
            if hash_on_chain(&meta.source_hash, &ancestors) {
                return self.fail(&meta, "container-recursive".to_string(), started);
            }
        }

        // The source ceiling precedes every parent-side load. An image
        // whose metadata leg would load its bytes for the dedup borrow
        // is over the ceiling here, so it skips the borrow and falls
        // through to the leaf path, which records the resource-limit
        // failure with no child, exactly as an unborrowed image would.
        let over_ceiling = meta.source_size > convert::MAX_SOURCE_BYTES;

        // Dedup borrow, non-containers only. A container never dedups,
        // because borrowing its artifact would skip re-expanding its
        // members under their own paths.
        if kind.is_none()
            && !(metadata_leg && over_ceiling)
            && let Some(canonical) = self.dedup.get(&meta.source_hash)
            && canonical.source_path != meta.source_path
            && converter.is_some_and(|c| {
                c.id() == canonical.converter_id && c.version() == canonical.converter_version
            })
        {
            let canonical = canonical.clone();
            let canonical_segments = segments::segments_path(
                self.mirror_root,
                self.division,
                Path::new(&canonical.source_path),
            );
            if let Ok(canonical_text) =
                mirror::resolve_recorded_path(self.mirror_root, &canonical.text_path)
                && let (Ok(text), Ok(segment_lines)) = (
                    fs::read_to_string(&canonical_text),
                    fs::read_to_string(&canonical_segments),
                )
                && hash::hash_bytes(text.as_bytes()) == canonical.text_hash
                && segments::parse_jsonl(&segment_lines)
                    .is_ok_and(|segs| segments::validate(&segs, &text).is_ok())
            {
                // The metadata leg still runs for a borrowed primary:
                // the bytes are identical by hash, the parse is cheap,
                // and the child belongs to this path. The bytes are
                // loaded here, before the record, so a load failure is
                // recorded the way the leaf path records it.
                #[cfg(all(unix, feature = "image-metadata"))]
                let raw = if metadata_leg {
                    match bytes.load(&meta.source_hash) {
                        Ok(raw) => Some(raw),
                        Err(reason) => return self.fail(&meta, reason, started),
                    }
                } else {
                    None
                };
                let mut meta = meta;
                let collides = metadata_leg && self.metadata_collides(&meta.source_path);
                if collides {
                    meta.detect_warnings.push(
                        convert::image_metadata::IMAGE_METADATA_NAMESPACE_OCCUPIED.to_string(),
                    );
                }
                let mut record = self.base_record(&meta, Status::Dedup);
                for warning in &canonical.warnings {
                    if !record.warnings.contains(warning) {
                        record.warnings.push(warning.clone());
                    }
                }
                match mirror::write_atomic(&text_absolute, &text)
                    .and_then(|()| mirror::write_atomic(&segments_absolute, &segment_lines))
                {
                    Ok(()) => {
                        record.text_path = Some(text_relative);
                        record.text_hash = Some(hash::hash_bytes(text.as_bytes()));
                        record.artifact_kind = canonical.artifact_kind;
                        record.converter_id = Some(canonical.converter_id.clone());
                        record.converter_version = Some(canonical.converter_version.clone());
                        record.dedup_of = Some(canonical.source_path.clone());
                    }
                    Err(e) => {
                        record.status = Status::Failed;
                        record.error = Some(format!("mirror_write_error: {e}"));
                        remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                    }
                }
                record.duration_ms = Some(elapsed_ms(started));
                self.emit(record)?;
                #[cfg(all(unix, feature = "image-metadata"))]
                if let Some(raw) = raw
                    && !collides
                {
                    let format = meta.detection.detected.clone();
                    let declared = meta.detection.declared.clone();
                    return self.run_metadata_leg(
                        &meta.source_path,
                        &format,
                        declared,
                        &meta.source_hash,
                        meta.source_size,
                        &raw,
                        started,
                    );
                }
                return Ok(());
            }
        }

        let Some(kind) = kind else {
            return self.convert_leaf_with_metadata(meta, bytes, started);
        };
        // A top-level container owns the claim state for its whole
        // subtree. Nested containers share the owner's state.
        let owns_claim = self.claim.is_none();
        if owns_claim {
            self.claim = Some(ClaimState {
                prefix: format!("{}.d/", meta.source_path),
                claimed: std::collections::HashSet::new(),
                emitted: std::collections::HashSet::new(),
                collisions: 0,
            });
        }
        let root = meta.source_path.clone();
        let result = match kind {
            ContainerKind::Zip => self.expand_zip(meta, bytes, depth, ancestors, started, expanded),
            ContainerKind::Eml => self.expand_eml(meta, bytes, depth, ancestors, started, expanded),
        };
        if owns_claim {
            // Reconcile even on a failure path, so a container that
            // failed whole still retires the descendants it no longer
            // holds and never leaves a partial expansion live.
            if let Some(claim) = self.claim.take() {
                self.reconcile(&root, &claim, started)?;
            }
        }
        result
    }

    /// True when every text-bearing descendant of a container still
    /// hashes to its recorded value on disk.
    fn descendants_intact(&self, root: &str) -> bool {
        let prefix = format!("{root}.d/");
        for record in self.terminal.values() {
            if !record.source_path.starts_with(&prefix) {
                continue;
            }
            if let (Some(text_path), Some(text_hash)) = (&record.text_path, &record.text_hash) {
                let segments_absolute = segments::segments_path(
                    self.mirror_root,
                    self.division,
                    Path::new(&record.source_path),
                );
                let ok = mirror::resolve_recorded_path(self.mirror_root, text_path).is_ok_and(
                    |artifact| envelope_intact(&artifact, text_hash, &segments_absolute),
                );
                if !ok {
                    return false;
                }
            }
        }
        true
    }

    /// Retires every prior descendant a re-expansion no longer holds
    /// with a terminal non-text record, and removes its artifact, so
    /// no removed member survives as a live converted record.
    fn reconcile(&mut self, root: &str, claim: &ClaimState, started: Instant) -> Result<()> {
        let stale: Vec<Record> = self
            .terminal
            .values()
            .filter(|record| {
                record.source_path.starts_with(&claim.prefix)
                    && !claim.emitted.contains(&record.source_path)
                    // An already-retired record stays retired, so the
                    // reconciliation reaches a fixpoint and does not
                    // re-emit a removed member every run.
                    && !(record.status == Status::Failed
                        && record.error.as_deref() == Some(REMOVED_MEMBER_REASON))
            })
            .cloned()
            .collect();
        let _ = root;
        for record in stale {
            let (text_absolute, segments_absolute, _) = self.artifact_paths(&record.source_path);
            let detection = Detection {
                declared: record.declared_format.clone(),
                detected: UNKNOWN_FORMAT.to_string(),
                mismatch: false,
            };
            let mut retire = new_record(
                &record.source_path,
                "",
                0,
                &detection,
                self.rules.version(),
                Status::Failed,
            );
            retire.parent_source.clone_from(&record.parent_source);
            retire.error = Some(REMOVED_MEMBER_REASON.to_string());
            retire.duration_ms = Some(elapsed_ms(started));
            remove_stale_artifact(&text_absolute, &segments_absolute, &mut retire);
            self.emit(retire)?;
        }
        Ok(())
    }

    /// The non-container conversion path: unsupported when no converter
    /// claims the format, else convert under the ceilings.
    fn convert_leaf(&mut self, meta: Meta, bytes: UnitBytes, started: Instant) -> Result<()> {
        let (text_absolute, segments_absolute, text_relative) =
            self.artifact_paths(&meta.source_path);
        let Some(converter) = self.rules.registry.converter_for(&meta.detection.detected) else {
            let mut record = self.base_record(&meta, Status::Unsupported);
            record.error = self
                .rules
                .registry
                .unsupported_reason(&meta.detection.detected)
                .map(str::to_string);
            record.duration_ms = Some(elapsed_ms(started));
            remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
            return self.emit(record);
        };
        let converter_id = converter.id().to_string();
        let converter_version = converter.version().to_string();

        let mut record = self.base_record(&meta, Status::Converted);
        let outcome = if meta.source_size > convert::MAX_SOURCE_BYTES {
            Err(format!(
                "resource_limit: source is {} bytes over the {} byte ceiling",
                meta.source_size,
                convert::MAX_SOURCE_BYTES
            ))
        } else {
            bytes
                .load(&meta.source_hash)
                .and_then(|bytes| run_converter(converter, &bytes, &meta.detection.detected))
        };
        match outcome {
            Ok(outcome) => match segments::to_jsonl(&outcome.segments)
                .map_err(|e| e.to_string())
                .and_then(|lines| {
                    mirror::write_atomic(&text_absolute, &outcome.text)
                        .and_then(|()| mirror::write_atomic(&segments_absolute, &lines))
                        .map_err(|e| e.to_string())
                }) {
                Ok(()) => {
                    let text_hash = hash::hash_bytes(outcome.text.as_bytes());
                    record.text_path = Some(text_relative.clone());
                    record.text_hash = Some(text_hash.clone());
                    record.artifact_kind = Some(outcome.artifact_kind);
                    record.converter_id = Some(outcome.converter_id.clone());
                    record.converter_version = Some(outcome.converter_version.clone());
                    record.warnings.extend(outcome.warnings.iter().cloned());
                    self.dedup.replace(
                        &meta.source_hash,
                        CanonicalArtifact {
                            source_path: meta.source_path.clone(),
                            text_path: text_relative,
                            text_hash,
                            converter_id: outcome.converter_id,
                            converter_version: outcome.converter_version,
                            artifact_kind: record.artifact_kind,
                            warnings: outcome.warnings,
                        },
                    );
                }
                Err(detail) => {
                    record.status = Status::Failed;
                    record.converter_id = Some(converter_id);
                    record.converter_version = Some(converter_version);
                    record.error = Some(format!("mirror_write_error: {detail}"));
                    remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                }
            },
            Err(reason) => {
                record.status = Status::Failed;
                record.converter_id = Some(converter_id);
                record.converter_version = Some(converter_version);
                record.error = Some(reason);
                remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
            }
        }
        record.duration_ms = Some(elapsed_ms(started));
        self.emit(record)
    }

    /// The leaf path plus, for an image carrier, the auxiliary
    /// metadata derived-child leg.
    ///
    /// The primary conversion is the unchanged leaf path. When the format
    /// is an image carrier and the metadata converter is built, one
    /// image source additionally yields a hidden metadata child at
    /// `<source>.d/#image-metadata`, structurally parallel to a container
    /// member. The two legs share nothing: a failure of the metadata
    /// child never touches the primary image record.
    fn convert_leaf_with_metadata(
        &mut self,
        mut meta: Meta,
        bytes: UnitBytes,
        started: Instant,
    ) -> Result<()> {
        #[cfg(all(unix, feature = "image-metadata"))]
        if self.metadata_leg_applies(&meta.detection.detected) {
            return self.convert_image_with_metadata(meta, bytes, started);
        }
        // An image carrier in a build without the metadata converter
        // records that its leg never ran, so a later build that carries
        // the converter does not skip this record as unchanged.
        if convert::image_metadata::image_metadata_applies(&meta.detection.detected) {
            meta.detect_warnings
                .push(convert::image_metadata::IMAGE_METADATA_NOT_BUILT.to_string());
        }
        self.convert_leaf(meta, bytes, started)
    }

    /// Whether the metadata derived-child leg runs for a detected
    /// format: the format is an image carrier and the build carries the
    /// converter.
    fn metadata_leg_applies(&self, format: &str) -> bool {
        #[cfg(all(unix, feature = "image-metadata"))]
        {
            convert::image_metadata::image_metadata_applies(format)
                && self.rules.registry.image_metadata_converter().is_some()
        }
        #[cfg(not(all(unix, feature = "image-metadata")))]
        {
            let _ = format;
            false
        }
    }

    /// Whether the metadata child of an image at `source_path` would
    /// collide with a real source, claiming the child path inside a
    /// container expansion as it checks.
    ///
    /// A real walked source in the image `.d/` namespace occupies it. So
    /// does a container member already claimed at the child path: the
    /// literal member came first, so the child yields to it. When the
    /// image comes first, the claim made here makes the later literal
    /// member the collision, so archive order never silently overwrites
    /// either artifact.
    fn metadata_collides(&mut self, source_path: &str) -> bool {
        let child_path = metadata_child_path(source_path);
        self.expansion_collides(source_path)
            || (self.claim.is_some()
                && !self
                    .claim
                    .as_mut()
                    .expect("checked above")
                    .claimed
                    .insert(collision_key(&child_path)))
    }

    /// Runs the primary OCR leg, then the metadata derived-child leg,
    /// for one image source, loading the bytes once for both.
    #[cfg(all(unix, feature = "image-metadata"))]
    fn convert_image_with_metadata(
        &mut self,
        mut meta: Meta,
        bytes: UnitBytes,
        started: Instant,
    ) -> Result<()> {
        // The source ceiling is checked before any load, exactly as the
        // leaf path checks it, so an over-ceiling source records the same
        // resource-limit failure there and no child is attempted.
        if meta.source_size > convert::MAX_SOURCE_BYTES {
            return self.convert_leaf(meta, bytes, started);
        }
        // Load once. A load error means the primary leg records it and no
        // metadata child is attempted, so route it through the leaf path.
        let raw = match bytes.load(&meta.source_hash) {
            Ok(raw) => raw,
            Err(reason) => return self.fail(&meta, reason, started),
        };
        // Collision guard on the image `.d/` namespace, before the primary
        // leg records, so the warning rides the parent image record. A
        // real walked source in the namespace means the metadata leg is
        // skipped rather than overwriting that source's artifact.
        let collides = self.metadata_collides(&meta.source_path);
        if collides {
            meta.detect_warnings
                .push(convert::image_metadata::IMAGE_METADATA_NAMESPACE_OCCUPIED.to_string());
        }
        let source_path = meta.source_path.clone();
        let format = meta.detection.detected.clone();
        let declared = meta.detection.declared.clone();
        let source_hash = meta.source_hash.clone();
        let source_size = meta.source_size;
        // The primary OCR leg is the unchanged leaf path. It emits the
        // parent image record, carrying the collision warning when set.
        self.convert_leaf(meta, UnitBytes::Mem(raw.clone()), started)?;
        if collides {
            return Ok(());
        }
        self.run_metadata_leg(
            &source_path,
            &format,
            declared,
            &source_hash,
            source_size,
            &raw,
            started,
        )
    }

    /// Runs the metadata child under the claim-and-reconcile machinery,
    /// so a re-run that finds no metadata retires a prior metadata child.
    ///
    /// A top-level image owns a claim over its own `.d/` namespace; an
    /// image that is itself a container member shares the owning
    /// container's claim, which already covers the child path.
    #[cfg(all(unix, feature = "image-metadata"))]
    #[allow(clippy::too_many_arguments)]
    fn run_metadata_leg(
        &mut self,
        source_path: &str,
        format: &str,
        declared: Option<String>,
        source_hash: &str,
        source_size: u64,
        raw: &[u8],
        started: Instant,
    ) -> Result<()> {
        let owns_claim = self.claim.is_none();
        if owns_claim {
            self.claim = Some(ClaimState {
                prefix: format!("{source_path}.d/"),
                claimed: std::collections::HashSet::new(),
                emitted: std::collections::HashSet::new(),
                collisions: 0,
            });
        }
        let result = self.emit_metadata_child(
            source_path,
            format,
            declared,
            source_hash,
            source_size,
            raw,
            started,
        );
        if owns_claim && let Some(claim) = self.claim.take() {
            self.reconcile(source_path, &claim, started)?;
        }
        result
    }

    /// Converts the metadata child and emits its record. Zero rows is the
    /// not-applicable outcome: nothing is written and reconciliation
    /// retires any prior child. A malformation records one failed child
    /// with a machine-readable reason and no artifact.
    #[cfg(all(unix, feature = "image-metadata"))]
    #[allow(clippy::too_many_arguments)]
    fn emit_metadata_child(
        &mut self,
        source_path: &str,
        format: &str,
        declared: Option<String>,
        source_hash: &str,
        source_size: u64,
        raw: &[u8],
        started: Instant,
    ) -> Result<()> {
        let child_path = metadata_child_path(source_path);
        let (text_absolute, segments_absolute, text_relative) = self.artifact_paths(&child_path);
        let converter = self
            .rules
            .registry
            .image_metadata_converter()
            .expect("the metadata leg runs only when the converter is present");
        let detection = Detection {
            declared,
            detected: format.to_string(),
            mismatch: false,
        };
        let child_meta = Meta {
            source_path: child_path.clone(),
            parent_source: Some(source_path.to_string()),
            source_hash: source_hash.to_string(),
            source_size,
            detection,
            detect_warnings: Vec::new(),
        };
        match run_converter(converter, raw, format) {
            Ok(outcome) => {
                match segments::to_jsonl(&outcome.segments)
                    .map_err(|e| e.to_string())
                    .and_then(|lines| {
                        mirror::write_atomic(&text_absolute, &outcome.text)
                            .and_then(|()| mirror::write_atomic(&segments_absolute, &lines))
                            .map_err(|e| e.to_string())
                    }) {
                    Ok(()) => {
                        let mut record = self.base_record(&child_meta, Status::Converted);
                        record.text_path = Some(text_relative);
                        record.text_hash = Some(hash::hash_bytes(outcome.text.as_bytes()));
                        record.artifact_kind = Some(outcome.artifact_kind);
                        record.converter_id = Some(outcome.converter_id.clone());
                        record.converter_version = Some(outcome.converter_version.clone());
                        record.warnings.extend(outcome.warnings.iter().cloned());
                        record.duration_ms = Some(elapsed_ms(started));
                        self.emit(record)
                    }
                    Err(detail) => {
                        let mut record = self.base_record(&child_meta, Status::Failed);
                        record.converter_id =
                            Some(convert::image_metadata::IMAGE_METADATA_ID.to_string());
                        record.converter_version =
                            Some(convert::image_metadata::IMAGE_METADATA_VERSION.to_string());
                        record.error = Some(format!("mirror_write_error: {detail}"));
                        record.duration_ms = Some(elapsed_ms(started));
                        remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                        self.emit(record)
                    }
                }
            }
            Err(reason)
                if reason.starts_with(convert::image_metadata::IMAGE_METADATA_NOT_APPLICABLE) =>
            {
                // No textual metadata: write nothing. A prior child, if
                // any, is retired by the owning reconciliation.
                Ok(())
            }
            Err(reason) => {
                let mut record = self.base_record(&child_meta, Status::Failed);
                record.converter_id = Some(convert::image_metadata::IMAGE_METADATA_ID.to_string());
                record.converter_version =
                    Some(convert::image_metadata::IMAGE_METADATA_VERSION.to_string());
                record.error = Some(reason);
                record.duration_ms = Some(elapsed_ms(started));
                remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                self.emit(record)
            }
        }
    }

    /// Writes a parent container artifact and records the parent as
    /// converted. Shared by both container families.
    fn write_parent(
        &mut self,
        meta: &Meta,
        outcome: &convert::Outcome,
        started: Instant,
    ) -> Result<bool> {
        let (text_absolute, segments_absolute, text_relative) =
            self.artifact_paths(&meta.source_path);
        let lines = match segments::to_jsonl(&outcome.segments) {
            Ok(lines) => lines,
            Err(e) => {
                self.fail(meta, format!("invalid_segments: {e}"), started)?;
                return Ok(false);
            }
        };
        match mirror::write_atomic(&text_absolute, &outcome.text)
            .and_then(|()| mirror::write_atomic(&segments_absolute, &lines))
        {
            Ok(()) => {
                let mut record = self.base_record(meta, Status::Converted);
                record.text_path = Some(text_relative);
                record.text_hash = Some(hash::hash_bytes(outcome.text.as_bytes()));
                // By design a container parent is a text manifest of its
                // members, not a recognized or transcribed artifact, so
                // it is always `Text` regardless of any member's kind. A
                // leaf converter's own kind flows through the single
                // source branch above instead.
                record.artifact_kind = Some(ArtifactKind::Text);
                record.converter_id = Some(outcome.converter_id.clone());
                record.converter_version = Some(outcome.converter_version.clone());
                record.warnings.extend(outcome.warnings.iter().cloned());
                record.duration_ms = Some(elapsed_ms(started));
                self.emit(record)?;
                Ok(true)
            }
            Err(e) => {
                self.fail(meta, format!("mirror_write_error: {e}"), started)?;
                Ok(false)
            }
        }
    }

    /// Builds and processes one container member as a child unit.
    fn process_member(
        &mut self,
        parent: &Meta,
        member_path: &str,
        member_bytes: Vec<u8>,
        depth: usize,
        ancestors: &[String],
        expanded: &mut u64,
    ) -> Result<()> {
        let source_path = format!("{}.d/{}", parent.source_path, member_path);
        // Two members whose normalized child paths collide would alias
        // one artifact, leaving two records with one file and a
        // mismatched hash. The later one is refused.
        if let Some(claim) = &mut self.claim {
            let key = collision_key(&source_path);
            if !claim.claimed.insert(key) {
                claim.collisions += 1;
                let synthetic = format!("{}.d/#collision-{}", parent.source_path, claim.collisions);
                return self.emit_member_failure(
                    parent,
                    synthetic,
                    member_bytes.len() as u64,
                    "member-path-collision".to_string(),
                    Instant::now(),
                );
            }
        }
        let (detection, detect_warnings) = detect::detect_bytes_with_warnings(
            Path::new(&source_path),
            &member_bytes,
            &self.rules.table,
        );
        let unit = Unit {
            meta: Meta {
                source_hash: hash::hash_bytes(&member_bytes),
                source_size: member_bytes.len() as u64,
                source_path,
                parent_source: Some(parent.source_path.clone()),
                detection,
                detect_warnings,
            },
            bytes: UnitBytes::Mem(member_bytes),
            depth,
            ancestors: ancestors.to_vec(),
        };
        self.process(unit, Instant::now(), expanded)
    }
}

/// The failure reason for a source over the conversion size ceiling.
fn over_source_ceiling(size: u64) -> String {
    format!(
        "resource_limit: source is {size} bytes over the {} byte ceiling",
        convert::MAX_SOURCE_BYTES
    )
}

/// Runs a converter under the panic boundary and output validation.
fn run_converter(
    converter: &dyn convert::Converter,
    bytes: &[u8],
    detected: &str,
) -> std::result::Result<convert::Outcome, String> {
    let guarded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        converter.convert(bytes, detected)
    }));
    let outcome = match guarded {
        Ok(result) => result.map_err(|e| e.to_string())?,
        Err(_) => return Err("converter_panic: conversion panicked".to_string()),
    };
    validate_output(&outcome)?;
    Ok(outcome)
}

/// The shared output gate: output-size ceiling, the NUL refusal, and
/// segments validation.
fn validate_output(outcome: &convert::Outcome) -> std::result::Result<(), String> {
    if outcome.text.len() > convert::MAX_OUTPUT_BYTES {
        return Err(format!(
            "resource_limit: output is {} bytes over the {} byte ceiling",
            outcome.text.len(),
            convert::MAX_OUTPUT_BYTES
        ));
    }
    if let Some(offset) = outcome.text.find('\0') {
        return Err(format!(
            "nul_bytes: NUL at byte {offset} of the converted text"
        ));
    }
    segments::validate(&outcome.segments, &outcome.text)
        .map_err(|detail| format!("invalid_segments: {detail}"))
}

impl Expander<'_> {
    /// Emits one failed child record for a member refused before or
    /// during inflation.
    fn emit_member_failure(
        &mut self,
        parent: &Meta,
        child_source_path: String,
        source_size: u64,
        reason: String,
        started: Instant,
    ) -> Result<()> {
        let (text_absolute, segments_absolute, _) = self.artifact_paths(&child_source_path);
        let detection = Detection {
            declared: None,
            detected: UNKNOWN_FORMAT.to_string(),
            mismatch: false,
        };
        let mut record = new_record(
            &child_source_path,
            "",
            source_size,
            &detection,
            self.rules.version(),
            Status::Failed,
        );
        record.parent_source = Some(parent.source_path.clone());
        record.error = Some(reason);
        record.duration_ms = Some(elapsed_ms(started));
        remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
        self.emit(record)
    }

    /// Expands a zip container: a member listing artifact for the
    /// parent, then each member routed back through dispatch.
    fn expand_zip(
        &mut self,
        meta: Meta,
        bytes: UnitBytes,
        depth: usize,
        ancestors: Vec<String>,
        started: Instant,
        expanded: &mut u64,
    ) -> Result<()> {
        if self.expansion_collides(&meta.source_path) {
            return self.fail(&meta, "container-mirror-collision".to_string(), started);
        }
        if meta.source_size > convert::MAX_SOURCE_BYTES {
            return self.fail(&meta, over_source_ceiling(meta.source_size), started);
        }
        let bytes = match bytes.load(&meta.source_hash) {
            Ok(bytes) => bytes,
            Err(reason) => return self.fail(&meta, reason, started),
        };
        // Preflight the raw entry count from the end-of-central-
        // directory record before the zip crate parses and allocates
        // the whole directory, and refuse on the raw count, which its
        // name-keyed map would otherwise undercount.
        if let Some(entries) = convert::preflight_entry_count(&bytes)
            && entries > self.limits.max_children as u64
        {
            return self.fail(&meta, "container-children-exceeded".to_string(), started);
        }
        let mut container = match convert::ZipContainer::open(&bytes) {
            Ok(container) => container,
            Err(e) => return self.fail(&meta, e.to_string(), started),
        };

        // Stage 1: the child count and declared sizes, before any
        // inflation.
        let count = container.len();
        if count > self.limits.max_children {
            return self.fail(&meta, "container-children-exceeded".to_string(), started);
        }
        let mut declared_total: u64 = 0;
        for index in 0..count {
            match container.meta(index) {
                Ok(member) => declared_total = declared_total.saturating_add(member.declared_size),
                Err(e) => return self.fail(&meta, e.to_string(), started),
            }
        }
        if declared_total > self.limits.max_expanded_bytes {
            return self.fail(&meta, "container-expansion-cap".to_string(), started);
        }
        let listing = match container.listing() {
            Ok(listing) => listing,
            Err(e) => return self.fail(&meta, e.to_string(), started),
        };

        let mut child_ancestors = ancestors;
        child_ancestors.push(meta.source_hash.clone());

        // Stage 2: inflate and route each member. The cumulative
        // counter charges actual inflated bytes, and an overrun fails
        // the whole container.
        let mut parent_failure: Option<String> = None;
        for index in 0..count {
            let member = match container.meta(index) {
                Ok(member) => member,
                Err(e) => {
                    parent_failure = Some(e.to_string());
                    break;
                }
            };
            if member.is_dir {
                continue;
            }
            let Some(member_path) = member.safe_path.clone() else {
                self.emit_member_failure(
                    &meta,
                    format!("{}.d/#unsafe-member-{index}", meta.source_path),
                    0,
                    "unsafe-member-path".to_string(),
                    started,
                )?;
                continue;
            };
            let child_source = format!("{}.d/{}", meta.source_path, member_path);
            if member.is_symlink {
                self.emit_member_failure(
                    &meta,
                    child_source,
                    0,
                    "unsafe-member-path".to_string(),
                    started,
                )?;
                continue;
            }
            if member.encrypted {
                self.emit_member_failure(
                    &meta,
                    child_source,
                    member.declared_size,
                    "encrypted".to_string(),
                    started,
                )?;
                continue;
            }
            if member.declared_size > self.limits.max_member_size {
                self.emit_member_failure(
                    &meta,
                    child_source,
                    member.declared_size,
                    "container-member-too-large".to_string(),
                    started,
                )?;
                continue;
            }
            let remaining = self.limits.max_expanded_bytes.saturating_sub(*expanded);
            let cap = self.limits.max_member_size.min(remaining);
            match container.inflate(index, cap) {
                convert::Inflated::Ok(data) => {
                    *expanded = expanded.saturating_add(data.len() as u64);
                    self.process_member(
                        &meta,
                        &member_path,
                        data,
                        depth + 1,
                        &child_ancestors,
                        expanded,
                    )?;
                }
                convert::Inflated::TooLarge(inflated) => {
                    *expanded = expanded.saturating_add(inflated);
                    if inflated > self.limits.max_member_size {
                        self.emit_member_failure(
                            &meta,
                            child_source,
                            inflated,
                            "container-member-too-large".to_string(),
                            started,
                        )?;
                    }
                    if *expanded > self.limits.max_expanded_bytes {
                        parent_failure = Some("container-expansion-cap".to_string());
                        break;
                    }
                }
                convert::Inflated::Error(e) => {
                    self.emit_member_failure(
                        &meta,
                        child_source,
                        0,
                        format!("container-member-unreadable: {e}"),
                        started,
                    )?;
                }
            }
        }

        match parent_failure {
            Some(reason) => self.fail(&meta, reason, started),
            None => {
                let segments = vec![segments::Segment::span(0, listing.len(), "document")];
                let outcome = convert::Outcome {
                    converter_id: convert::CONTAINER_ZIP_ID.to_string(),
                    converter_version: convert::CONTAINER_ZIP_VERSION.to_string(),
                    detected_format: meta.detection.detected.clone(),
                    text: listing,
                    warnings: Vec::new(),
                    segments,
                    artifact_kind: manifest::ArtifactKind::Text,
                };
                if let Err(reason) = validate_output(&outcome) {
                    return self.fail(&meta, reason, started);
                }
                self.write_parent(&meta, &outcome, started).map(|_| ())
            }
        }
    }

    /// Expands an eml container: the message renders to the parent
    /// artifact, and each attachment routes back through dispatch as a
    /// member.
    fn expand_eml(
        &mut self,
        meta: Meta,
        bytes: UnitBytes,
        depth: usize,
        ancestors: Vec<String>,
        started: Instant,
        expanded: &mut u64,
    ) -> Result<()> {
        if self.expansion_collides(&meta.source_path) {
            return self.fail(&meta, "container-mirror-collision".to_string(), started);
        }
        let bytes = match bytes.load(&meta.source_hash) {
            Ok(bytes) => bytes,
            Err(reason) => return self.fail(&meta, reason, started),
        };
        if meta.source_size > convert::MAX_SOURCE_BYTES {
            return self.fail(&meta, over_source_ceiling(meta.source_size), started);
        }
        let guarded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            convert::expand_eml(&bytes, &meta.detection.detected)
        }));
        let expansion = match guarded {
            Ok(Ok(expansion)) => expansion,
            Ok(Err(e)) => return self.fail(&meta, e.to_string(), started),
            Err(_) => {
                return self.fail(
                    &meta,
                    "converter_panic: conversion panicked".to_string(),
                    started,
                );
            }
        };
        if let Err(reason) = validate_output(&expansion.outcome) {
            return self.fail(&meta, reason, started);
        }

        // Expand the attachments first, so the parent record is
        // written last and an intact eml parent proves the whole
        // expansion finished, matching the zip ordering.
        let mut child_ancestors = ancestors;
        child_ancestors.push(meta.source_hash.clone());
        let mut parent_failure: Option<String> = None;
        for member in expansion.members {
            *expanded = expanded.saturating_add(member.bytes.len() as u64);
            if *expanded > self.limits.max_expanded_bytes {
                parent_failure = Some("container-expansion-cap".to_string());
                break;
            }
            self.process_member(
                &meta,
                &member.name,
                member.bytes,
                depth + 1,
                &child_ancestors,
                expanded,
            )?;
        }

        match parent_failure {
            Some(reason) => self.fail(&meta, reason, started),
            None => self
                .write_parent(&meta, &expansion.outcome, started)
                .map(|_| ()),
        }
    }
}

/// Converts a division root into the mirror tree.
///
/// Walks the root in sorted order, detects each file, and appends one
/// record per source to the division shard. Text-native formats pass
/// through the registered converter. A format no converter claims
/// becomes `unsupported`. A converter error becomes `failed` with a
/// reason and no text artifact. Safe to kill and re-run.
///
/// Dedup applies when a source's hash matches an artifact already
/// converted by the same converter id and version that would handle
/// this source. The duplicate gets a real text file at its parallel
/// path, hashed over the bytes actually written, with `dedup_of`
/// naming the canonical source. When the canonical artifact cannot be
/// read, the duplicate converts for itself.
pub fn run(rules: &Rules, options: &RunOptions) -> Result<RunReport> {
    validate_division(options.division)?;
    check_layout(options.root, options.mirror_root, options.manifest_dir)?;
    let entries = walk::walk_division(options.root, &options.walk)?;
    let shard_path = options
        .manifest_dir
        .join(format!("{}.jsonl", options.division));
    let (prior, mut warnings) = if shard_path.exists() {
        let shard = manifest::read_shard(&shard_path)?;
        (shard.records, shard.warnings)
    } else {
        (Vec::new(), Vec::new())
    };
    let mut terminal = terminal_by_path(prior);
    let mut dedup = DedupIndex::default();
    seed_dedup(&terminal, rules, &mut dedup);

    // The mirror paths a container's `.d/` expansion would claim must
    // not collide with a real walked source, so the walked set is
    // checked before any container expands.
    let walked: std::collections::HashSet<String> = entries
        .iter()
        .filter_map(|entry| entry.path.to_str().map(str::to_string))
        .collect();
    let limits = rules.registry.container_limits().clone();

    let mut writer = ManifestWriter::open(&shard_path)?;
    let mut counts = StatusCounts::default();
    let mut special_entries = 0u64;

    for entry in &entries {
        let started = Instant::now();
        let relative = &entry.path;
        let absolute = options.root.join(relative);
        let text_absolute = mirror::mirror_path(options.mirror_root, options.division, relative);
        let segments_absolute =
            segments::segments_path(options.mirror_root, options.division, relative);

        if entry.kind == EntryKind::Other {
            special_entries += 1;
            continue;
        }

        // A lossy path must never name a record key or an artifact, so
        // a non-UTF-8 source name, symlink or file, is a recorded
        // failure with no conversion.
        let Some(source_path) = relative.to_str().map(str::to_string) else {
            let detection = Detection {
                declared: detect::declared_format(relative, &rules.table),
                detected: UNKNOWN_FORMAT.to_string(),
                mismatch: false,
            };
            let mut record = new_record(
                &relative.to_string_lossy(),
                "",
                0,
                &detection,
                rules.version(),
                Status::Failed,
            );
            record.error = Some("non_utf8_path: source path is not valid UTF-8".to_string());
            record.duration_ms = Some(elapsed_ms(started));
            remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
            record_outcome(&mut writer, &mut terminal, &mut counts, record)?;
            continue;
        };

        if entry.kind == EntryKind::Symlink {
            let detection = Detection {
                declared: None,
                detected: SYMLINK_FORMAT.to_string(),
                mismatch: false,
            };
            let mut record = match fs::read_link(&absolute) {
                Ok(target) => {
                    let target_bytes = target.as_os_str().as_encoded_bytes();
                    let mut record = new_record(
                        &source_path,
                        &hash::hash_bytes(target_bytes),
                        target_bytes.len() as u64,
                        &detection,
                        rules.version(),
                        Status::Unsupported,
                    );
                    // Symlinks are unsupported by pipeline design,
                    // whatever the registry claims, so the reason is
                    // set directly instead of looked up.
                    record.error = Some(convert::NO_CONVERTER_REASON.to_string());
                    record
                }
                Err(e) => {
                    let mut record = new_record(
                        &source_path,
                        "",
                        0,
                        &detection,
                        rules.version(),
                        Status::Failed,
                    );
                    record.error = Some(format!("source_io_error: readlink: {e}"));
                    record
                }
            };
            record.duration_ms = Some(elapsed_ms(started));
            remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
            record_outcome(&mut writer, &mut terminal, &mut counts, record)?;
            continue;
        }

        // Gate the source size before detection. Format detection
        // reads from the file to sniff its type, and for a zip it can
        // allocate from a forged member size, so an oversized source
        // must fail before that read, containers included.
        let stat = match absolute.metadata() {
            Ok(metadata) => metadata,
            Err(e) => {
                let detection = Detection {
                    declared: detect::declared_format(relative, &rules.table),
                    detected: UNKNOWN_FORMAT.to_string(),
                    mismatch: false,
                };
                let mut record = new_record(
                    &source_path,
                    "",
                    0,
                    &detection,
                    rules.version(),
                    Status::Failed,
                );
                record.error = Some(format!("source_io_error: stat: {e}"));
                record.duration_ms = Some(elapsed_ms(started));
                remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                record_outcome(&mut writer, &mut terminal, &mut counts, record)?;
                continue;
            }
        };
        if stat.len() > convert::MAX_SOURCE_BYTES {
            let detection = Detection {
                declared: detect::declared_format(relative, &rules.table),
                detected: UNKNOWN_FORMAT.to_string(),
                mismatch: false,
            };
            let mut record = new_record(
                &source_path,
                "",
                stat.len(),
                &detection,
                rules.version(),
                Status::Failed,
            );
            record.error = Some(over_source_ceiling(stat.len()));
            record.duration_ms = Some(elapsed_ms(started));
            remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
            record_outcome(&mut writer, &mut terminal, &mut counts, record)?;
            continue;
        }

        let front = match source_front(&absolute, &rules.table) {
            Ok(front) => front,
            Err(e) => {
                let detection = Detection {
                    declared: detect::declared_format(relative, &rules.table),
                    detected: UNKNOWN_FORMAT.to_string(),
                    mismatch: false,
                };
                let mut record = new_record(
                    &source_path,
                    "",
                    0,
                    &detection,
                    rules.version(),
                    Status::Failed,
                );
                record.error = Some(format!("source_io_error: {e}"));
                record.duration_ms = Some(elapsed_ms(started));
                remove_stale_artifact(&text_absolute, &segments_absolute, &mut record);
                record_outcome(&mut writer, &mut terminal, &mut counts, record)?;
                continue;
            }
        };
        let (source_hash, source_size, detection, detect_warnings) = front;
        let mut expanded = 0u64;
        let unit = Unit {
            meta: Meta {
                source_path,
                parent_source: None,
                source_hash,
                source_size,
                detection,
                detect_warnings,
            },
            bytes: UnitBytes::Disk(absolute.clone()),
            depth: 0,
            ancestors: Vec::new(),
        };
        let mut expander = Expander {
            rules,
            mirror_root: options.mirror_root,
            division: options.division,
            walked: &walked,
            limits: &limits,
            writer: &mut writer,
            terminal: &mut terminal,
            counts: &mut counts,
            dedup: &mut dedup,
            claim: None,
        };
        expander.process(unit, started, &mut expanded)?;
    }

    warnings.sort();
    Ok(RunReport {
        division: options.division.to_string(),
        root: options.root.display().to_string(),
        sources: entries.len() as u64 - special_entries,
        special_entries,
        counts,
        warnings,
    })
}

fn shard_paths(manifest_dir: &Path) -> Result<Vec<PathBuf>> {
    let entries = fs::read_dir(manifest_dir).map_err(|e| Error::io("read_dir", manifest_dir, e))?;
    let mut shards = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|e| Error::io("read_dir", manifest_dir, e))?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) == Some("jsonl") {
            shards.push(path);
        }
    }
    shards.sort();
    Ok(shards)
}

fn division_name(shard: &Path) -> String {
    shard
        .file_stem()
        .map(|stem| stem.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Computes coverage per division over terminal records.
pub fn status(manifest_dir: &Path) -> Result<StatusReport> {
    let mut divisions = Vec::new();
    for shard_path in shard_paths(manifest_dir)? {
        let shard = manifest::read_shard(&shard_path)?;
        let terminal = terminal_by_path(shard.records);
        let mut counts = StatusCounts::default();
        let mut with_text = 0u64;
        for record in terminal.values() {
            match record.status {
                Status::Converted => counts.converted += 1,
                Status::Failed => counts.failed += 1,
                Status::Unsupported => counts.unsupported += 1,
                Status::SkippedUnchanged => counts.skipped_unchanged += 1,
                Status::Dedup => counts.dedup += 1,
            }
            if record.text_path.is_some() {
                with_text += 1;
            }
        }
        let sources = terminal.len() as u64;
        let coverage = if sources == 0 {
            0.0
        } else {
            with_text as f64 / sources as f64
        };
        divisions.push(DivisionStatus {
            division: division_name(&shard_path),
            sources,
            with_text,
            coverage,
            counts,
            warnings: shard.warnings,
        });
    }
    Ok(StatusReport { divisions })
}

/// Collects every record for one source path across all shards.
pub fn explain(manifest_dir: &Path, source_path: &str) -> Result<Vec<ExplainEntry>> {
    let mut entries = Vec::new();
    for shard_path in shard_paths(manifest_dir)? {
        let division = division_name(&shard_path);
        for record in manifest::read_shard(&shard_path)?.records {
            if record.source_path == source_path {
                entries.push(ExplainEntry {
                    division: division.clone(),
                    record,
                });
            }
        }
    }
    Ok(entries)
}

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

    #[test]
    fn builtin_rules_agree_on_a_version() {
        let rules = Rules::builtin().unwrap();
        assert_eq!(rules.version(), "9");
    }

    /// Drives `Expander::process` directly with an over-ceiling image
    /// carrier whose hash has a current-rules canonical in the dedup
    /// index, past the run-level walker gate that would otherwise refuse
    /// the file before a unit exists. The ceiling precedes the dedup
    /// borrow, so the source falls through to the leaf path: one failed
    /// record with the resource-limit reason, no dedup record, no
    /// metadata child, and the body never loaded for the borrow.
    #[cfg(all(unix, feature = "image-metadata"))]
    #[test]
    fn an_over_ceiling_image_with_a_dedup_seed_is_refused_before_the_borrow() {
        use std::collections::HashSet;
        use std::io::Write as _;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("source");
        fs::create_dir_all(&root).unwrap();
        let mirror_root = dir.path().join("mirror");
        let manifest_dir = dir.path().join("manifest");
        let division = "unit";
        let rules = Rules::builtin().unwrap();
        assert!(
            rules.registry.image_metadata_converter().is_some(),
            "the metadata leg must be present for this path"
        );

        // A sparse over-ceiling png-magic source.
        let huge = root.join("huge.png");
        let mut file = fs::File::create(&huge).unwrap();
        file.write_all(b"\x89PNG\r\n\x1a\n").unwrap();
        file.set_len(convert::MAX_SOURCE_BYTES + 1).unwrap();
        drop(file);
        let source_size = fs::metadata(&huge).unwrap().len();
        let source_hash = hash::hash_bytes(&fs::read(&huge).unwrap());

        // An intact canonical artifact for that hash, under the current
        // primary converter, so the dedup borrow would otherwise fire.
        let converter = rules.registry.converter_for("png").unwrap();
        let canon_text = "recognized line\n";
        let canon_text_path = mirror::mirror_path(&mirror_root, division, Path::new("canon.png"));
        let canon_segments =
            segments::segments_path(&mirror_root, division, Path::new("canon.png"));
        let lines = segments::to_jsonl(&[Segment::span(0, canon_text.len(), "ocr")]).unwrap();
        mirror::write_atomic(&canon_text_path, canon_text).unwrap();
        mirror::write_atomic(&canon_segments, &lines).unwrap();
        let mut dedup = DedupIndex::default();
        dedup.insert(
            &source_hash,
            CanonicalArtifact {
                source_path: "canon.png".to_string(),
                text_path: mirror::recorded_text_path(division, "canon.png"),
                text_hash: hash::hash_bytes(canon_text.as_bytes()),
                converter_id: converter.id().to_string(),
                converter_version: converter.version().to_string(),
                artifact_kind: Some(ArtifactKind::Ocr),
                warnings: Vec::new(),
            },
        );

        let shard = manifest_dir.join("unit.jsonl");
        let mut writer = ManifestWriter::open(&shard).unwrap();
        let mut terminal = HashMap::new();
        let mut counts = StatusCounts::default();
        let walked = HashSet::new();
        let unit = Unit {
            meta: Meta {
                source_path: "huge.png".to_string(),
                parent_source: None,
                source_hash,
                source_size,
                detection: Detection {
                    declared: Some("png".to_string()),
                    detected: "png".to_string(),
                    mismatch: false,
                },
                detect_warnings: Vec::new(),
            },
            bytes: UnitBytes::Disk(huge),
            depth: 0,
            ancestors: Vec::new(),
        };
        let mut expander = Expander {
            rules: &rules,
            mirror_root: &mirror_root,
            division,
            walked: &walked,
            limits: rules.registry.container_limits(),
            writer: &mut writer,
            terminal: &mut terminal,
            counts: &mut counts,
            dedup: &mut dedup,
            claim: None,
        };
        let mut expanded = 0u64;
        expander
            .process(unit, Instant::now(), &mut expanded)
            .unwrap();
        drop(writer);

        let records = manifest::read_shard(&shard).unwrap().records;
        assert_eq!(records.len(), 1, "{records:?}");
        let record = &records[0];
        assert_eq!(record.source_path, "huge.png");
        assert_eq!(record.status, Status::Failed);
        assert!(
            record
                .error
                .as_deref()
                .is_some_and(|e| e.starts_with("resource_limit")),
            "{:?}",
            record.error
        );
        assert!(record.dedup_of.is_none());
        assert_eq!(counts.dedup, 0);
        assert_eq!(counts.failed, 1);
        assert!(!terminal.contains_key("huge.png.d/#image-metadata"));
        assert!(
            !mirror::mirror_path(
                &mirror_root,
                division,
                Path::new("huge.png.d/#image-metadata")
            )
            .exists()
        );
    }

    #[test]
    fn the_quine_guard_matches_an_ancestor_hash() {
        let chain = vec!["aa".to_string(), "bb".to_string()];
        assert!(hash_on_chain("bb", &chain));
        assert!(hash_on_chain("aa", &chain));
        assert!(!hash_on_chain("cc", &chain));
        assert!(!hash_on_chain("aa", &[]));
    }

    use crate::convert::{ConvertError, Converter, Outcome, PlainTextPassthrough};
    use crate::segments::Segment;

    /// A converter that panics, for the boundary test. No shipped
    /// converter panics on purpose, so the test registry injects one.
    struct PanicConverter;

    impl Converter for PanicConverter {
        fn id(&self) -> &'static str {
            "panic-test"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        fn convert(
            &self,
            _source: &[u8],
            _detected_format: &str,
        ) -> std::result::Result<Outcome, ConvertError> {
            panic!("deliberate test panic");
        }
    }

    /// A converter whose segments do not fit its text.
    struct BadSegmentsConverter;

    impl Converter for BadSegmentsConverter {
        fn id(&self) -> &'static str {
            "bad-segments-test"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        fn convert(
            &self,
            _source: &[u8],
            detected_format: &str,
        ) -> std::result::Result<Outcome, ConvertError> {
            Ok(Outcome {
                converter_id: self.id().to_string(),
                converter_version: self.version().to_string(),
                detected_format: detected_format.to_string(),
                text: "ok".to_string(),
                warnings: Vec::new(),
                segments: vec![Segment::span(0, 999, "document")],
                artifact_kind: manifest::ArtifactKind::Text,
            })
        }
    }

    /// A converter that returns a valid outcome stamped
    /// [`manifest::ArtifactKind::Ocr`], so the pipeline's kind
    /// propagation through the single-source, dedup, and checkpoint paths
    /// can be exercised without a jailed engine.
    struct OcrKindConverter;

    impl Converter for OcrKindConverter {
        fn id(&self) -> &'static str {
            "ocr-kind-test"
        }
        fn version(&self) -> &'static str {
            "1.0.0"
        }
        fn convert(
            &self,
            _source: &[u8],
            detected_format: &str,
        ) -> std::result::Result<Outcome, ConvertError> {
            let text = "recognized text\n".to_string();
            Ok(Outcome {
                converter_id: self.id().to_string(),
                converter_version: self.version().to_string(),
                detected_format: detected_format.to_string(),
                segments: vec![Segment::span(0, text.len(), "document")],
                text,
                warnings: Vec::new(),
                artifact_kind: manifest::ArtifactKind::Ocr,
            })
        }
    }

    fn injected_rules() -> Rules {
        let table = FormatTable::parse(
            r#"
version = "9"

[[formats]]
id = "text"
name = "Plain text"
extensions = ["txt"]

[[formats]]
id = "panicfmt"
name = "Panic trigger"
extensions = ["panicfmt"]

[[formats]]
id = "badseg"
name = "Bad segments trigger"
extensions = ["badseg"]

[[formats]]
id = "ocrfmt"
name = "OCR kind trigger"
extensions = ["ocrfmt"]
"#,
            "formats.toml",
        )
        .unwrap();
        let registry = Registry::for_tests(
            "9",
            vec![
                (Box::new(PlainTextPassthrough), vec!["text"]),
                (Box::new(PanicConverter), vec!["panicfmt"]),
                (Box::new(BadSegmentsConverter), vec!["badseg"]),
                (Box::new(OcrKindConverter), vec!["ocrfmt"]),
            ],
        );
        Rules { table, registry }
    }

    #[test]
    fn a_panicking_converter_fails_one_source_and_the_division_survives() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("src");
        fs::create_dir_all(&root).unwrap();
        fs::write(root.join("boom.panicfmt"), "trigger\n").unwrap();
        fs::write(root.join("fine.txt"), "safe content\n").unwrap();

        let rules = injected_rules();
        let report = run(
            &rules,
            &RunOptions {
                root: &root,
                mirror_root: &dir.path().join("mirror"),
                manifest_dir: &dir.path().join("manifest"),
                division: "unit",
                walk: WalkOptions::default(),
            },
        )
        .unwrap();

        assert_eq!(report.counts.failed, 1);
        assert_eq!(report.counts.converted, 1);
        let records = manifest::read_shard(&dir.path().join("manifest/unit.jsonl"))
            .unwrap()
            .records;
        let failed = records.iter().find(|r| r.status == Status::Failed).unwrap();
        assert_eq!(failed.source_path, "boom.panicfmt");
        assert!(
            failed
                .error
                .as_deref()
                .unwrap()
                .starts_with("converter_panic")
        );
        assert!(!dir.path().join("mirror/unit/boom.panicfmt.txt").exists());
    }

    #[test]
    fn invalid_segments_from_a_converter_fail_before_any_write() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("src");
        fs::create_dir_all(&root).unwrap();
        fs::write(root.join("bad.badseg"), "trigger\n").unwrap();

        let rules = injected_rules();
        let report = run(
            &rules,
            &RunOptions {
                root: &root,
                mirror_root: &dir.path().join("mirror"),
                manifest_dir: &dir.path().join("manifest"),
                division: "unit",
                walk: WalkOptions::default(),
            },
        )
        .unwrap();

        assert_eq!(report.counts.failed, 1);
        let records = manifest::read_shard(&dir.path().join("manifest/unit.jsonl"))
            .unwrap()
            .records;
        assert!(
            records[0]
                .error
                .as_deref()
                .unwrap()
                .starts_with("invalid_segments")
        );
        assert!(!dir.path().join("mirror/unit/bad.badseg.txt").exists());
        assert!(
            !dir.path()
                .join("mirror/unit/bad.badseg.segments.jsonl")
                .exists()
        );
    }

    #[test]
    fn the_ocr_artifact_kind_propagates_through_dedup_and_checkpoint() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("src");
        let mirror = dir.path().join("mirror");
        let manifest_dir = dir.path().join("manifest");
        fs::create_dir_all(&root).unwrap();
        // Two identical-content OCR sources: the first converts, the
        // second dedups off it within the same run.
        fs::write(root.join("a.ocrfmt"), "same pixels\n").unwrap();
        fs::write(root.join("b.ocrfmt"), "same pixels\n").unwrap();

        let rules = injected_rules();
        let options = RunOptions {
            root: &root,
            mirror_root: &mirror,
            manifest_dir: &manifest_dir,
            division: "unit",
            walk: WalkOptions::default(),
        };
        run(&rules, &options).unwrap();

        let shard = manifest_dir.join("unit.jsonl");
        let latest = |path: &str| {
            manifest::read_shard(&shard)
                .unwrap()
                .records
                .into_iter()
                .rev()
                .find(|r| r.source_path == path)
                .unwrap()
        };

        // Same-run: one Converted, one Dedup, both carry the OCR kind.
        let a = latest("a.ocrfmt");
        let b = latest("b.ocrfmt");
        let (converted, deduped) = if a.status == Status::Converted {
            (a, b)
        } else {
            (b, a)
        };
        assert_eq!(converted.status, Status::Converted);
        assert_eq!(deduped.status, Status::Dedup);
        assert_eq!(converted.artifact_kind, Some(ArtifactKind::Ocr));
        assert_eq!(deduped.artifact_kind, Some(ArtifactKind::Ocr));

        // Second run with the prior manifest present. The unchanged
        // sources skip and keep their OCR kind (checkpoint-skip clones
        // the prior record); a new identical source dedups off the
        // seeded prior canonical and is also OCR (seeded dedup).
        fs::write(root.join("c.ocrfmt"), "same pixels\n").unwrap();
        run(&rules, &options).unwrap();

        let a2 = latest("a.ocrfmt");
        let b2 = latest("b.ocrfmt");
        let c = latest("c.ocrfmt");
        assert_eq!(a2.status, Status::SkippedUnchanged);
        assert_eq!(b2.status, Status::SkippedUnchanged);
        assert_eq!(a2.artifact_kind, Some(ArtifactKind::Ocr));
        assert_eq!(b2.artifact_kind, Some(ArtifactKind::Ocr));
        assert_eq!(c.status, Status::Dedup);
        assert_eq!(c.artifact_kind, Some(ArtifactKind::Ocr));
    }

    #[test]
    fn division_names_are_validated() {
        assert!(validate_division("finance-eu_1").is_ok());
        assert!(validate_division("").is_err());
        assert!(validate_division("a/b").is_err());
        assert!(validate_division("dot.dot").is_err());
    }

    #[test]
    fn layout_rejects_outputs_inside_the_root() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("src");
        fs::create_dir_all(&root).unwrap();
        let outside = dir.path().join("out");

        let err = check_layout(&root, &root.join("mirror"), &outside).unwrap_err();
        assert!(err.to_string().contains("mirror root"));

        let err = check_layout(&root, &outside.join("mirror"), &root.join("manifest")).unwrap_err();
        assert!(err.to_string().contains("manifest directory"));

        check_layout(&root, &outside.join("mirror"), &outside.join("manifest")).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn non_utf8_paths_are_rejected_without_an_artifact() {
        use std::os::unix::ffi::OsStrExt;
        let raw = std::ffi::OsStr::from_bytes(b"bad-\xff-name.txt");
        assert!(Path::new(raw).to_str().is_none());
    }

    #[test]
    fn identical_sources_dedup_to_one_conversion() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("src");
        fs::create_dir_all(root.join("sub")).unwrap();
        fs::write(root.join("first.txt"), "same bytes\n").unwrap();
        fs::write(root.join("sub/second.txt"), "same bytes\n").unwrap();

        let rules = Rules::builtin().unwrap();
        let report = run(
            &rules,
            &RunOptions {
                root: &root,
                mirror_root: &dir.path().join("mirror"),
                manifest_dir: &dir.path().join("manifest"),
                division: "unit",
                walk: WalkOptions::default(),
            },
        )
        .unwrap();

        assert_eq!(report.counts.converted, 1);
        assert_eq!(report.counts.dedup, 1);

        let records = manifest::read_shard(&dir.path().join("manifest/unit.jsonl"))
            .unwrap()
            .records;
        let canonical = records
            .iter()
            .find(|r| r.source_path == "first.txt")
            .unwrap();
        let duplicate = records
            .iter()
            .find(|r| r.source_path == "sub/second.txt")
            .unwrap();
        assert_eq!(canonical.status, Status::Converted);
        assert_eq!(duplicate.status, Status::Dedup);
        assert_eq!(duplicate.dedup_of.as_deref(), Some("first.txt"));
        assert_eq!(duplicate.text_hash, canonical.text_hash);

        let mirrored =
            fs::read_to_string(dir.path().join("mirror/unit/sub/second.txt.txt")).unwrap();
        assert_eq!(mirrored, "same bytes\n");
    }
}