alef 0.70.0

Opinionated polyglot binding generator for Rust libraries
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
use std::fs;
use std::path::{Path, PathBuf};

/// Eager legacy-to-committed ownership migration -- see [`ownership::is_scaffold_owned_path`],
/// re-exported below at this module's own path so every existing caller
/// (`crate::cli::cache::is_scaffold_owned_path`) keeps compiling unchanged. Split out of this
/// file on its own, rather than folded into the surrounding ownership-manifest code, purely to
/// keep this already-oversized file from growing further -- see `file-modularization`. ~keep
mod ownership;
pub use ownership::is_scaffold_owned_path;

pub(super) const CACHE_DIR: &str = ".alef";
const PER_FILE_CACHE_NAME: &str = "sources_hash.cache";

/// Read the raw bytes of the alef config file for use in [`crate::core::hash::compute_inputs_hash`].
///
/// Returns an empty `Vec` when the file is absent or unreadable — callers
/// treat missing bytes as "empty config", which still produces a stable hash
/// when combined with `sources_hash`.
pub fn read_alef_toml_bytes(config_path: &Path) -> Vec<u8> {
    fs::read(config_path).unwrap_or_default()
}

/// Compute the per-run sources hash that drives both the IR cache and the
/// embedded `alef:hash:` value. Pure function of the rust source files
/// (paths + content); independent of `alef.toml` and the alef CLI version, so
/// that `alef verify` is idempotent across alef upgrades.
///
/// Warm-run optimisation: stat every source and check `(mtime_nanos, size)`
/// against an on-disk memo (`.alef/sources_hash.cache`). When **every** file's
/// stat is unchanged we return the cached aggregate hash directly — no file
/// reads, no blake3 work. Any change to any file falls back to the canonical
/// [`crate::core::hash::compute_sources_hash`] (which reads + hashes everything)
/// and refreshes the memo. The output is always equivalent to the canonical
/// function; the memo only elides redundant reads on no-change runs.
pub fn sources_hash(sources: &[PathBuf]) -> anyhow::Result<String> {
    let mut sorted: Vec<&PathBuf> = sources.iter().collect();
    sorted.sort();

    let memo = read_per_file_memo();
    let mut current: Vec<(String, u64, u64)> = Vec::with_capacity(sorted.len());
    let mut all_match = !memo.entries.is_empty() && memo.aggregate.is_some();
    for source in &sorted {
        let metadata =
            fs::metadata(source).map_err(|e| anyhow::anyhow!("failed to stat source {}: {e}", source.display()))?;
        let mtime_nanos = metadata
            .modified()
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0);
        let size = metadata.len();
        let path_str = source.to_string_lossy().to_string();
        if all_match {
            match memo.entries.get(&path_str) {
                Some((m, s)) if *m == mtime_nanos && *s == size => {}
                _ => all_match = false,
            }
        }
        current.push((path_str, mtime_nanos, size));
    }

    if all_match
        && current.len() == memo.entries.len()
        && let Some(agg) = memo.aggregate
    {
        return Ok(agg);
    }

    let aggregate = crate::core::hash::compute_sources_hash(sources)?;
    let _ = write_per_file_memo(&current, &aggregate);
    Ok(aggregate)
}

struct PerFileMemo {
    aggregate: Option<String>,
    entries: std::collections::HashMap<String, (u64, u64)>,
}

fn read_per_file_memo() -> PerFileMemo {
    let path = Path::new(CACHE_DIR).join(PER_FILE_CACHE_NAME);
    let Ok(content) = fs::read_to_string(&path) else {
        return PerFileMemo {
            aggregate: None,
            entries: std::collections::HashMap::new(),
        };
    };
    let mut aggregate: Option<String> = None;
    let mut entries = std::collections::HashMap::new();
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("aggregate\t") {
            aggregate = Some(rest.to_string());
            continue;
        }
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() != 3 {
            continue;
        }
        let mtime_nanos = parts[1].parse::<u64>().unwrap_or(0);
        let size = parts[2].parse::<u64>().unwrap_or(0);
        entries.insert(parts[0].to_string(), (mtime_nanos, size));
    }
    PerFileMemo { aggregate, entries }
}

fn write_per_file_memo(entries: &[(String, u64, u64)], aggregate: &str) -> anyhow::Result<()> {
    let dir = Path::new(CACHE_DIR);
    fs::create_dir_all(dir)?;
    let mut content = format!("aggregate\t{aggregate}\n");
    for (path, mtime, size) in entries {
        content.push_str(&format!("{path}\t{mtime}\t{size}\n"));
    }
    fs::write(dir.join(PER_FILE_CACHE_NAME), content)?;
    Ok(())
}

/// Validate a crate name before using it as a filesystem path component.
///
/// Returns an error if the name contains path separators, NUL bytes, `..`,
/// or is a bare `.` — any of which could be used to escape the cache directory.
pub fn validate_cache_crate_name(crate_name: &str) -> anyhow::Result<()> {
    if crate_name.contains('\0') {
        anyhow::bail!("invalid crate name for cache: NUL byte not allowed in {crate_name:?}");
    }
    if crate_name.contains('/') || crate_name.contains('\\') {
        anyhow::bail!("invalid crate name for cache: path separator not allowed in {crate_name:?}");
    }
    if crate_name == ".." || crate_name == "." {
        anyhow::bail!("invalid crate name for cache: {crate_name:?} is not a valid crate name");
    }
    Ok(())
}

/// Return the per-crate IR cache directory, e.g. `.alef/<crate_name>/`.
fn ir_cache_dir(crate_name: &str) -> PathBuf {
    Path::new(CACHE_DIR).join(crate_name)
}

/// Check if cached IR is still valid for the given crate.
pub fn is_ir_cached(crate_name: &str, cache_key: &CacheKey) -> bool {
    let dir = ir_cache_dir(crate_name);
    let hash_path = dir.join("ir.hash");
    let ir_path = dir.join("ir.json");
    if !ir_path.exists() {
        return false;
    }
    match fs::read_to_string(&hash_path) {
        Ok(cached) => cached.trim() == cache_key.as_str(),
        Err(_) => false,
    }
}

/// Read cached IR for the given crate.
pub fn read_cached_ir(crate_name: &str) -> anyhow::Result<crate::core::ir::ApiSurface> {
    let ir_path = ir_cache_dir(crate_name).join("ir.json");
    let content = fs::read_to_string(&ir_path)?;
    Ok(serde_json::from_str(&content)?)
}

/// Write IR to cache for the given crate.
pub fn write_ir_cache(crate_name: &str, api: &crate::core::ir::ApiSurface, cache_key: &CacheKey) -> anyhow::Result<()> {
    let cache_dir = ir_cache_dir(crate_name);
    fs::create_dir_all(&cache_dir)?;
    fs::write(cache_dir.join("ir.json"), serde_json::to_string_pretty(api)?)?;
    fs::write(cache_dir.join("ir.hash"), cache_key.as_str())?;
    Ok(())
}

pub use crate::cli::cache_identity::{CacheKey, compute_ir_key, compute_lang_hash, compute_stage_hash};
pub(crate) use crate::cli::cache_outputs::{outputs_exist, stamped_outputs_agree_with_disk};

/// Per-crate hashes directory: `.alef/<crate>/hashes/`.
fn hashes_dir(crate_name: &str) -> PathBuf {
    ir_cache_dir(crate_name).join("hashes")
}

/// Check if a language's output is cached for the given crate.
///
/// A hit requires the key to match, every manifested output to still be on disk, AND every
/// manifested output that carries an `alef:hash:` stamp to still agree with that stamp under
/// `inputs_hash`. The last condition is what makes a hit mean anything: [`outputs_exist`]
/// tests only for *existence*, so a generated file edited in place stayed a cache hit, and
/// `alef generate` answered `Generated 0 files` while leaving the edit untouched — a skip
/// indistinguishable from a verification. The stamp comparison is the same one `alef verify`
/// runs (`hash::compute_file_hash` against the embedded value), so a tree that passes verify
/// passes here; unstamped outputs (`generated_header: false`, create-once seeds) have nothing
/// to compare and keep the existence-only rule. ~keep
pub fn is_lang_cached(crate_name: &str, lang: &str, lang_hash: &CacheKey, inputs_hash: &str) -> bool {
    let dir = hashes_dir(crate_name);
    let hash_path = dir.join(format!("{lang}.hash"));
    let manifest_path = dir.join(format!("{lang}.manifest"));
    match fs::read_to_string(&hash_path) {
        Ok(cached) => {
            if cached.trim() != lang_hash.as_str() {
                return false;
            }
            outputs_exist(&manifest_path) && stamped_outputs_agree_with_disk(&manifest_path, inputs_hash)
        }
        Err(_) => false,
    }
}

/// Write language hash and output file manifest for the given crate.
///
/// `output_paths` is whatever the caller passes -- this does not, by itself, cover every
/// phase a language's generation may run (service API, type stubs, public API wrappers
/// are each a separate pipeline call the caller may or may not have made yet). The count
/// is logged at `debug` because a manifest this call leaves at one or two entries for a
/// backend whose language-side output tree is much larger is otherwise silent: nothing
/// else marks the difference between "this backend genuinely emits one file" and "the
/// caller never folded a later phase's output back in" (alef#158). ~keep
pub fn write_lang_hash(crate_name: &str, lang: &str, key: &CacheKey, output_paths: &[PathBuf]) -> anyhow::Result<()> {
    let dir = hashes_dir(crate_name);
    fs::create_dir_all(&dir)?;
    fs::write(dir.join(format!("{lang}.hash")), key.as_str())?;
    write_manifest(&dir.join(format!("{lang}.manifest")), output_paths)?;
    tracing::debug!(
        crate_name,
        lang,
        paths = output_paths.len(),
        "wrote language manifest via write_lang_hash"
    );
    Ok(())
}

/// Replace a language manifest after every generation phase has contributed
/// its files. The language hash itself remains unchanged.
pub fn write_lang_manifest(crate_name: &str, lang: &str, output_paths: &[PathBuf]) -> anyhow::Result<()> {
    let dir = hashes_dir(crate_name);
    fs::create_dir_all(&dir)?;
    write_manifest(&dir.join(format!("{lang}.manifest")), output_paths)?;
    tracing::debug!(
        crate_name,
        lang,
        paths = output_paths.len(),
        "wrote language manifest via write_lang_manifest"
    );
    Ok(())
}

pub fn read_lang_manifest(crate_name: &str, lang: &str) -> Vec<PathBuf> {
    let manifest_path = hashes_dir(crate_name).join(format!("{lang}.manifest"));
    match fs::read_to_string(manifest_path) {
        Ok(content) => content
            .lines()
            .filter(|line| !line.is_empty())
            .map(PathBuf::from)
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// Replace the crate-wide scaffold-ownership manifest with every path the
/// current run's scaffold pass emitted, deliberately including
/// `generated_header: false` seeds (`composer.json`, `package.json`, ...) that
/// carry no `alef:hash:` marker and are therefore invisible to
/// [`write_lang_manifest`]'s `carries_alef_marker()` filter.
///
/// This is the sole durable record that lets `sweep_manifest_orphans`'s
/// unmarkable-manifest route (see `path_is_reclaimable` in
/// `generate/orphans.rs`) reclaim a manifest a later run stops emitting (e.g. a
/// co-located/split PHP layout toggle that drops a second `composer.json`), and
/// it doubles as the current-run "keep" evidence that stops a manifest still
/// being written from ever being mistaken for an orphan of itself.
///
/// Crate-scoped rather than per-language like [`write_lang_manifest`] because
/// `scaffold()` returns a flat, unpartitioned file list; callers that only run
/// scaffold for a `--lang` subset must not call this, or the write here would
/// clobber the recorded paths for every other language's manifests.
pub fn write_scaffold_manifest(crate_name: &str, output_paths: &[PathBuf]) -> anyhow::Result<()> {
    let dir = hashes_dir(crate_name);
    fs::create_dir_all(&dir)?;
    write_manifest(&dir.join("scaffold-ownership.manifest"), output_paths)
}

/// Read the previous run's scaffold-ownership manifest written by
/// [`write_scaffold_manifest`]. Empty when scaffold has never run for this
/// crate under this mechanism (including every run before this manifest was
/// introduced) -- callers must tolerate an empty result as "no known prior
/// scaffold state" rather than "nothing was ever scaffolded".
pub fn read_scaffold_manifest(crate_name: &str) -> Vec<PathBuf> {
    let manifest_path = hashes_dir(crate_name).join("scaffold-ownership.manifest");
    match fs::read_to_string(manifest_path) {
        Ok(content) => content
            .lines()
            .filter(|line| !line.is_empty())
            .map(PathBuf::from)
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// Repo-scoped (rooted at `base_dir`, not crate-scoped) durable record of
/// every path alef owns whose format cannot carry an `alef:hash:` marker.
///
/// **Committed to git on purpose.** For every format that can carry a comment
/// the marker is the proof of ownership and it travels in the repository; for
/// `package.json`, `*.jar` and friends there is no such place to put it, so the
/// proof has to live in a separate file — and that file has to travel too. The
/// pre-#80 record lived at `.alef/scaffold-owned-paths.manifest`, inside the
/// directory alef writes into every consumer's `.gitignore` itself
/// (`cli::pipeline::extract::gitignore::ensure_gitignore`). That made ownership
/// a property of a particular developer's disk: a fresh clone and a warm
/// machine answered differently for the same commit, so CI refused writes a
/// developer's machine permitted. Sitting at the repo root outside `.alef/`,
/// this file is picked up by an ordinary `git add` and every checkout of a
/// commit agrees about what alef owns.
///
/// Deliberately additive and never replaced wholesale, unlike
/// [`write_scaffold_manifest`]'s per-crate, per-run snapshot: the write-time
/// ownership guard in `write_scaffold_files_report` has no crate name in
/// scope (it writes plain scaffold/readme/e2e/docs output keyed only by
/// `base_dir`) and is invoked incrementally from many independent commands
/// (readme, e2e regen, version sync, ...), so each call must extend the
/// record without erasing paths a different call already proved ownership
/// of. Rooted at `base_dir` rather than the process CWD so parallel tests
/// (each with their own tempdir `base_dir`) never share, and race on, the
/// same manifest file. ~keep
pub(super) const OWNERSHIP_MANIFEST: &str = ".alef-ownership.toml";

/// The pre-#80 location of the same record, under the gitignored `.alef/` cache.
///
/// Still *read* (unioned with [`OWNERSHIP_MANIFEST`]) and never written. A
/// working copy that established ownership under an older alef keeps it, so
/// upgrading does not turn every unmarkable file in every existing consumer
/// repo into a refusal at once; the entry migrates into the committed manifest
/// the first time alef performs an authorised write of that path. Dropping the
/// read outright would be correct in the abstract and a mass outage in
/// practice. ~keep
pub(super) const LEGACY_SCAFFOLD_OWNED_PATHS_MANIFEST: &str = "scaffold-owned-paths.manifest";

/// Preamble written above the path list.
///
/// Addressed at a human reading a `git diff` who has no reason to know what the
/// file is for: without it the natural reaction to a mystery dotfile is to
/// gitignore it, which restores exactly the bug this file exists to fix. ~keep
const OWNERSHIP_MANIFEST_HEADER: &str = "\
# alef ownership record -- COMMIT THIS FILE, do not add it to .gitignore.
#
# Lists the alef-generated paths whose format cannot carry an `alef:hash:`
# provenance marker (`package.json`, `*.jar`, ...). Every other format proves
# alef's ownership from the marker in the file itself and never appears here.
# Without this list committed, a fresh clone cannot tell an alef-generated
# `package.json` from a hand-written one and refuses to regenerate it.
#
# Ownership is a fact about history, not about content: a path lands here only
# because alef created the file, or because a human ran `alef adopt` on it.
# Nothing here is inferred by comparing bytes against generated output -- a
# hand-written file that happens to match must never be claimed. Do not hand-add
# entries; run `alef adopt <path>`, read the diff it prints, and let it write.
";

/// Normalize `path` to a `base_dir`-relative key before it is used to read or
/// write the owned-paths manifest.
///
/// Production callers of [`record_scaffold_owned_path`] / [`is_scaffold_owned_path`]
/// do not agree on how they spell `base_dir`: most `bin_cli` commands pass
/// `std::env::current_dir()?` (absolute), while `version_regen.rs`'s regen
/// helpers pass `PathBuf::from(".")` (relative) -- both name the same
/// directory, but `base_dir.join(&file.path)` produces textually different
/// strings from each (`/abs/repo/packages/java/pom.xml` vs
/// `./packages/java/pom.xml`). Storing and looking up that raw joined string
/// meant a record written by one caller was invisible to a lookup from the
/// other: `is_scaffold_owned_path` read as permanently `false` for any file
/// whose write-time caller and check-time caller happened to spell `base_dir`
/// differently, which in practice is most real cross-command sequences (e.g.
/// `alef all` establishes ownership, a later `alef version` bump checks it).
/// Stripping `base_dir` back off before keying makes the record depend only
/// on `file.path`, which every caller already agrees on. Falls back to the
/// path as given if it is not actually rooted at `base_dir` (should not
/// happen in practice, since every caller builds `path` via
/// `base_dir.join(...)`, but a mismatched pair must degrade to "some key"
/// rather than panic). ~keep
pub(super) fn scaffold_owned_path_key(base_dir: &Path, path: &Path) -> String {
    path.strip_prefix(base_dir)
        .unwrap_or(path)
        .to_string_lossy()
        .into_owned()
}

#[derive(serde::Deserialize)]
struct OwnershipManifest {
    #[serde(default)]
    owned_paths: Vec<String>,
}

fn ownership_manifest_path(base_dir: &Path) -> PathBuf {
    base_dir.join(OWNERSHIP_MANIFEST)
}

/// The outcome of reading the committed ownership record, keeping "there is no record yet" apart
/// from "there is a record and we could not read it".
///
/// The two are indistinguishable to a caller handed only a `Vec`, yet they license opposite
/// actions: the first is proof that alef has recorded no ownership, the second is proof of
/// nothing at all. Reading and *rewriting* the record therefore diverge -- see
/// [`read_committed_owned_paths`] and [`record_scaffold_owned_paths`] for which way each goes and
/// why. ~keep
enum OwnedPathsRecord {
    /// No manifest on disk: alef has never recorded ownership under this `base_dir`.
    Absent,
    /// Parsed cleanly; carries every path currently recorded.
    Present(Vec<String>),
    /// A manifest exists but could not be read or parsed. Carries the reason, for the operator.
    Unreadable(String),
}

fn read_owned_paths_record(base_dir: &Path) -> OwnedPathsRecord {
    match fs::read_to_string(ownership_manifest_path(base_dir)) {
        Ok(content) => match toml::from_str::<OwnershipManifest>(&content) {
            Ok(manifest) => OwnedPathsRecord::Present(manifest.owned_paths),
            Err(error) => OwnedPathsRecord::Unreadable(error.to_string()),
        },
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => OwnedPathsRecord::Absent,
        Err(error) => OwnedPathsRecord::Unreadable(error.to_string()),
    }
}

/// Read the committed record for *querying* ownership, treating an unreadable or unparseable file
/// as empty.
///
/// Degrading to "alef owns nothing" is the safe direction for a query: the write-time guard then
/// refuses rather than clobbers, and nothing is silently claimed on the strength of a file we
/// could not actually parse. A hard error here would instead take down every generate in a repo
/// where someone hand-edited the manifest into invalid TOML.
///
/// This is emphatically *not* the safe direction for a caller that rewrites the record from what
/// it read back -- [`record_scaffold_owned_paths`] must refuse instead, because there the same
/// empty `Vec` would erase every recorded path. ~keep
pub(super) fn read_committed_owned_paths(base_dir: &Path) -> Vec<String> {
    match read_owned_paths_record(base_dir) {
        OwnedPathsRecord::Present(paths) => paths,
        OwnedPathsRecord::Absent => Vec::new(),
        OwnedPathsRecord::Unreadable(reason) => {
            tracing::warn!(
                manifest = %OWNERSHIP_MANIFEST,
                reason = %reason,
                "the alef ownership record could not be read; treating every path in it as unowned, \
                 so writes to unmarkable files will be refused until it is repaired"
            );
            Vec::new()
        }
    }
}

pub(super) fn read_legacy_owned_paths(base_dir: &Path) -> Vec<String> {
    let manifest_path = base_dir.join(CACHE_DIR).join(LEGACY_SCAFFOLD_OWNED_PATHS_MANIFEST);
    fs::read_to_string(manifest_path)
        .map(|content| {
            content
                .lines()
                .filter(|line| !line.is_empty())
                .map(str::to_owned)
                .collect()
        })
        .unwrap_or_default()
}

/// The indentation every committed record alef writes uses for one array element per line.
///
/// One fact, one definition. Consumers gate their commits on `poly fmt --check`, whose TOML
/// formatter normalises array elements to two spaces, and a record that indents differently is a
/// gate failure they cannot repair: the next `alef generate` overwrites any hand-formatting. The
/// two sibling records at the repo root used to derive this separately -- the ownership record
/// hand-rendered two spaces while the merge-provenance record inherited four from
/// `toml::to_string_pretty` (whose pretty serializer writes a hard-coded `"    "` per element,
/// with nothing to configure) -- and so disagreed for as long as nothing compared them. ~keep
const RECORD_ARRAY_INDENT: &str = "  ";

/// Widest `key = [...]` line `poly fmt` leaves inline. Measured against the bundled TOML
/// formatter rather than assumed: a two-element array rendering to 120 columns is collapsed onto
/// one line, 121 is left expanded, and no repo in the polyrepo overrides the formatter's column
/// width. Both committed records are rewritten wholesale on every `alef generate`, so emitting a
/// shape the formatter disagrees with is not a one-time cosmetic diff -- alef re-expands what
/// `poly fmt` collapsed, the consumer's format gate rewrites it back, and the file ping-pongs in
/// every commit forever. ~keep
const RECORD_ARRAY_MAX_INLINE_WIDTH: usize = 120;

/// Render `key = [...]` for a committed record array, with no trailing newline: inline when the
/// result fits [`RECORD_ARRAY_MAX_INLINE_WIDTH`], otherwise one element per line at
/// [`RECORD_ARRAY_INDENT`] with a trailing comma.
///
/// Element reprs come from `toml_edit` rather than a hand-rolled escape so a value carrying a
/// quote, a backslash or a control character cannot produce a record that no longer parses. An
/// unparseable record is silent by design (it reads as "alef owns nothing" / "alef proposed
/// nothing"), so a bad escape would not announce itself. ~keep
fn render_record_assignment(key: &str, values: &[String]) -> String {
    let elements: Vec<String> = values
        .iter()
        .map(|value| toml_edit::Value::from(value.as_str()).to_string())
        .collect();

    let inline = format!("{key} = [{}]", elements.join(", "));
    if inline.chars().count() <= RECORD_ARRAY_MAX_INLINE_WIDTH {
        return inline;
    }

    let mut rendered = format!("{key} = [\n");
    for element in &elements {
        rendered.push_str(RECORD_ARRAY_INDENT);
        rendered.push_str(element);
        rendered.push_str(",\n");
    }
    rendered.push(']');
    rendered
}

/// Render the manifest by hand rather than through `toml::to_string`.
///
/// This file is read in `git diff` far more often than by a parser, and a
/// serializer is free to emit the array inline on one line. Adopting a single
/// path would then rewrite the whole line and show as a wholesale replacement,
/// which is precisely the shape that hides an unintended ownership claim from a
/// reviewer. One path per line makes every claim its own `+` line. ~keep
fn render_ownership_manifest(paths: &[String]) -> String {
    format!(
        "{OWNERSHIP_MANIFEST_HEADER}\n{}\n",
        render_record_assignment("owned_paths", paths)
    )
}

/// Record `path` (relative to `base_dir`, or already `base_dir`-joined -- see
/// [`scaffold_owned_path_key`]) as alef-owned, in the committed
/// [`OWNERSHIP_MANIFEST`].
///
/// The write-time guard in `write_scaffold_files_report` consults this for
/// extensions it cannot stamp with an `alef:hash:` marker (`.json`, `.jar`,
/// ...) to distinguish "alef legitimately wrote this before" from "this
/// pre-existed alef and must not be silently claimed." Idempotent: a path
/// already present is left alone, so a converged tree never rewrites the file
/// and never produces a spurious diff.
///
/// Callers must only reach this having established ownership *historically* --
/// alef created the file, or `alef adopt` obtained a human's consent for it.
/// Calling it because the bytes on disk happen to equal this run's output turns
/// a coincidence into a permanent, committed claim over a file nobody adopted;
/// see `cli::pipeline::generate::write::stamp_for_adoption` for the incident
/// that settles why byte-equality is not evidence. ~keep
pub fn record_scaffold_owned_path(base_dir: &Path, path: &Path) -> anyhow::Result<()> {
    record_scaffold_owned_paths(base_dir, std::slice::from_ref(&path))
}

/// Record every path in `paths` as alef-owned in one read-modify-write.
///
/// Semantically identical to calling [`record_scaffold_owned_path`] once per path,
/// which is exactly why it exists: that function reads, parses, re-renders and
/// rewrites the whole manifest per call, so adopting a batch through it costs
/// O(n) manifest parses over an O(n)-sized file — quadratic, and `alef adopt`
/// now has to clear ~12k unmarkable paths in a single consumer-repo migration.
/// One parse and one write for the whole batch makes that linear. The
/// per-path entry point delegates here rather than the reverse so there is a
/// single copy of the locking and rendering logic. ~keep
pub fn record_scaffold_owned_paths(base_dir: &Path, paths: &[&Path]) -> anyhow::Result<()> {
    // Serialised because this is a read-modify-write of one file and
    // `write_files_report` calls it from a rayon `par_iter`: two threads that both
    // observe the pre-write list and then both write it lose one entry, and a lost
    // entry is a path alef silently stops owning — a refusal on the next run, in CI,
    // for a file alef itself created. The old gitignored record had the same race and
    // could be repaired by rerunning locally; a committed one gets the wrong answer
    // captured in a commit instead. Cross-*process* concurrency in one repo is not a
    // supported mode for any of this module's caches. ~keep
    static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _guard = WRITE_LOCK.lock().unwrap_or_else(|error| error.into_inner());

    if paths.is_empty() {
        return Ok(());
    }
    fs::create_dir_all(base_dir)?;
    let record = read_owned_paths_record(base_dir);
    let is_new_manifest = matches!(record, OwnedPathsRecord::Absent);
    let mut recorded: std::collections::BTreeSet<String> = match record {
        OwnedPathsRecord::Present(paths) => paths.into_iter().collect(),
        OwnedPathsRecord::Absent => std::collections::BTreeSet::new(),
        // Refusing is the only non-destructive answer available here. The write below replaces the
        // manifest whole, so continuing from an unparsed read would persist this batch alone and
        // silently un-own every path already in the file -- and that record is the only thing
        // standing between `--clean`/the orphan scan and hand-written unmarkable scaffold files
        // (see `is_scaffold_owned_path`). Unlike the query direction there is no "assume nothing"
        // that preserves anything: unknown ownership survives only if nobody writes. So this
        // fails loudly and names the file, which is a state exactly one hand-edit can produce and
        // one `git checkout` can undo. ~keep
        OwnedPathsRecord::Unreadable(reason) => anyhow::bail!(
            "refusing to update the alef ownership record at {}: it exists but could not be read \
             ({reason}). Repair or restore it (`git checkout -- {OWNERSHIP_MANIFEST}`) and re-run \
             -- rewriting it from a state alef could not read would drop every path already recorded.",
            ownership_manifest_path(base_dir).display()
        ),
    };
    let mut added = false;
    for path in paths {
        added |= recorded.insert(scaffold_owned_path_key(base_dir, path));
    }
    if !added {
        return Ok(());
    }
    let ordered: Vec<String> = recorded.into_iter().collect();
    fs::write(ownership_manifest_path(base_dir), render_ownership_manifest(&ordered))?;
    if is_new_manifest {
        tracing::info!(
            manifest = %OWNERSHIP_MANIFEST,
            "created the alef ownership record: commit it, or a fresh clone cannot regenerate \
             the unmarkable files listed in it"
        );
        // The record did not exist yet when the standing check last ran for this
        // `base_dir`, so it correctly reported nothing. Re-arm it so the run that creates
        // the file is also a run that says it is untracked -- the one moment the operator
        // is unambiguously in a position to stage it. ~keep
        rearm_untracked_record_notice(base_dir);
    }
    note_untracked_required_records(base_dir);
    Ok(())
}

/// The namespace alef reserves for its own bookkeeping artifacts, and the first of the
/// two conditions [`is_alef_derived_output`] requires.
///
/// Already load-bearing elsewhere on exactly this meaning: `snippets::discovery` skips
/// every `.alef-`-prefixed entry when it walks a snippet directory, because a file in
/// this namespace is alef's own state and never documentation a consumer wrote. Naming
/// it here makes that convention checkable rather than a per-site string literal. ~keep
const ALEF_RESERVED_NAME_PREFIX: &str = ".alef-";

/// File names that are **pure derived output**: every byte is recomputed from this run's
/// inputs, nothing but alef writes them, and nothing but alef reads them.
///
/// A name earns a place here only by satisfying **all four** of these, verified against
/// the emitter, not assumed from the extension:
///
/// 1. The format structurally cannot carry an `alef:hash:` marker (strict JSON has no
///    comment syntax), so `write::marker_comment_style` is `None` for it and a missing
///    marker is not evidence of foreign authorship.
/// 2. The name sits in alef's reserved [`ALEF_RESERVED_NAME_PREFIX`] namespace, so no
///    other tool defines a file by that name and a consumer has no reason to author one.
/// 3. Alef is the only *reader* as well as the only writer. This is the condition that
///    separates this list from `orphans::UNMARKABLE_ALEF_MANIFESTS`
///    (`composer.json`, `package.json`): those are also unmarkable and also
///    alef-generated, but a human edits them and a package manager reads them, so
///    trusting their name alone would be a licence to clobber hand-written content.
/// 4. The content has no state a human could have added. Regenerating it wholesale is
///    not a loss of work, it is the *point* — the opposite of a create-once seed, whose
///    whole premise is that the copy on disk has grown past the placeholder alef emitted.
///
/// The snippet-coverage ledger (`e2e::snippets::COVERAGE_MANIFEST`) is the founding
/// member: a `generated_paths`/`generated_metadata` index of what the snippet stage
/// emitted, consumed only by alef's own coverage checks. ~keep
const ALEF_DERIVED_OUTPUT_NAMES: &[&str] = &[crate::e2e::snippets::COVERAGE_MANIFEST];

/// The single named property "this is pure derived output alef must be free to replace".
///
/// Exists because a generated artifact that cannot carry a marker has, until it is
/// answered, exactly the same signature as a hand-grown create-once seed: no marker, no
/// ownership record, `generated_header: false`. Every mechanism that reads that signature
/// — the write-time ownership guard, the write-time create-once skip, and
/// `commands::adopt`'s create-once classifier — must therefore consult *this* property
/// rather than each carving out its own exception, which is how the ledger came to be
/// unblocked at the guard and still refused by adopt (see `adopt::is_create_once_seed`).
///
/// **What this deliberately does not do.** It is not an ownership record and it never
/// widens one: [`is_scaffold_owned_path`] still answers only from what alef actually
/// wrote or a human actually adopted, so nothing here can claim a path by coincidence.
/// It is also not consulted by any *delete* gate — `orphans::path_is_reclaimable` keeps
/// its own, narrower allowlist on purpose, because "alef may overwrite this with freshly
/// computed content" and "alef may remove this file" are different licences and the
/// second one is how a consumer's public API nearly went missing.
///
/// The [`ALEF_RESERVED_NAME_PREFIX`] conjunct is a structural backstop rather than a
/// redundant test: it makes a mistaken future entry in [`ALEF_DERIVED_OUTPUT_NAMES`]
/// inert instead of dangerous. Adding `composer.json` there would grant nothing, because
/// no name a consumer's toolchain defines can live in alef's reserved namespace. ~keep
pub fn is_alef_derived_output(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.starts_with(ALEF_RESERVED_NAME_PREFIX) && ALEF_DERIVED_OUTPUT_NAMES.contains(&name))
}

/// Every alef-authored record whose entire purpose depends on it being committed.
///
/// Both are provenance alef cannot re-derive from anything else: [`OWNERSHIP_MANIFEST`]
/// is the only proof of authorship for a format that cannot carry a marker, and
/// [`TOML_MERGE_PROVENANCE_MANIFEST`] is the only proof of which array values alef itself
/// once proposed. Left out of the commit, each degrades in the *safe* direction — the
/// guard refuses, the prune declines — which is precisely why the failure is silent: the
/// run is green on the machine that holds the untracked file and refuses everything on a
/// fresh clone or in CI, with no signal connecting the two. ~keep
const REQUIRED_COMMITTED_RECORDS: &[&str] = &[OWNERSHIP_MANIFEST, TOML_MERGE_PROVENANCE_MANIFEST];

/// Which of [`REQUIRED_COMMITTED_RECORDS`] exist on disk under `base_dir` but are not
/// tracked by git.
///
/// A record that does not exist is not reported: alef has nothing to depend on yet, so
/// there is no hidden dependency to warn about. `None` from [`git_tracks`] — no git, not
/// a work tree, git failed — is likewise not reported: this must never cry wolf in an
/// export tarball or a container without git, where "untracked" is meaningless rather
/// than wrong.
///
/// Exposed as a pure query, separate from the logging in
/// [`note_untracked_required_records`], so a command can escalate it. The recommended
/// split: `alef all` warns (the operator can still `git add` and the run's output is
/// genuinely correct on their disk), while `alef verify` should fail — a verification
/// that passes only because of an uncommitted local file certifies a state no other
/// checkout has, which is the same defect class as a check that examines nothing. ~keep
pub fn untracked_required_records(base_dir: &Path) -> Vec<&'static str> {
    REQUIRED_COMMITTED_RECORDS
        .iter()
        .filter(|record| base_dir.join(record).is_file() && git_tracks(base_dir, record) == Some(false))
        .copied()
        .collect()
}

/// Whether git tracks `relative` under `base_dir`; `None` when git cannot answer at all.
///
/// `--error-unmatch` is what makes the exit status meaningful: without it `git ls-files`
/// exits 0 and prints nothing for an untracked path, which is indistinguishable from
/// success. A non-zero exit therefore means "git ran and does not track this", and only a
/// failure to spawn (or a repository git refuses to read) yields `None`. `git status`
/// would answer the same question far more expensively and would also fold in staged and
/// dirty state, which is not what is being asked here. ~keep
fn git_tracks(base_dir: &Path, relative: &str) -> Option<bool> {
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(base_dir)
        .args(["ls-files", "--error-unmatch", "--", relative])
        .output()
        .ok()?;
    if output.status.success() {
        return Some(true);
    }
    // Distinguish "git ran and said no" from "there is no repository here to ask". Git
    // reports the latter on stderr and exits non-zero for both, so the exit code alone
    // would turn every non-repo invocation into a false alarm. ~keep
    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("not a git repository") || stderr.contains("this operation must be run in a work tree") {
        return None;
    }
    Some(false)
}

/// Base directories already reported on, so the `git` probe and the warning happen once
/// per repository per process rather than once per path consulted.
///
/// A set rather than a `OnceLock`: the check is keyed on `base_dir`, and a single
/// process legitimately visits several (a multi-crate workspace command, and every test
/// in this module, each with its own tempdir). A `OnceLock` would answer for whichever
/// directory happened to arrive first and stay silent for the rest. ~keep
static REPORTED_RECORD_TRACKING: std::sync::Mutex<Option<std::collections::BTreeSet<PathBuf>>> =
    std::sync::Mutex::new(None);

/// Warn, at most once per `base_dir` per process, about every required record that exists
/// but is untracked.
///
/// Called from the two places alef actually *depends* on such a record —
/// [`is_scaffold_owned_path`] and [`record_scaffold_owned_paths`] — rather than only from
/// the branch that creates it. That is the whole correction: the previous notice was a
/// one-shot `INFO` on the single historical run that first wrote the file, so a repository
/// that missed it once never heard about it again, and every subsequent green run was
/// green because of a file no other checkout has. A standing condition has to be re-stated
/// by every run that relies on it.
///
/// `WARN`, not `ERROR`: per this repo's level contract the run is degraded but correct on
/// this disk, and the output it produced is real. Escalation to a hard failure belongs to
/// `alef verify`, via [`untracked_required_records`]. ~keep
pub(super) fn note_untracked_required_records(base_dir: &Path) {
    {
        let mut reported = REPORTED_RECORD_TRACKING
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let seen = reported.get_or_insert_with(std::collections::BTreeSet::new);
        if !seen.insert(base_dir.to_path_buf()) {
            return;
        }
    }
    for record in untracked_required_records(base_dir) {
        tracing::warn!(
            manifest = %record,
            "alef depends on `{record}` but git does not track it: this run's writes succeeded only \
             because of a file no other checkout has. Run `git add {record}` and commit it, or a \
             fresh clone and CI will refuse to regenerate everything it vouches for"
        );
    }
}

/// Drop `base_dir` from the once-per-repo memo so the next
/// [`note_untracked_required_records`] re-probes it. Only for the moment a required
/// record comes into existence *after* the check already ran for this directory. ~keep
fn rearm_untracked_record_notice(base_dir: &Path) {
    let mut reported = REPORTED_RECORD_TRACKING
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    if let Some(seen) = reported.as_mut() {
        seen.remove(base_dir);
    }
}

/// Repo-scoped (rooted at `base_dir`), COMMITTED record of the array
/// *values* alef's own generator proposed for a TOML merge target, per
/// dotted key path, on the most recent successful merge -- e.g. alef last
/// generated `["target/**", "docs/snippets/**"]` for `poly.toml`'s
/// `discovery.exclude`.
///
/// This is the provenance data [`merge_managed_toml`]'s prune step needs to
/// answer "did alef itself, in a past run, propose this exact value" without
/// guessing from the value's text alone: a value present in `existing` that
/// merely *equals* something alef's current template happens to emit is not
/// evidence of authorship (a consumer's own `[workspace.poly] exclude` entry
/// can coincide), but a value that was captured here -- straight from alef's
/// own generated output, before any merge with consumer content -- genuinely
/// was alef's proposal. A value the consumer configures via
/// `[workspace.poly] exclude` (or `file_safety_exclude`) is echoed back into
/// the generator's own output on every run for as long as it stays
/// configured, so it keeps reappearing here too and is never a prune
/// candidate; it only becomes one if the consumer removes it from their own
/// config, at which point pruning it matches their own subsequent intent.
///
/// Deliberately keyed by the merge target's *relative* path (`"poly.toml"`),
/// not the `base_dir`-joined absolute one, so the record does not depend on
/// how a given invocation happened to express `base_dir`.
///
/// **Committed to git on purpose**, same rationale and same failure mode as
/// [`OWNERSHIP_MANIFEST`]: this used to live at gitignored
/// `.alef/toml-merge-provenance.json`, so a fresh clone or a CI checkout
/// never had a baseline and the prune step could never fire there, no matter
/// how long a value had been gone from alef's own template. Concretely, this
/// is why a consumer's `docs/assets/**` / `docs/snippets/**` `poly.toml`
/// excludes, for a `docs/` tree that had been deleted, had to be removed BY
/// HAND downstream instead of pruning themselves. Sitting at the repo
/// root, this file travels with every checkout of the commit that describes
/// it, so pruning behaves identically on a fresh clone and a warm machine.
///
/// Unlike [`OWNERSHIP_MANIFEST`] this record carries no legacy-gitignored-read
/// fallback and no cross-machine migration bridge: [`OWNERSHIP_MANIFEST`]
/// needs one because losing a positive ownership claim flips the guard to
/// *refuse* a write it used to allow, which upgrading alef must never do to
/// every existing consumer repo at once. Losing a stale prune baseline only
/// means *not pruning* for one run -- never data loss, never a spurious
/// refusal -- so the first run after upgrading simply establishes a fresh
/// committed baseline and pruning resumes from there. ~keep
const TOML_MERGE_PROVENANCE_MANIFEST: &str = ".alef-toml-merge-provenance.toml";

/// Preamble written above the entry list, mirroring [`OWNERSHIP_MANIFEST_HEADER`]:
/// addressed at a human reading a `git diff` who has no reason to know what this
/// mystery dotfile is for. ~keep
const TOML_MERGE_PROVENANCE_HEADER: &str = "\
# alef toml-merge provenance record -- COMMIT THIS FILE, do not add it to .gitignore.
#
# Records, per merge target and key path, the array values alef itself generated on
# the most recent `alef generate` run -- the baseline the poly.toml merge's prune step
# diffs against to tell \"alef proposed this and later stopped\" from \"the consumer
# wrote this by hand.\" Without this file committed, a fresh clone has no baseline, so
# a value alef stops generating can never be pruned there -- it accumulates forever.
#
# Nothing here is inferred by comparing bytes -- an entry is only ever a copy of
# alef's own past `generated` output for the given key path, captured before merging
# with consumer content. Do not hand-edit; it is rewritten on every `alef generate`.
";

/// Deserialize-only on purpose: the record is *written* by
/// [`render_toml_merge_provenance`], because `toml::to_string_pretty` indents array elements
/// four spaces and `toml::to_string` puts the whole array on one line -- neither matches the
/// sibling ownership record or the `poly fmt` gate consumers run. Deriving `Serialize` would put
/// the discarded route back within reach of the next edit. ~keep
#[derive(serde::Deserialize)]
struct TomlMergeProvenanceEntry {
    relative_path: String,
    key_path: String,
    values: Vec<String>,
}

#[derive(Default, serde::Deserialize)]
struct TomlMergeProvenanceFile {
    #[serde(default)]
    entries: Vec<TomlMergeProvenanceEntry>,
}

type TomlMergeProvenance = std::collections::BTreeMap<String, std::collections::BTreeMap<String, Vec<String>>>;

fn toml_merge_provenance_path(base_dir: &Path) -> PathBuf {
    base_dir.join(TOML_MERGE_PROVENANCE_MANIFEST)
}

/// Read the committed record, treating an unreadable or unparseable file as
/// empty -- the same safe direction as [`read_committed_owned_paths`]: a
/// record we could not parse must never be silently treated as "no prior
/// proposal for anything," which here is the *pruning* direction and is
/// exactly as safe as it looks (see [`TOML_MERGE_PROVENANCE_MANIFEST`]'s doc).
fn read_toml_merge_provenance_file(base_dir: &Path) -> TomlMergeProvenance {
    let Ok(content) = fs::read_to_string(toml_merge_provenance_path(base_dir)) else {
        return TomlMergeProvenance::new();
    };
    let Ok(parsed) = toml::from_str::<TomlMergeProvenanceFile>(&content) else {
        return TomlMergeProvenance::new();
    };
    let mut all = TomlMergeProvenance::new();
    for entry in parsed.entries {
        all.entry(entry.relative_path)
            .or_default()
            .insert(entry.key_path, entry.values);
    }
    all
}

/// Read the previously recorded array values for every key path in
/// `relative_path` (e.g. `"poly.toml"`). Empty when nothing was ever
/// recorded for this path -- callers must treat that as "no known prior
/// proposal," never as "alef proposed no arrays."
pub fn read_toml_merge_provenance(
    base_dir: &Path,
    relative_path: &Path,
) -> std::collections::BTreeMap<String, Vec<String>> {
    read_toml_merge_provenance_file(base_dir)
        .remove(&relative_path.to_string_lossy().into_owned())
        .unwrap_or_default()
}

/// Render the record body: one `[[entries]]` table per entry, blank-line separated, arrays
/// rendered by [`render_record_assignment`] like the sibling ownership record.
///
/// Hand-rendered for the indentation, which `toml::to_string_pretty` hard-codes at four spaces
/// while `poly fmt` -- the gate consumers commit through -- normalises to two, leaving this file
/// permanently "would reformat" in every repo alef generates into and unfixable by hand, since
/// the next `alef generate` rewrites it. ~keep
fn render_toml_merge_provenance(entries: &[TomlMergeProvenanceEntry]) -> String {
    let mut body = String::new();
    for entry in entries {
        if !body.is_empty() {
            body.push('\n');
        }
        body.push_str("[[entries]]\n");
        for (key, value) in [("relative_path", &entry.relative_path), ("key_path", &entry.key_path)] {
            body.push_str(key);
            body.push_str(" = ");
            body.push_str(&toml_edit::Value::from(value.as_str()).to_string());
            body.push('\n');
        }
        body.push_str(&render_record_assignment("values", &entry.values));
        body.push('\n');
    }
    body
}

/// Replace the recorded array values for `relative_path` with
/// `arrays_by_key_path` -- this run's freshly generated content, captured
/// before merging with consumer content -- for the next run's comparison.
/// Other merge targets' records are left untouched. Rewrites the committed
/// [`TOML_MERGE_PROVENANCE_MANIFEST`] in full every call, the same
/// read-modify-write shape as [`record_scaffold_owned_paths`] (and, like it,
/// not guarded against concurrent writers from other processes -- not a
/// supported mode for any cache in this module).
pub fn write_toml_merge_provenance(
    base_dir: &Path,
    relative_path: &Path,
    arrays_by_key_path: &std::collections::BTreeMap<String, Vec<String>>,
) -> anyhow::Result<()> {
    let manifest_path = toml_merge_provenance_path(base_dir);
    let is_new_manifest = !manifest_path.exists();

    let mut all = read_toml_merge_provenance_file(base_dir);
    all.insert(relative_path.to_string_lossy().into_owned(), arrays_by_key_path.clone());

    // Both maps are `BTreeMap`s, so this iterates in `(relative_path, key_path)`
    // order already -- no separate sort needed to keep the rendered file diffable.
    let entries: Vec<TomlMergeProvenanceEntry> = all
        .into_iter()
        .flat_map(|(relative_path, by_key_path)| {
            by_key_path
                .into_iter()
                .map(move |(key_path, values)| TomlMergeProvenanceEntry {
                    relative_path: relative_path.clone(),
                    key_path,
                    values,
                })
        })
        .collect();

    fs::create_dir_all(base_dir)?;
    let body = render_toml_merge_provenance(&entries);
    fs::write(&manifest_path, format!("{TOML_MERGE_PROVENANCE_HEADER}\n{body}"))?;
    if is_new_manifest {
        tracing::info!(
            manifest = %TOML_MERGE_PROVENANCE_MANIFEST,
            "created the alef toml-merge provenance record: commit it, or a fresh clone can never \
             prune a value alef stops generating"
        );
    }
    Ok(())
}

/// Check if a stage's output is cached for the given crate.
///
/// A hit requires the key to match, every manifested output to still be on disk, AND every
/// manifested output that carries an `alef:hash:` stamp to still agree with that stamp under
/// `inputs_hash` -- the same three-part check [`is_lang_cached`] runs, for the same reason: the
/// manifest-existence check alone cannot tell a hand-edited stage output (e2e suite, scaffold
/// file, README, docs page) from an untouched one, so a consumer's edit to e.g. a generated e2e
/// test survived a stage-cache hit silently. See [`is_lang_cached`]'s doc for the full incident
/// and [`stamped_outputs_agree_with_disk`]'s doc for why an unstamped output (`generated_header:
/// false`, create-once seeds) keeps the existence-only rule instead of forcing a permanent miss.
/// ~keep
pub fn is_stage_cached(crate_name: &str, stage: &str, stage_hash: &CacheKey, inputs_hash: &str) -> bool {
    let dir = hashes_dir(crate_name);
    let hash_path = dir.join(format!("{stage}.hash"));
    let manifest_path = dir.join(format!("{stage}.manifest"));
    match fs::read_to_string(&hash_path) {
        Ok(cached) => {
            if cached.trim() != stage_hash.as_str() {
                return false;
            }
            outputs_exist(&manifest_path) && stamped_outputs_agree_with_disk(&manifest_path, inputs_hash)
        }
        Err(_) => false,
    }
}

/// Read the manifest of output paths previously written for the given stage.
///
/// Returns an empty `Vec` when the manifest does not exist (either the stage
/// has never been generated for this crate, or the cache predates the manifest
/// format introduced in 0.18.1). Callers should use this to repopulate
/// `current_gen_paths` on a cache hit so the orphan-cleanup pass does not
/// delete files that the previous run wrote but the current run skipped.
pub fn read_stage_paths(crate_name: &str, stage: &str) -> Vec<PathBuf> {
    let dir = hashes_dir(crate_name);
    let manifest_path = dir.join(format!("{stage}.manifest"));
    match fs::read_to_string(&manifest_path) {
        Ok(content) => content
            .lines()
            .filter(|line| !line.is_empty())
            .map(PathBuf::from)
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// Write stage hash and output file manifest for the given crate.
///
/// Takes `&str`, not [`CacheKey`]: manifest-only callers store a plain content hash here and
/// never read it back through [`is_stage_cached`]. See `cache_identity`'s module doc. ~keep
pub fn write_stage_hash(
    crate_name: &str,
    stage: &str,
    stage_hash: &str,
    output_paths: &[PathBuf],
) -> anyhow::Result<()> {
    let dir = hashes_dir(crate_name);
    fs::create_dir_all(&dir)?;
    fs::write(dir.join(format!("{stage}.hash")), stage_hash)?;
    write_manifest(&dir.join(format!("{stage}.manifest")), output_paths)?;
    Ok(())
}

/// Write a manifest of output file paths (one per line).
fn write_manifest(manifest_path: &Path, output_paths: &[PathBuf]) -> anyhow::Result<()> {
    let mut paths: Vec<_> = output_paths.iter().map(|p| p.to_string_lossy()).collect();
    paths.sort_unstable();
    paths.dedup();
    let mut content = paths.join("\n");
    if !content.is_empty() {
        content.push('\n');
    }
    fs::write(manifest_path, content)?;
    Ok(())
}

/// Hash all files in a directory recursively (for e2e fixture hashing).
pub fn hash_directory(dir: &Path) -> anyhow::Result<Vec<u8>> {
    let mut hasher = blake3::Hasher::new();
    if dir.exists() {
        let mut entries: Vec<_> = walkdir(dir)?;
        entries.sort();
        for path in entries {
            let content = fs::read(&path)?;
            hasher.update(path.to_string_lossy().as_bytes());
            hasher.update(&content);
        }
    }
    Ok(hasher.finalize().as_bytes().to_vec())
}

fn walkdir(dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            files.extend(walkdir(&path)?);
        } else {
            files.push(path);
        }
    }
    Ok(files)
}

/// Blake3 hash of a content string.
pub fn hash_content(content: &str) -> String {
    blake3::hash(content.as_bytes()).to_hex().to_string()
}

/// Store generation content hashes: Vec of (path_display, content_hash).
///
/// Call this with pre-computed hashes — use [`hash_content`] on each file's
/// content string before calling.  Stored before writing to disk so hashes
/// reflect pure codegen output, independent of any on-disk formatter.
pub fn write_generation_hashes(name: &str, hashes: &[(String, String)]) -> anyhow::Result<()> {
    let dir = Path::new(CACHE_DIR).join("hashes");
    fs::create_dir_all(&dir)?;
    let lines: Vec<String> = hashes.iter().map(|(p, h)| format!("{p}\t{h}")).collect();
    fs::write(dir.join(format!("{name}.output_hashes")), lines.join("\n"))?;
    Ok(())
}

/// Load stored generation hashes as `HashMap<path, hash>`.
pub fn read_generation_hashes(name: &str) -> anyhow::Result<std::collections::HashMap<String, String>> {
    let path = Path::new(CACHE_DIR)
        .join("hashes")
        .join(format!("{name}.output_hashes"));
    let content = fs::read_to_string(&path)?;
    Ok(content
        .lines()
        .filter(|l| !l.is_empty())
        .filter_map(|l| l.split_once('\t'))
        .map(|(p, h)| (p.to_string(), h.to_string()))
        .collect())
}

/// Clear cache.
pub fn clear_cache() -> anyhow::Result<()> {
    let cache_dir = Path::new(CACHE_DIR);
    if cache_dir.exists() {
        fs::remove_dir_all(cache_dir)?;
    }
    Ok(())
}

/// Show cache status information.
pub fn show_status() {
    let cache_dir = Path::new(CACHE_DIR);
    if !cache_dir.exists() {
        crate::bin_cli::output::line("No cache directory.");
        return;
    }

    crate::bin_cli::output::line("Cache directory: .alef/");

    let ir_path = cache_dir.join("ir.json");
    if ir_path.exists() {
        if let Ok(meta) = fs::metadata(&ir_path) {
            crate::bin_cli::output::line(format!("  ir.json: {} bytes", meta.len()));
        }
    } else {
        crate::bin_cli::output::line("  ir.json: not cached");
    }

    let hashes_dir = cache_dir.join("hashes");
    if hashes_dir.exists() {
        if let Ok(entries) = fs::read_dir(&hashes_dir) {
            let langs: Vec<String> = entries
                .filter_map(|e| e.ok())
                .filter_map(|e| e.path().file_stem().and_then(|s| s.to_str().map(String::from)))
                .collect();
            if langs.is_empty() {
                crate::bin_cli::output::line("  language hashes: none");
            } else {
                crate::bin_cli::output::line(format!("  language hashes: {}", langs.join(", ")));
            }
        }
    } else {
        crate::bin_cli::output::line("  language hashes: none");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::cache_identity::key_for_test as test_key;

    fn api_with_ordered_entries(entries: &[(&str, &str)]) -> crate::core::ir::ApiSurface {
        let mut api = crate::core::ir::ApiSurface {
            crate_name: "sample_crate".to_string(),
            ..Default::default()
        };
        for (name, path) in entries {
            api.excluded_type_paths.insert((*name).to_string(), (*path).to_string());
            api.excluded_trait_names.insert((*name).to_string());
        }
        api
    }

    #[test]
    fn validate_cache_crate_name_accepts_normal_names() {
        validate_cache_crate_name("my-lib").unwrap();
        validate_cache_crate_name("sample_crate").unwrap();
        validate_cache_crate_name("sample_markdown").unwrap();
    }

    #[test]
    fn validate_cache_crate_name_rejects_path_separators() {
        assert!(validate_cache_crate_name("../escape").is_err());
        assert!(validate_cache_crate_name("foo/bar").is_err());
        assert!(validate_cache_crate_name("foo\\bar").is_err());
    }

    #[test]
    fn validate_cache_crate_name_rejects_dot_aliases() {
        assert!(validate_cache_crate_name("..").is_err());
        assert!(validate_cache_crate_name(".").is_err());
    }

    #[test]
    fn validate_cache_crate_name_rejects_nul_byte() {
        assert!(validate_cache_crate_name("foo\0bar").is_err());
    }

    #[test]
    fn ir_cache_dir_scopes_by_crate_name() {
        assert_eq!(ir_cache_dir("crate-a"), Path::new(CACHE_DIR).join("crate-a"));
        assert_eq!(ir_cache_dir("crate-b"), Path::new(CACHE_DIR).join("crate-b"));
        assert_ne!(ir_cache_dir("crate-a"), ir_cache_dir("crate-b"));
    }

    #[test]
    fn repeated_ir_serialization_preserves_cache_and_provenance_hashes() {
        let first = api_with_ordered_entries(&[
            ("Gamma", "sample_crate::gamma::Gamma"),
            ("Alpha", "sample_crate::alpha::Alpha"),
            ("Beta", "sample_crate::beta::Beta"),
        ]);
        let second = api_with_ordered_entries(&[
            ("Beta", "sample_crate::beta::Beta"),
            ("Gamma", "sample_crate::gamma::Gamma"),
            ("Alpha", "sample_crate::alpha::Alpha"),
        ]);

        let first_json = serde_json::to_string_pretty(&first).expect("serialize first IR");
        let second_json = serde_json::to_string_pretty(&second).expect("serialize second IR");
        let generated = "// auto-generated by alef\npub fn sample() {}\n";
        let first_cache_hash = compute_lang_hash(&first_json, "sample", "[sample]\n");
        let second_cache_hash = compute_lang_hash(&second_json, "sample", "[sample]\n");
        let first_file_hash = crate::core::hash::compute_file_hash(first_cache_hash.as_str(), generated);
        let second_file_hash = crate::core::hash::compute_file_hash(second_cache_hash.as_str(), generated);

        assert_eq!(first_json, second_json);
        assert_eq!(first_cache_hash, second_cache_hash);
        assert_eq!(first_file_hash, second_file_hash);
        assert_eq!(
            crate::core::hash::inject_hash_line(generated, &first_file_hash),
            crate::core::hash::inject_hash_line(generated, &second_file_hash)
        );
    }

    #[test]
    fn manifest_is_sorted_deduplicated_and_newline_terminated() {
        let directory = tempfile::tempdir().expect("tempdir");
        let manifest = directory.path().join("rust.manifest");
        let alpha = directory.path().join("alpha.rs");
        let beta = directory.path().join("beta.rs");

        write_manifest(&manifest, &[beta.clone(), alpha.clone(), beta.clone()]).expect("write manifest");

        let content = std::fs::read_to_string(manifest).expect("read manifest");
        assert_eq!(content, format!("{}\n{}\n", alpha.display(), beta.display()));
    }

    #[test]
    fn empty_manifest_is_not_a_cache_hit() {
        let directory = tempfile::tempdir().expect("tempdir");
        let manifest = directory.path().join("rust.manifest");
        std::fs::write(&manifest, "").expect("write empty manifest");

        assert!(!outputs_exist(&manifest));
    }

    /// A manifest alef cannot read is no evidence that the outputs it lists are on disk, in either
    /// of the two ways it can fail to read: absent (what an interrupted `write_lang_hash` leaves,
    /// since the hash and the manifest are two separate writes) or present-but-unreadable.
    ///
    /// Asserted on `is_lang_cached` -- the decision a caller acts on by skipping generation
    /// entirely -- and not on a diagnostic. The defect this pins was a `true` returned while every
    /// message about the cache was already saying the right thing, so a test that watched the
    /// messages would have passed throughout. ~keep
    #[test]
    fn unreadable_output_manifest_is_a_cache_miss() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let generated = tmp.path().join("bindings.py");
        std::fs::write(&generated, "# generated\n").expect("write generated output");
        write_lang_hash("sample-crate", "python", &test_key("hash-1"), &[generated]).expect("write hash and manifest");
        assert!(
            is_lang_cached("sample-crate", "python", &test_key("hash-1"), "inputs-hash"),
            "a matching hash whose manifested outputs are all present must be a hit"
        );

        let manifest = hashes_dir("sample-crate").join("python.manifest");
        std::fs::remove_file(&manifest).expect("remove the manifest, leaving the hash behind");
        assert!(
            !is_lang_cached("sample-crate", "python", &test_key("hash-1"), "inputs-hash"),
            "a hash with no manifest at all must not validate a cache hit"
        );

        std::fs::create_dir_all(&manifest).expect("put something unreadable where the manifest belongs");
        assert!(
            !is_lang_cached("sample-crate", "python", &test_key("hash-1"), "inputs-hash"),
            "a manifest that exists but cannot be read must not validate a cache hit either"
        );
    }

    /// Table-driven coverage of `is_stage_cached` -- the single choke point every generation
    /// stage (scaffold, readme, docs, e2e, test-apps) calls to decide "up to date" versus
    /// "regenerate". A hit requires both a matching input hash and every manifested output path
    /// still present on disk; either failing alone is a miss.
    ///
    /// The empty-recorded-paths row is deliberately a miss, not a hit. `outputs_exist` (shared by
    /// `is_stage_cached` and `is_lang_cached`) treats zero recorded paths as zero evidence of
    /// surviving output, so a stage that recorded nothing never satisfies the cache. Treating it
    /// as a hit instead would mean a stage that fails to record its own outputs -- necessarily a
    /// bug, since every writer here calls `write_stage_hash` with the paths it just wrote --
    /// silently disables output verification for that stage forever, which is the deleted-output
    /// bug this test file exists to catch, just triggered a different way. ~keep
    #[test]
    fn a_deleted_recorded_output_downgrades_a_cache_hit_to_a_miss() {
        struct Scenario {
            name: &'static str,
            stage: &'static str,
            recorded_outputs: &'static [&'static str],
            delete_output: Option<&'static str>,
            query_hash: &'static str,
            expect_hit: bool,
        }

        let scenarios = [
            Scenario {
                name: "matching hash with every recorded output present is a hit",
                stage: "hit",
                recorded_outputs: &["a.rs", "b.rs"],
                delete_output: None,
                query_hash: "hash-1",
                expect_hit: true,
            },
            Scenario {
                name: "matching hash with one recorded output deleted is a miss",
                stage: "deleted-output",
                recorded_outputs: &["a.rs", "b.rs"],
                delete_output: Some("b.rs"),
                query_hash: "hash-1",
                expect_hit: false,
            },
            Scenario {
                name: "non-matching input hash is a miss regardless of outputs",
                stage: "stale-hash",
                recorded_outputs: &["a.rs"],
                delete_output: None,
                query_hash: "hash-2",
                expect_hit: false,
            },
            Scenario {
                name: "empty recorded paths is a miss, not an automatic hit",
                stage: "empty",
                recorded_outputs: &[],
                delete_output: None,
                query_hash: "hash-1",
                expect_hit: false,
            },
        ];

        for scenario in scenarios {
            let tmp = tempfile::tempdir().expect("tempdir");
            let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

            let outputs: Vec<PathBuf> = scenario
                .recorded_outputs
                .iter()
                .map(|name| {
                    let path = tmp.path().join(name);
                    std::fs::write(&path, "// generated\n").expect("write generated output");
                    path
                })
                .collect();
            write_stage_hash("sample-crate", scenario.stage, test_key("hash-1").as_str(), &outputs)
                .expect("write stage hash and manifest");

            if let Some(to_delete) = scenario.delete_output {
                std::fs::remove_file(tmp.path().join(to_delete)).expect("delete recorded output");
            }

            assert_eq!(
                is_stage_cached(
                    "sample-crate",
                    scenario.stage,
                    &test_key(scenario.query_hash),
                    "inputs-hash"
                ),
                scenario.expect_hit,
                "scenario `{}` expected hit={}",
                scenario.name,
                scenario.expect_hit
            );
        }
    }

    /// `write_scaffold_manifest` must round-trip through `read_scaffold_manifest`,
    /// sorted and deduplicated like every other manifest. This is the durable
    /// record `sweep_manifest_orphans`'s unmarkable-manifest route depends on to
    /// know a `composer.json`/`package.json` path was scaffold's on a prior run --
    /// without it, `read_scaffold_manifest` (which does not exist on unfixed code)
    /// cannot be called at all.
    #[test]
    fn scaffold_manifest_round_trips_through_write_and_read() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let composer = tmp.path().join("packages/php/composer.json");
        let cargo_toml = tmp.path().join("Cargo.toml");
        let write_result = write_scaffold_manifest("sample-crate", &[composer.clone(), cargo_toml.clone()]);
        let read_back = read_scaffold_manifest("sample-crate");

        write_result.expect("write scaffold manifest");
        assert_eq!(
            read_back,
            vec![cargo_toml, composer],
            "manifest must round-trip both paths in sorted order"
        );
    }

    /// A crate that has never had scaffold run under this mechanism (including
    /// every run before it existed) must read back empty rather than erroring --
    /// callers treat an empty result as "no known prior scaffold state", never as
    /// proof nothing was ever scaffolded.
    #[test]
    fn scaffold_manifest_reads_empty_when_never_written() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let read_back = read_scaffold_manifest("never-scaffolded-crate");

        assert_eq!(read_back, Vec::<PathBuf>::new());
    }

    /// End-to-end regression for the `composer.json` orphan observed in a consumer repo: proves the
    /// `write_scaffold_manifest`/`read_scaffold_manifest` wiring is what lets
    /// `sweep_manifest_orphans` reclaim an unmarkable manifest a later run stops
    /// emitting. Before this manifest existed, nothing ever recorded
    /// `composer.json`'s path -- `write_lang_manifest` and every
    /// `generate-{lang}-ownership` stage filter scaffold paths through
    /// `carries_alef_marker()`, which `composer.json` never satisfies (it is
    /// emitted with `generated_header: false`) -- so `sweep_manifest_orphans` was
    /// always called with an empty `previous_paths` for this file and could never
    /// reach it, regardless of how permissive `path_is_reclaimable` is. On unfixed
    /// code, `previous_scaffold` here is empty (no prior-run record exists), so
    /// `sweep_manifest_orphans` skips `composer_json` entirely and `removed` is 0,
    /// failing the `assert_eq!(removed, 1, ...)` below.
    #[test]
    fn scaffold_manifest_wiring_lets_next_run_reclaim_dropped_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let package_dir = tmp.path().join("packages/php");
        std::fs::create_dir_all(&package_dir).expect("create package dir");
        let composer_json = package_dir.join("composer.json");
        std::fs::write(&composer_json, "{\n  \"name\": \"acme/demo\"\n}\n").expect("write composer.json");

        write_scaffold_manifest("sample-php", std::slice::from_ref(&composer_json)).expect("write manifest for run 1");

        let previous_scaffold = read_scaffold_manifest("sample-php");
        let keep = std::collections::HashSet::new();
        let removed = crate::cli::pipeline::sweep_manifest_orphans(&previous_scaffold, &keep, &[package_dir], &[])
            .expect("sweep");

        assert_eq!(
            removed, 1,
            "composer.json recorded by run 1's manifest must be reclaimed in run 2"
        );
        assert!(!composer_json.exists(), "orphaned composer.json must be deleted");
    }

    /// Regression for the `alef all` binding-orphan sweep's baseline collision: `alef all`'s
    /// dedicated `all-bindings-{lang}-ownership` stage manifest (read via [`read_stage_paths`],
    /// written via [`write_stage_hash`]) must be a distinct file from `<lang>.manifest`, so that
    /// `write_lang_hash` -- the call `pipeline::generate` makes unconditionally for every language
    /// it regenerates -- can never clobber it. Before `bin_cli/all_commands.rs` moved off
    /// `read_lang_manifest`, reading `<lang>.manifest` as the "previous run" baseline after
    /// `pipeline::generate` had already overwritten it with THIS run's own output meant a dropped
    /// binding could never be seen as missing -- see
    /// `cli::pipeline::generate::generation::lang_manifest_baseline_self_erases_before_the_orphan_sweep_ever_reads_it`
    /// for the pinned reproduction of that old behaviour. This test proves the replacement baseline
    /// does not share that fate.
    #[test]
    fn all_bindings_ownership_baseline_survives_the_lang_manifest_collision_that_used_to_erase_it() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dropped_type_file = tmp.path().join("packages/python/dropped_type.py");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let result = (|| -> anyhow::Result<(Vec<PathBuf>, Vec<PathBuf>)> {
            // Run N-1's write-back: the dedicated ownership stage records the file that still
            // existed back then.
            write_stage_hash(
                "sample",
                "all-bindings-python-ownership",
                "sources-hash-n-minus-1",
                std::slice::from_ref(&dropped_type_file),
            )?;

            // Run N: the type folded into a capsule type, so `pipeline::generate` no longer emits
            // it, and calls `write_lang_hash` (unconditionally, for every regenerated language) with
            // the smaller list -- exactly the call that used to be misread as the sweep's baseline.
            write_lang_hash("sample", "python", &test_key("lang-hash-n"), &[])?;

            let dedicated_baseline = read_stage_paths("sample", "all-bindings-python-ownership");
            let lang_manifest = read_lang_manifest("sample", "python");
            Ok((dedicated_baseline, lang_manifest))
        })();

        let (dedicated_baseline, lang_manifest) = result.expect("baseline read");
        assert_eq!(
            dedicated_baseline,
            vec![dropped_type_file],
            "the dedicated ownership stage must still report last run's file list, unaffected by \
             `write_lang_hash` overwriting the unrelated `<lang>.manifest` file"
        );
        assert!(
            lang_manifest.is_empty(),
            "`<lang>.manifest` itself is expected to have been overwritten by `write_lang_hash` -- \
             that overwrite is legitimate cache-invalidation behaviour; the fix is to stop reading \
             this file as the sweep baseline, not to change what it stores"
        );
    }

    /// With a correct baseline in place, a binding this run no longer emits must be swept -- the
    /// behaviour that never worked while `alef all` read `<lang>.manifest` as its baseline (see
    /// [`all_bindings_ownership_baseline_survives_the_lang_manifest_collision_that_used_to_erase_it`]).
    #[test]
    fn all_bindings_ownership_correct_baseline_sweeps_a_binding_this_run_no_longer_emits() {
        let dir = tempfile::tempdir().expect("tempdir");
        let package_dir = dir.path().join("packages/python");
        std::fs::create_dir_all(&package_dir).expect("create package dir");

        let kept_file = package_dir.join("kept_type.py");
        let dropped_file = package_dir.join("dropped_type.py");
        std::fs::write(&kept_file, "kept\n").expect("write kept file");
        let header = crate::core::hash::header(crate::core::hash::CommentStyle::Hash);
        let hashed = crate::core::hash::inject_hash_line(&header, &"0".repeat(64));
        std::fs::write(&dropped_file, &hashed).expect("write dropped file");

        let previous_paths = vec![kept_file.clone(), dropped_file.clone()];
        let mut keep = std::collections::HashSet::new();
        keep.insert(kept_file.clone());

        let removed =
            crate::cli::pipeline::sweep_manifest_orphans(&previous_paths, &keep, &[package_dir], &[]).expect("sweep");

        assert_eq!(removed, 1, "exactly the dropped binding must be swept");
        assert!(
            !dropped_file.exists(),
            "the binding this run no longer emits must be deleted"
        );
        assert!(
            kept_file.exists(),
            "a binding still in this run's keep set must survive"
        );
    }

    /// A missing baseline -- the state of a fresh `.alef/` cache, or of every crate on the first
    /// `alef all` run after this fix ships -- must sweep nothing. Getting this backwards would
    /// delete a consumer's entire generated tree on upgrade: non-negotiable.
    #[test]
    fn all_bindings_ownership_missing_baseline_sweeps_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let package_dir = dir.path().join("packages/python");
        std::fs::create_dir_all(&package_dir).expect("create package dir");

        let untouched_file = package_dir.join("untouched_type.py");
        let header = crate::core::hash::header(crate::core::hash::CommentStyle::Hash);
        let hashed = crate::core::hash::inject_hash_line(&header, &"0".repeat(64));
        std::fs::write(&untouched_file, &hashed).expect("write file");

        // No prior `write_stage_hash` call for this stage at all -- `read_stage_paths` degrades to
        // an empty `Vec`, mirroring the crate-fresh / upgrade case.
        let previous_paths = read_stage_paths(
            "crate-with-no-prior-all-bindings-ownership-record",
            "all-bindings-python-ownership",
        );
        assert!(previous_paths.is_empty(), "a never-written stage must read back empty");

        let keep = std::collections::HashSet::new();
        let removed =
            crate::cli::pipeline::sweep_manifest_orphans(&previous_paths, &keep, &[package_dir], &[]).expect("sweep");

        assert_eq!(removed, 0, "a missing baseline must sweep nothing, never everything");
        assert!(
            untouched_file.exists(),
            "a file must never be deleted on the strength of an absent baseline"
        );
    }

    /// A path alef never recorded owning must never be swept, even when it sits inside a directory
    /// the sweep is allowed to touch and even when nothing this run keeps. Non-negotiable negative
    /// control: `previous_paths` membership is the only ownership evidence `sweep_manifest_orphans`
    /// accepts, and a file absent from it must be invisible to the sweep regardless of location.
    #[test]
    fn all_bindings_ownership_never_owned_path_is_left_untouched_even_when_present_in_sweep_root() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let result = (|| -> anyhow::Result<(usize, bool, bool, bool)> {
            let package_dir = tmp.path().join("packages/python");
            std::fs::create_dir_all(&package_dir)?;

            let owned_file = package_dir.join("owned_type.py");
            let header = crate::core::hash::header(crate::core::hash::CommentStyle::Hash);
            let hashed = crate::core::hash::inject_hash_line(&header, &"0".repeat(64));
            std::fs::write(&owned_file, &hashed)?;

            let foreign_file = package_dir.join("hand_written.py");
            std::fs::write(&foreign_file, "# never generated by alef\n")?;

            write_stage_hash(
                "sample",
                "all-bindings-python-ownership",
                "sources-hash",
                std::slice::from_ref(&owned_file),
            )?;
            let previous_paths = read_stage_paths("sample", "all-bindings-python-ownership");
            let leaked = previous_paths.iter().any(|path| path.ends_with("hand_written.py"));

            let keep = std::collections::HashSet::new();
            let removed = crate::cli::pipeline::sweep_manifest_orphans(&previous_paths, &keep, &[package_dir], &[])?;
            Ok((removed, owned_file.exists(), foreign_file.exists(), leaked))
        })();

        let (removed, owned_exists, foreign_exists, leaked) = result.expect("sweep");
        assert!(!leaked, "the never-owned file must not have leaked into the baseline");
        assert_eq!(removed, 1, "only the recorded, owned path may be removed");
        assert!(!owned_exists, "the recorded, no-longer-kept binding must be swept");
        assert!(
            foreign_exists,
            "a path alef never recorded owning must survive the sweep"
        );
    }

    /// The positive half: the snippet-coverage ledger is recognised as pure derived
    /// output by the property itself, with no ownership record and no marker anywhere —
    /// which is the state every consumer tree's ledger is actually in.
    #[test]
    fn is_alef_derived_output_recognises_the_snippet_coverage_ledger() {
        assert!(is_alef_derived_output(Path::new(
            "docs-site/src/snippets-generated/.alef-snippet-coverage.json"
        )));
        assert!(is_alef_derived_output(Path::new(
            crate::e2e::snippets::COVERAGE_MANIFEST
        )));
    }

    /// THE load-bearing half. A fix that simply answered `true` for every unmarkable
    /// `generated_header: false` path would satisfy the ledger assertion above on its own
    /// while handing alef a licence to overwrite `composer.json`, `package.json`, a zig
    /// test suite and every other create-once seed — the `e2e/go/helpers_test.go`
    /// incident, re-opened. Each name below is a real generated, unmarkable or
    /// create-once path that a human legitimately grows past alef's placeholder, and none
    /// of them may ever be classified as derived output. ~keep
    #[test]
    fn is_alef_derived_output_refuses_every_hand_growable_generated_path() {
        for hand_growable in [
            "packages/php/composer.json",
            "packages/node/package.json",
            "packages/java/pom.xml",
            "packages/zig/build.zig",
            "packages/zig/test/sample_core_test.zig",
            "packages/dart/test/sample_core_test.dart",
            "e2e/go/helpers_test.go",
        ] {
            assert!(
                !is_alef_derived_output(Path::new(hand_growable)),
                "{hand_growable} is content a human grows: it must never be classified as derived output"
            );
        }
    }

    /// The reserved-namespace conjunct is a backstop, not decoration: it is what makes a
    /// mistaken future entry in `ALEF_DERIVED_OUTPUT_NAMES` inert rather than a licence to
    /// clobber. Pinned by construction so the guard cannot be dropped as redundant. ~keep
    #[test]
    fn is_alef_derived_output_requires_the_reserved_namespace_not_only_list_membership() {
        for name in ALEF_DERIVED_OUTPUT_NAMES {
            assert!(
                name.starts_with(ALEF_RESERVED_NAME_PREFIX),
                "{name} is registered as derived output but sits outside alef's reserved namespace, \
                 so the backstop silently disables it"
            );
        }
        assert!(
            !is_alef_derived_output(Path::new("docs/snippets/.alef-snippet-coverage.json.bak")),
            "a name that merely contains the ledger's name must not match"
        );
        assert!(
            !is_alef_derived_output(Path::new("docs/snippets/.alef-unregistered-state.json")),
            "the reserved prefix alone is not enough: membership in the registry is still required"
        );
    }

    /// Initialise a git work tree in `base_dir`, or `None` when git is unavailable.
    ///
    /// Nothing here commits: `git ls-files --error-unmatch` answers from the index, so `git
    /// add` alone is enough to make a path tracked for the purpose under test. ~keep
    fn init_git_work_tree(base_dir: &Path) -> Option<()> {
        let status = crate::test_support::git_command(base_dir)
            .args(["init", "--quiet"])
            .status()
            .ok()?;
        status.success().then_some(())
    }

    fn git_add(base_dir: &Path, relative: &str) {
        let status = crate::test_support::git_command(base_dir)
            .args(["add", "--", relative])
            .status()
            .expect("git add");
        assert!(status.success(), "git add {relative} failed");
    }

    /// THE new regression: alef writes `.alef-ownership.toml`, depends on it for every
    /// unmarkable file it is allowed to rewrite, tells the reader inside the file to commit
    /// it -- and never once notices that nobody did. A run is then green only because of a
    /// file no other checkout has, and a fresh clone or CI refuses everything the record
    /// vouches for. The condition has to be observable from outside alef, which is what this
    /// query is for. ~keep
    #[test]
    fn untracked_required_records_reports_a_record_git_does_not_track() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        if init_git_work_tree(base).is_none() {
            return;
        }
        record_scaffold_owned_path(base, &base.join("packages/node/package.json")).expect("record");

        assert_eq!(
            untracked_required_records(base),
            vec![OWNERSHIP_MANIFEST],
            "a record alef just created and now depends on must be reported as untracked"
        );
    }

    /// The other half: once the operator stages it, the condition is gone and must stop
    /// being reported. A check that fires unconditionally is a check nobody reads, which is
    /// how the original one-shot notice failed in the first place. ~keep
    #[test]
    fn untracked_required_records_is_silent_once_the_record_is_staged() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        if init_git_work_tree(base).is_none() {
            return;
        }
        record_scaffold_owned_path(base, &base.join("packages/node/package.json")).expect("record");
        git_add(base, OWNERSHIP_MANIFEST);

        assert!(
            untracked_required_records(base).is_empty(),
            "a staged record is tracked; reporting it anyway trains the operator to ignore the warning"
        );
    }

    /// Never cry wolf. Outside a git work tree "untracked" is not a defect, it is a
    /// question with no answer -- an export tarball, a vendored copy, a container with no
    /// git. Reporting there would fire on every such run forever with nothing the operator
    /// could do about it. ~keep
    #[test]
    fn untracked_required_records_is_silent_outside_a_git_work_tree() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        record_scaffold_owned_path(base, &base.join("packages/node/package.json")).expect("record");
        assert!(base.join(OWNERSHIP_MANIFEST).is_file(), "sanity: the record exists");

        assert!(
            untracked_required_records(base).is_empty(),
            "with no repository to ask, tracked-ness is unanswerable and must not be reported as a fault"
        );
    }

    /// A record alef has never had reason to write is not a hidden dependency, so an empty
    /// repository must stay quiet. ~keep
    #[test]
    fn untracked_required_records_ignores_a_record_that_does_not_exist_yet() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        if init_git_work_tree(base).is_none() {
            return;
        }

        assert!(untracked_required_records(base).is_empty());
    }

    #[test]
    fn scaffold_owned_path_round_trips_and_is_idempotent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        let target = base.join("packages/java/pom.xml");

        assert!(!is_scaffold_owned_path(base, &target), "must start unrecorded");

        record_scaffold_owned_path(base, &target).expect("record");
        record_scaffold_owned_path(base, &target).expect("record again (idempotent)");

        assert!(is_scaffold_owned_path(base, &target));
        let manifest = std::fs::read_to_string(base.join(OWNERSHIP_MANIFEST)).expect("read manifest");
        assert_eq!(
            manifest.matches("packages/java/pom.xml").count(),
            1,
            "recording the same path twice must not duplicate it, got:\n{manifest}"
        );
        assert!(
            !base.join(".alef").join(LEGACY_SCAFFOLD_OWNED_PATHS_MANIFEST).exists(),
            "the gitignored legacy record must no longer be written, got:\n{manifest}"
        );
    }

    /// The batch entry point must be indistinguishable in outcome from the per-path
    /// one — same entries, same order, same idempotence, and existing entries left
    /// alone — because it exists purely to collapse N manifest parses into one for a
    /// bulk `alef adopt`. If it ever diverges in *result*, the fast path is silently
    /// recording something different from what the reviewed path would have. ~keep
    #[test]
    fn batch_recording_matches_per_path_recording_entry_for_entry() {
        let batched = tempfile::tempdir().expect("tempdir");
        let one_at_a_time = tempfile::tempdir().expect("tempdir");
        let relatives = [
            "docs/snippets/python/api/z.md",
            "packages/node/package.json",
            "docs/snippets/python/api/a.md",
            "packages/java/pom.xml",
        ];

        record_scaffold_owned_path(batched.path(), &batched.path().join("pre/existing.json")).expect("seed");
        record_scaffold_owned_path(one_at_a_time.path(), &one_at_a_time.path().join("pre/existing.json"))
            .expect("seed");

        let joined: Vec<PathBuf> = relatives.iter().map(|rel| batched.path().join(rel)).collect();
        let refs: Vec<&Path> = joined.iter().map(PathBuf::as_path).collect();
        record_scaffold_owned_paths(batched.path(), &refs).expect("batch record");
        record_scaffold_owned_paths(batched.path(), &refs).expect("batch record again (idempotent)");
        for relative in relatives {
            record_scaffold_owned_path(one_at_a_time.path(), &one_at_a_time.path().join(relative)).expect("record");
        }

        assert_eq!(
            std::fs::read_to_string(batched.path().join(OWNERSHIP_MANIFEST)).expect("batched manifest"),
            std::fs::read_to_string(one_at_a_time.path().join(OWNERSHIP_MANIFEST)).expect("sequential manifest"),
        );
        for relative in relatives {
            assert!(is_scaffold_owned_path(batched.path(), &batched.path().join(relative)));
        }
        assert!(
            is_scaffold_owned_path(batched.path(), &batched.path().join("pre/existing.json")),
            "a batch must extend the record, never replace it"
        );
    }

    /// The record must be a file `git add` picks up, not one alef itself
    /// gitignores. `ensure_gitignore` writes `.alef/` into every consumer's
    /// `.gitignore` (`cli::pipeline::extract::gitignore`), so a record stored
    /// under that directory can never travel with the commit it describes --
    /// which is the entire #80 reproducibility hole. Asserting the location and
    /// the parseability together, because a committed file nobody can parse is
    /// worth no more than an ignored one. ~keep
    #[test]
    fn ownership_record_lives_outside_the_gitignored_cache_and_is_valid_toml() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();

        record_scaffold_owned_path(base, &base.join("packages/typescript/package.json")).expect("record");

        let manifest_path = base.join(OWNERSHIP_MANIFEST);
        assert!(manifest_path.exists(), "the record must exist at the repo root");
        assert!(
            !manifest_path.starts_with(base.join(CACHE_DIR)),
            "the record must not live under the gitignored `{CACHE_DIR}` directory"
        );
        let content = std::fs::read_to_string(&manifest_path).expect("read manifest");
        let parsed: OwnershipManifest = toml::from_str(&content).expect("the record must be valid TOML");
        assert_eq!(parsed.owned_paths, vec!["packages/typescript/package.json".to_owned()]);
    }

    /// A fresh clone carries the committed record but no `.alef/` cache at all.
    /// Simulated by recording into one `base_dir` and reading the manifest back
    /// from a second, cache-less one -- the machine-local half of the answer is
    /// absent there by construction, so a `true` can only have come from the
    /// committed file.
    #[test]
    fn committed_record_answers_identically_on_a_cache_less_clone() {
        let warm = tempfile::tempdir().expect("tempdir warm");
        let clone = tempfile::tempdir().expect("tempdir clone");
        let relative = std::path::Path::new("packages/typescript/package.json");

        record_scaffold_owned_path(warm.path(), &warm.path().join(relative)).expect("record");
        std::fs::copy(
            warm.path().join(OWNERSHIP_MANIFEST),
            clone.path().join(OWNERSHIP_MANIFEST),
        )
        .expect("check out the committed record");

        assert!(
            !clone.path().join(CACHE_DIR).exists(),
            "the simulated clone must have no machine-local cache"
        );
        assert!(
            is_scaffold_owned_path(clone.path(), &clone.path().join(relative)),
            "a fresh clone must agree with the warm machine about what alef owns"
        );
    }

    /// One bad hand-edit must cost the edit, not the record. `record_scaffold_owned_paths`
    /// rewrites the manifest whole from what it read back, so before this was fixed an
    /// unparseable line made the read return an empty `Vec` and the write persist only the current
    /// batch -- silently un-owning every path recorded before it, in a committed file.
    ///
    /// The assertion is on the bytes on disk after the call, because that is what is destroyed.
    /// A test on the error text alone would pass just as well against code that emitted the
    /// message and then truncated the file anyway. ~keep
    #[test]
    fn malformed_ownership_record_refuses_rather_than_dropping_recorded_paths() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        record_scaffold_owned_path(base, &base.join("packages/java/pom.xml")).expect("seed the record");

        let manifest_path = base.join(OWNERSHIP_MANIFEST);
        let seeded = std::fs::read_to_string(&manifest_path).expect("read the seeded record");
        let corrupted = format!("{seeded}this line is not toml\n");
        std::fs::write(&manifest_path, &corrupted).expect("hand-edit the record into invalid TOML");

        let newly_scaffolded = base.join("packages/node/package.json");
        let error = record_scaffold_owned_paths(base, &[newly_scaffolded.as_path()])
            .expect_err("recording against an unreadable record must fail rather than rewrite it");

        assert_eq!(
            std::fs::read_to_string(&manifest_path).expect("read the record after the refusal"),
            corrupted,
            "the refused run must leave the record byte-identical, keeping every recorded path"
        );
        assert!(
            error.to_string().contains(OWNERSHIP_MANIFEST),
            "the failure must name the file the operator has to repair, got: {error}"
        );
    }

    /// An unparseable record must read as "alef owns nothing" rather than
    /// panicking or, far worse, being treated as ownership of everything.
    #[test]
    fn unparseable_ownership_record_claims_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        std::fs::write(base.join(OWNERSHIP_MANIFEST), "this is not = = valid toml [[[").expect("write junk");

        assert!(!is_scaffold_owned_path(
            base,
            &base.join("packages/typescript/package.json")
        ));
    }

    /// The record is itself a `.toml` file at the repo root, so `alef verify`'s walk
    /// reaches it. Its explanatory header must not read as a provenance marker
    /// ([`crate::core::hash::content_has_alef_marker`] matches the substrings
    /// "auto-generated by alef" / "Generated by alef" anywhere in the first ten lines):
    /// a file that claims to be alef-stamped but is outside the generated-file hash
    /// pipeline has no computable hash, so it would surface as permanently stale. The
    /// header is prose a human wrote and is easy to reword into a false positive, which
    /// is why this is pinned rather than left to care. ~keep
    #[test]
    fn ownership_record_header_does_not_read_as_a_provenance_marker() {
        let rendered = render_ownership_manifest(&["packages/typescript/package.json".to_owned()]);
        assert!(
            !crate::core::hash::content_has_alef_marker(&rendered),
            "the record's own header must not look like an alef provenance marker, got:\n{rendered}"
        );
    }

    /// A path containing a quote or a backslash (a Windows-spelled key, a perverse but
    /// legal filename) must survive the hand-rolled TOML writer. Escaping it wrongly
    /// produces a manifest that no longer parses, and an unparseable manifest reads as
    /// "alef owns nothing" -- so the failure would not be loud, it would quietly un-own
    /// every path in the repo at once. ~keep
    #[test]
    fn ownership_record_escapes_paths_that_need_it() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        let awkward = "packages/we\"ird\\name.json";

        record_scaffold_owned_path(base, &base.join(awkward)).expect("record");
        record_scaffold_owned_path(base, &base.join("packages/plain.json")).expect("record plain");

        let content = std::fs::read_to_string(base.join(OWNERSHIP_MANIFEST)).expect("read manifest");
        let parsed: OwnershipManifest = toml::from_str(&content).expect("manifest must stay parseable");
        assert!(
            parsed.owned_paths.iter().any(|path| path == awkward),
            "the awkward path must round-trip unchanged, got: {:?}",
            parsed.owned_paths
        );
        assert!(is_scaffold_owned_path(base, &base.join(awkward)));
        assert!(
            is_scaffold_owned_path(base, &base.join("packages/plain.json")),
            "a bad escape must not take the rest of the record down with it"
        );
    }

    #[test]
    fn scaffold_owned_path_is_scoped_to_base_dir() {
        let dir_a = tempfile::tempdir().expect("tempdir a");
        let dir_b = tempfile::tempdir().expect("tempdir b");
        let target = std::path::PathBuf::from("packages/java/pom.xml");

        record_scaffold_owned_path(dir_a.path(), &dir_a.path().join(&target)).expect("record in a");

        assert!(!is_scaffold_owned_path(dir_b.path(), &dir_b.path().join(&target)));
    }

    /// Regression: a record written with an *absolute* `base_dir`
    /// (`std::env::current_dir()`, what most `bin_cli` commands pass) must
    /// still be found by a lookup that expresses `base_dir` *relatively*
    /// (`PathBuf::from(".")`, what `version_regen.rs`'s regen helpers pass)
    /// when both name the same directory -- and vice versa. Before
    /// `scaffold_owned_path_key` normalized the stored key back to
    /// `file.path`, the two representations produced different
    /// `base_dir.join(path)` strings for the same file, so
    /// `is_scaffold_owned_path` read as permanently `false` for any path
    /// whose owning write and later check happened to come from commands
    /// that spell `base_dir` differently -- which most real multi-command
    /// sequences do (e.g. `alef all` establishes ownership, a later
    /// `alef version` bump checks it), making the manifest effectively inert
    /// even though it was being written and read from the exact same file on
    /// disk the whole time.
    #[test]
    fn scaffold_owned_path_matches_across_absolute_and_relative_base_dir_spellings() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let _cwd = crate::test_support::CwdGuard::enter(tmp.path());

        let absolute_base = std::env::current_dir().expect("absolute cwd");
        let relative_base = Path::new(".");
        let relative_target = relative_base.join("packages/java/pom.xml");

        let result = (|| -> anyhow::Result<(bool, bool)> {
            // Written as an absolute-`base_dir` caller (e.g. a `bin_cli` command) would.
            record_scaffold_owned_path(&absolute_base, &absolute_base.join("packages/java/pom.xml"))?;
            // Checked as a relative-`base_dir` caller (e.g. `version_regen.rs`) would.
            let found_from_relative = is_scaffold_owned_path(relative_base, &relative_target);
            // And the reverse direction: written relatively, checked absolutely.
            record_scaffold_owned_path(relative_base, &relative_base.join("packages/csharp/foo.csproj"))?;
            let found_from_absolute =
                is_scaffold_owned_path(&absolute_base, &absolute_base.join("packages/csharp/foo.csproj"));
            Ok((found_from_relative, found_from_absolute))
        })();

        let (found_from_relative, found_from_absolute) = result.expect("record/check round-trip");
        assert!(
            found_from_relative,
            "a record written with an absolute base_dir must be found by a relative-base_dir lookup"
        );
        assert!(
            found_from_absolute,
            "a record written with a relative base_dir must be found by an absolute-base_dir lookup"
        );
    }

    /// The record must be a file `git add` picks up, not one alef itself gitignores --
    /// same #80-shaped concern as [`ownership_record_lives_outside_the_gitignored_cache_and_is_valid_toml`],
    /// applied to the merge-provenance baseline. ~keep
    #[test]
    fn toml_merge_provenance_record_lives_outside_the_gitignored_cache_and_is_valid_toml() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        let mut arrays = std::collections::BTreeMap::new();
        arrays.insert(
            "discovery.exclude".to_string(),
            vec!["target/**".to_string(), "docs/assets/**".to_string()],
        );

        write_toml_merge_provenance(base, Path::new("poly.toml"), &arrays).expect("write provenance");

        let manifest_path = base.join(TOML_MERGE_PROVENANCE_MANIFEST);
        assert!(manifest_path.exists(), "the record must exist at the repo root");
        assert!(
            !manifest_path.starts_with(base.join(CACHE_DIR)),
            "the record must not live under the gitignored `{CACHE_DIR}` directory"
        );
        let content = std::fs::read_to_string(&manifest_path).expect("read manifest");
        let parsed: TomlMergeProvenanceFile = toml::from_str(&content).expect("the record must be valid TOML");
        assert_eq!(parsed.entries.len(), 1);
        assert_eq!(parsed.entries[0].relative_path, "poly.toml");
        assert_eq!(parsed.entries[0].key_path, "discovery.exclude");
        assert_eq!(
            parsed.entries[0].values,
            vec!["target/**".to_string(), "docs/assets/**".to_string()]
        );
    }

    /// A fresh clone carries the committed record but no `.alef/` cache at all. Simulated
    /// by writing into one `base_dir` and reading the manifest back from a second,
    /// cache-less one -- mirrors [`committed_record_answers_identically_on_a_cache_less_clone`]
    /// for the merge-provenance baseline.
    #[test]
    fn toml_merge_provenance_answers_identically_on_a_cache_less_clone() {
        let warm = tempfile::tempdir().expect("tempdir warm");
        let clone = tempfile::tempdir().expect("tempdir clone");
        let mut arrays = std::collections::BTreeMap::new();
        arrays.insert("discovery.exclude".to_string(), vec!["docs/assets/**".to_string()]);

        write_toml_merge_provenance(warm.path(), Path::new("poly.toml"), &arrays).expect("write provenance");
        std::fs::copy(
            warm.path().join(TOML_MERGE_PROVENANCE_MANIFEST),
            clone.path().join(TOML_MERGE_PROVENANCE_MANIFEST),
        )
        .expect("check out the committed record");

        assert!(
            !clone.path().join(CACHE_DIR).exists(),
            "the simulated clone must have no machine-local cache"
        );
        assert_eq!(
            read_toml_merge_provenance(warm.path(), Path::new("poly.toml")),
            read_toml_merge_provenance(clone.path(), Path::new("poly.toml")),
            "a fresh clone must agree with the warm machine about alef's prior proposal"
        );
    }

    /// An unparseable record must read as "no prior proposal for anything" -- the prune
    /// step then removes nothing, rather than panicking or, far worse, guessing.
    #[test]
    fn unparseable_toml_merge_provenance_record_prunes_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        std::fs::write(
            base.join(TOML_MERGE_PROVENANCE_MANIFEST),
            "this is not = = valid toml [[[",
        )
        .expect("write junk");

        assert_eq!(
            read_toml_merge_provenance(base, Path::new("poly.toml")),
            std::collections::BTreeMap::new()
        );
    }

    /// The record is itself a `.toml` file at the repo root, so `alef verify`'s walk
    /// reaches it. Its explanatory header must not read as a provenance marker, for the
    /// same reason pinned in [`ownership_record_header_does_not_read_as_a_provenance_marker`].
    #[test]
    fn toml_merge_provenance_header_does_not_read_as_a_provenance_marker() {
        assert!(
            !crate::core::hash::content_has_alef_marker(TOML_MERGE_PROVENANCE_HEADER),
            "the record's own header must not look like an alef provenance marker, got:\n{TOML_MERGE_PROVENANCE_HEADER}"
        );
    }

    /// Writing a second, unrelated merge target's provenance must not clobber a
    /// previously recorded one -- this is the read-modify-write round trip
    /// [`write_toml_merge_provenance`]'s doc promises ("other merge targets' records are
    /// left untouched"), pinned so a future rewrite of the read-modify-write step cannot
    /// silently drop it.
    #[test]
    fn toml_merge_provenance_write_extends_rather_than_replaces_other_targets() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        let mut poly_arrays = std::collections::BTreeMap::new();
        poly_arrays.insert("discovery.exclude".to_string(), vec!["target/**".to_string()]);
        write_toml_merge_provenance(base, Path::new("poly.toml"), &poly_arrays).expect("write poly.toml provenance");

        let mut other_arrays = std::collections::BTreeMap::new();
        other_arrays.insert("some.key".to_string(), vec!["value".to_string()]);
        write_toml_merge_provenance(base, Path::new("other.toml"), &other_arrays).expect("write other.toml provenance");

        assert_eq!(
            read_toml_merge_provenance(base, Path::new("poly.toml")),
            poly_arrays,
            "recording a second merge target's provenance must leave the first's untouched"
        );
        assert_eq!(read_toml_merge_provenance(base, Path::new("other.toml")), other_arrays);
    }

    /// The leading whitespace of every array-element line in a rendered record.
    ///
    /// An element line is any line between one ending in `= [` and the `]` that closes it, which
    /// is the only structure both records share -- deliberately derived from the rendered bytes
    /// rather than from [`RECORD_ARRAY_INDENT`], so the comparison below cannot agree with itself
    /// by construction. ~keep
    fn array_element_indents(rendered: &str) -> Vec<String> {
        let mut indents = Vec::new();
        let mut inside_array = false;
        for line in rendered.lines() {
            let trimmed = line.trim();
            if inside_array {
                if trimmed == "]" {
                    inside_array = false;
                } else {
                    indents.push(line.chars().take_while(|character| character.is_whitespace()).collect());
                }
            } else if trimmed.ends_with("= [") {
                inside_array = true;
            }
        }
        indents
    }

    /// The two committed records sit side by side in a consumer's repo root and pass through the
    /// same `poly fmt --check` gate, so how they indent an array element is one fact -- and it was
    /// derived in two places that never compared notes: the ownership record hand-rendered two
    /// spaces while the provenance record inherited `toml::to_string_pretty`'s four, which made
    /// every regenerated tree unreleasable downstream (the gate says "would reformat", and
    /// hand-formatting is overwritten by the next `alef generate`).
    ///
    /// Comparing the two writers' actual output, rather than pinning the literal two spaces, is
    /// what makes the next divergence fail here whichever side moves. ~keep
    #[test]
    fn both_committed_records_indent_array_elements_identically() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        // Long enough that neither record collapses to one line -- there is no element
        // indentation to compare in the inline shape. ~keep
        let values = vec![
            "packages/generated-bindings/some-language/build/**".to_string(),
            "packages/generated-bindings/other-language/build/**".to_string(),
            "packages/generated-bindings/third-language/build/**".to_string(),
        ];
        let mut arrays = std::collections::BTreeMap::new();
        arrays.insert("discovery.exclude".to_string(), values.clone());

        write_toml_merge_provenance(base, Path::new("poly.toml"), &arrays).expect("write provenance");
        let provenance = std::fs::read_to_string(base.join(TOML_MERGE_PROVENANCE_MANIFEST)).expect("read provenance");
        let ownership = render_ownership_manifest(&values);

        let provenance_indents = array_element_indents(&provenance);
        let ownership_indents = array_element_indents(&ownership);
        assert_eq!(
            ownership_indents.len(),
            values.len(),
            "apparatus check: the ownership record must render one element line per value, got:\n{ownership}"
        );
        assert_eq!(
            provenance_indents.len(),
            values.len(),
            "apparatus check: the provenance record must render one element line per value, got:\n{provenance}"
        );
        assert_eq!(
            provenance_indents, ownership_indents,
            "the two committed records must indent array elements identically, got \
             {provenance_indents:?} for the provenance record and {ownership_indents:?} for the \
             ownership record"
        );
    }

    /// Both committed records are rewritten wholesale on every `alef generate`, so the shape they
    /// emit has to be the shape `poly fmt` would leave alone. It was not: a short array was
    /// written one element per line, the consumer's format gate collapsed it onto one line, and
    /// the next `alef generate` expanded it again -- the file changed in every commit forever and
    /// no one could stop it by hand. The boundary below is measured against the bundled formatter
    /// (120 columns inline is collapsed, 121 is left expanded), not assumed. ~keep
    #[test]
    fn record_arrays_collapse_exactly_where_the_format_gate_collapses_them() {
        let short = render_record_assignment("values", &["one".to_string(), "two".to_string()]);
        assert_eq!(
            short, r#"values = ["one", "two"]"#,
            "an array the format gate would collapse must be written inline"
        );

        let empty = render_record_assignment("values", &[]);
        assert_eq!(empty, "values = []", "an empty array has nothing to spread over lines");

        // Sized so `values = [...]` is exactly RECORD_ARRAY_MAX_INLINE_WIDTH columns.
        let filler = "x".repeat(RECORD_ARRAY_MAX_INLINE_WIDTH - r#"values = [""]"#.len());
        let at_limit = render_record_assignment("values", std::slice::from_ref(&filler));
        assert_eq!(
            at_limit.chars().count(),
            RECORD_ARRAY_MAX_INLINE_WIDTH,
            "apparatus check: the fixture must land exactly on the limit, got:\n{at_limit}"
        );
        assert!(
            !at_limit.contains('\n'),
            "a line exactly at the limit is still collapsed by the gate, so it must stay inline"
        );

        let over_limit = render_record_assignment("values", &[format!("{filler}y")]);
        assert_eq!(
            over_limit,
            format!("values = [\n{RECORD_ARRAY_INDENT}\"{filler}y\",\n]"),
            "one column past the limit the gate leaves the array expanded, so alef must too"
        );
    }

    /// A value carrying a quote or a backslash must survive the hand-rolled provenance writer,
    /// for the same reason [`ownership_record_escapes_paths_that_need_it`] pins it for the other
    /// record: the record is written by hand rather than by a serializer, and an unparseable one
    /// reads as "alef proposed nothing", so a bad escape silently disables pruning instead of
    /// failing. ~keep
    #[test]
    fn toml_merge_provenance_escapes_values_that_need_it() {
        let dir = tempfile::tempdir().expect("tempdir");
        let base = dir.path();
        let awkward = vec!["we\"ird\\value/**".to_string(), "plain/**".to_string()];
        let mut arrays = std::collections::BTreeMap::new();
        arrays.insert("discovery.ex\"clude".to_string(), awkward);

        write_toml_merge_provenance(base, Path::new("poly.toml"), &arrays).expect("write provenance");

        assert_eq!(
            read_toml_merge_provenance(base, Path::new("poly.toml")),
            arrays,
            "an awkward key path and value must round-trip through the hand-rolled writer unchanged"
        );
    }
}