ym 0.3.66

Yummy - A modern Java build tool
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

const FINGERPRINT_FILE: &str = "fingerprints.json";
const BUILD_MANIFEST_FILE: &str = "build-manifest.json";

// Hash domain separator tags for cache key computation
mod tag {
    pub const SRC: &[u8] = b"src:";
    pub const DEP: &[u8] = b"dep:";
    pub const MVN: &[u8] = b"mvn:";
    pub const CP: &[u8] = b"cp:";
    pub const AP: &[u8] = b"ap:";
    pub const VER: &[u8] = b"ver:";
    pub const ENC: &[u8] = b"enc:";
    pub const LINT: &[u8] = b"lint:";
    pub const ARG: &[u8] = b"arg:";
}

/// Tracks source file fingerprints for incremental compilation.
///
/// Strategy:
///   file changed → compute sourceHash
///     → sourceHash unchanged → skip
///     → sourceHash changed → compile → compute abiHash
///       → abiHash unchanged → only update .class, don't propagate
///       → abiHash changed → recompile all dependents (recursive)
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct Fingerprints {
    /// source_path (relative to project) -> entry
    entries: HashMap<String, FileEntry>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct FileEntry {
    pub source_hash: String,
    pub abi_hash: Option<String>,
    pub mtime_secs: u64,
}

impl Fingerprints {
    pub fn load(cache_dir: &Path) -> Self {
        let path = cache_dir.join(FINGERPRINT_FILE);
        if let Ok(content) = std::fs::read_to_string(&path) {
            serde_json::from_str(&content).unwrap_or_default()
        } else {
            Self::default()
        }
    }

    pub fn save(&self, cache_dir: &Path) -> Result<()> {
        std::fs::create_dir_all(cache_dir)?;
        let path = cache_dir.join(FINGERPRINT_FILE);
        let content = serde_json::to_string(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Find source files that have changed since last compilation.
    /// Returns (changed_files, all_files).
    pub fn get_changed_files(&self, source_dirs: &[PathBuf]) -> Result<(Vec<PathBuf>, Vec<PathBuf>)> {
        let mut changed = Vec::new();
        let mut all = Vec::new();
        for (path, rel_key, mtime) in walk_java_files(source_dirs)? {
            all.push(path.clone());
            if let Some(existing) = self.entries.get(&rel_key) {
                if existing.mtime_secs == mtime {
                    continue;
                }
                if hash_file(&path)? == existing.source_hash {
                    continue;
                }
            }
            changed.push(path);
        }
        Ok((changed, all))
    }

    /// Update fingerprint for a compiled file.
    pub fn update_source(&mut self, path: &Path, source_hash: &str, mtime_secs: u64) {
        let key = crate::normalize_cache_path(path);
        let entry = self.entries.entry(key).or_insert_with(|| FileEntry {
            source_hash: String::new(),
            abi_hash: None,
            mtime_secs: 0,
        });
        entry.source_hash = source_hash.to_string();
        entry.mtime_secs = mtime_secs;
    }

    /// Update ABI hash for a compiled class.
    pub fn update_abi(&mut self, source_path: &Path, abi_hash: &str) {
        let key = crate::normalize_cache_path(source_path);
        if let Some(entry) = self.entries.get_mut(&key) {
            entry.abi_hash = Some(abi_hash.to_string());
        }
    }

    /// Check if the ABI of a source file has changed.
    /// Returns true if ABI changed or if no previous ABI recorded.
    #[allow(dead_code)]
    pub fn abi_changed(&self, source_path: &Path, new_abi_hash: &str) -> bool {
        let key = crate::normalize_cache_path(source_path);
        match self.entries.get(&key) {
            Some(entry) => entry.abi_hash.as_deref() != Some(new_abi_hash),
            None => true,
        }
    }

    /// Remove entries for files that no longer exist.
    /// Returns the list of removed source paths.
    pub fn prune(&mut self, existing_files: &[PathBuf]) -> Vec<String> {
        let existing_keys: std::collections::HashSet<String> = existing_files
            .iter()
            .map(|p| crate::normalize_cache_path(p))
            .collect();
        let removed: Vec<String> = self.entries.keys()
            .filter(|k| !existing_keys.contains(k.as_str()))
            .cloned()
            .collect();
        self.entries.retain(|k, _| existing_keys.contains(k));
        removed
    }
}

fn file_mtime_secs(entry: &walkdir::DirEntry) -> u64 {
    entry
        .metadata()
        .ok()
        .and_then(|m| m.modified().ok())
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Aggregate a module-level ABI hash from per-file fingerprint entries.
/// Reuses already-computed per-file ABI hashes, avoiding re-reading .class files.
fn aggregate_abi_from_fingerprints(fingerprints: &Fingerprints) -> String {
    let mut entries: Vec<(&str, &str)> = fingerprints
        .entries
        .iter()
        .filter_map(|(k, e)| e.abi_hash.as_deref().map(|h| (k.as_str(), h)))
        .collect();
    entries.sort_by(|a, b| a.0.cmp(&b.0));
    let mut hasher = Sha256::new();
    for (key, abi) in &entries {
        hasher.update(key.as_bytes());
        hasher.update(abi.as_bytes());
    }
    format!("{:x}", hasher.finalize())
}

fn cache_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// Walk source directories and collect all .java files with their normalized key and mtime.
fn walk_java_files(source_dirs: &[PathBuf]) -> Result<Vec<(PathBuf, String, u64)>> {
    let mut files = Vec::new();
    for src_dir in source_dirs {
        if !src_dir.exists() {
            continue;
        }
        for entry in walkdir::WalkDir::new(src_dir) {
            let entry = entry?;
            if entry.path().extension().and_then(|e| e.to_str()) != Some("java") {
                continue;
            }
            let path = entry.path().to_path_buf();
            let rel_key = crate::normalize_cache_path(&path);
            let mtime = file_mtime_secs(&entry);
            files.push((path, rel_key, mtime));
        }
    }
    Ok(files)
}

/// Compute SHA-256 hash of file content.
pub fn hash_file(path: &Path) -> Result<String> {
    let content = std::fs::read(path)?;
    Ok(hash_bytes(&content))
}

pub fn hash_bytes(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    format!("{:x}", hasher.finalize())
}

/// Compute an ABI hash from a .class file.
/// Parses the Java class file format and hashes everything except:
/// - Code attributes (method bodies)
/// - Private fields and methods
///
/// This means method body changes don't trigger dependent recompilation,
/// only signature/API changes do.
pub fn compute_class_abi_hash(class_file: &Path) -> Result<String> {
    let data = std::fs::read(class_file)?;
    match extract_abi_bytes(&data) {
        Some(abi) => Ok(hash_bytes(&abi)),
        None => Ok(hash_bytes(&data)), // fallback: hash entire file
    }
}

/// Parse a Java class file and extract ABI-relevant bytes (everything except
/// Code attributes and private members).
///
/// Java class file format (simplified):
///   magic(4) version(4) constant_pool fields methods attributes
fn extract_abi_bytes(data: &[u8]) -> Option<Vec<u8>> {
    let len = data.len();

    if len < 10 {
        return None;
    }

    // Magic number: 0xCAFEBABE
    if data[0..4] != [0xCA, 0xFE, 0xBA, 0xBE] {
        return None;
    }

    let mut abi = Vec::with_capacity(len);

    // Include magic + version (8 bytes)
    abi.extend_from_slice(&data[0..8]);
    let mut pos = 8;

    // Parse constant pool count (u16)
    let cp_count = read_u16(data, pos)? as usize;
    abi.extend_from_slice(&data[pos..pos + 2]);
    pos += 2;

    // Skip through constant pool entries (we include them all in ABI hash
    // since they contain type names, method signatures, etc.)
    let cp_start = pos;
    let mut i = 1; // constant pool is 1-indexed
    while i < cp_count {
        if pos >= len {
            return None;
        }
        let tag = data[pos];
        match tag {
            1 => {
                // CONSTANT_Utf8: u16 length + bytes
                if pos + 3 > len {
                    return None;
                }
                let str_len = read_u16(data, pos + 1)? as usize;
                pos += 3 + str_len;
            }
            3 | 4 => pos += 5,    // Integer, Float
            5 | 6 => {
                pos += 9; // Long, Double (takes 2 entries)
                i += 1;
            }
            7 | 8 | 16 | 19 | 20 => pos += 3, // Class, String, MethodType, Module, Package
            9 | 10 | 11 | 12 | 17 | 18 => pos += 5, // Fieldref, Methodref, InterfaceMethodref, NameAndType, Dynamic, InvokeDynamic
            15 => pos += 4, // MethodHandle
            _ => return None, // Unknown tag, bail out
        }
        i += 1;
    }
    // Include entire constant pool
    abi.extend_from_slice(&data[cp_start..pos]);

    // access_flags(2) + this_class(2) + super_class(2)
    if pos + 6 > len {
        return None;
    }
    abi.extend_from_slice(&data[pos..pos + 6]);
    pos += 6;

    // Interfaces count + interface indices
    if pos + 2 > len {
        return None;
    }
    let iface_count = read_u16(data, pos)? as usize;
    let iface_bytes = 2 + iface_count * 2;
    if pos + iface_bytes > len {
        return None;
    }
    abi.extend_from_slice(&data[pos..pos + iface_bytes]);
    pos += iface_bytes;

    // Fields
    pos = extract_members_abi(data, pos, &mut abi, false)?;

    // Methods — skip Code attributes
    pos = extract_members_abi(data, pos, &mut abi, true)?;

    // Class attributes (include all — SourceFile, InnerClasses, etc.)
    if pos + 2 <= len {
        abi.extend_from_slice(&data[pos..len.min(pos + (len - pos))]);
    }

    Some(abi)
}

const ACC_PRIVATE: u16 = 0x0002;

/// Parse fields or methods and add ABI-relevant bytes.
/// For methods with `skip_code=true`, Code attributes are excluded from the hash.
/// Private members are excluded entirely.
fn extract_members_abi(data: &[u8], mut pos: usize, abi: &mut Vec<u8>, skip_code: bool) -> Option<usize> {
    let len = data.len();
    if pos + 2 > len {
        return None;
    }
    let count = read_u16(data, pos)? as usize;
    // We'll write the actual count of non-private members later
    let count_pos = abi.len();
    abi.extend_from_slice(&[0, 0]); // placeholder
    pos += 2;

    let mut included_count: u16 = 0;

    for _ in 0..count {
        if pos + 8 > len {
            return None;
        }
        let access_flags = read_u16(data, pos)?;
        let _name_idx = read_u16(data, pos + 2)?;
        let _desc_idx = read_u16(data, pos + 4)?;
        let attr_count = read_u16(data, pos + 6)? as usize;

        let is_private = (access_flags & ACC_PRIVATE) != 0;

        if !is_private {
            // Include: access_flags + name_index + descriptor_index
            abi.extend_from_slice(&data[pos..pos + 6]);
            included_count += 1;
        }
        pos += 8;

        // We need to write attribute count for included members
        let attr_count_pos = abi.len();
        if !is_private {
            abi.extend_from_slice(&[0, 0]); // placeholder for attr count
        }
        let mut included_attrs: u16 = 0;

        // Parse attributes
        for _ in 0..attr_count {
            if pos + 6 > len {
                return None;
            }
            let attr_name_idx = read_u16(data, pos)?;
            let attr_len = read_u32(data, pos + 2)? as usize;
            let attr_end = pos + 6 + attr_len;
            if attr_end > len {
                return None;
            }

            if !is_private {
                // For methods, check if this is a Code attribute.
                // Code attribute has name_index pointing to "Code" in constant pool.
                // We can't easily resolve the name here without re-parsing the constant pool,
                // so we use a heuristic: we check if the attribute is a Code attribute
                // by looking up the constant pool entry.
                //
                // Actually, let's just check if skip_code is true and this is likely Code.
                // Code attributes are typically the largest method attributes.
                // But a reliable approach: we already parsed the constant pool,
                // so let's resolve the name index.
                //
                // For simplicity and reliability, we include the attribute name index
                // in the ABI. If skip_code, we check the name_idx against known Code positions.
                // Since we can't easily look up the constant pool here, we take a different approach:
                // we scan the constant pool for "Code" utf8 entry during parsing.
                //
                // Simpler approach: just skip large method attributes (Code is always the largest).
                // But that's not reliable.
                //
                // Best approach: we always include all attributes except Code for methods.
                // We detect Code by checking the constant pool string.
                // Since we already have the full data, let's resolve it.
                let is_code_attr = skip_code && is_utf8_constant(data, attr_name_idx, b"Code");

                if !is_code_attr {
                    abi.extend_from_slice(&data[pos..attr_end]);
                    included_attrs += 1;
                }
            }

            pos = attr_end;
        }

        // Patch attribute count
        if !is_private {
            abi[attr_count_pos] = (included_attrs >> 8) as u8;
            abi[attr_count_pos + 1] = (included_attrs & 0xFF) as u8;
        }
    }

    // Patch member count
    abi[count_pos] = (included_count >> 8) as u8;
    abi[count_pos + 1] = (included_count & 0xFF) as u8;

    Some(pos)
}

/// Check if a constant pool entry at the given index is a UTF-8 constant with the given value.
fn is_utf8_constant(data: &[u8], target_idx: u16, expected: &[u8]) -> bool {
    if data.len() < 10 {
        return false;
    }
    let cp_count = match read_u16(data, 8) {
        Some(c) => c as usize,
        None => return false,
    };
    let mut pos = 10;
    let mut idx: u16 = 1;
    while (idx as usize) < cp_count && pos < data.len() {
        let tag = data[pos];
        if idx == target_idx {
            if tag == 1 {
                // CONSTANT_Utf8
                if let Some(str_len) = read_u16(data, pos + 1) {
                    let str_start = pos + 3;
                    let str_end = str_start + str_len as usize;
                    if str_end <= data.len() {
                        return &data[str_start..str_end] == expected;
                    }
                }
            }
            return false;
        }
        match tag {
            1 => {
                let str_len = read_u16(data, pos + 1).unwrap_or(0) as usize;
                pos += 3 + str_len;
            }
            3 | 4 => pos += 5,
            5 | 6 => {
                pos += 9;
                idx += 1;
            }
            7 | 8 | 16 | 19 | 20 => pos += 3,
            9 | 10 | 11 | 12 | 17 | 18 => pos += 5,
            15 => pos += 4,
            _ => return false,
        }
        idx += 1;
    }
    false
}

fn read_u16(data: &[u8], pos: usize) -> Option<u16> {
    if pos + 2 > data.len() {
        return None;
    }
    Some(((data[pos] as u16) << 8) | data[pos + 1] as u16)
}

fn read_u32(data: &[u8], pos: usize) -> Option<u32> {
    if pos + 4 > data.len() {
        return None;
    }
    Some(
        ((data[pos] as u32) << 24)
            | ((data[pos + 1] as u32) << 16)
            | ((data[pos + 2] as u32) << 8)
            | data[pos + 3] as u32,
    )
}

/// Incremental compile: only compile changed files.
/// Falls back to full compilation if output dir is empty.
/// Supports build cache sharing: on full recompilation, checks
/// ~/.ym/cache/build-cache/{input_hash}/ for cached .class files.
pub fn incremental_compile(
    config: &super::CompileConfig,
    cache_dir: &Path,
    pool: Option<&super::worker::CompilerPool>,
) -> Result<super::CompileResult> {
    // Use a per-output-dir fingerprint file so workspace modules don't conflict
    let fp_dir = fingerprint_dir_for(cache_dir, &config.output_dir);
    let mut fingerprints = Fingerprints::load(&fp_dir);
    let (changed, all_files) = fingerprints.get_changed_files(&config.source_dirs)?;

    // ADR-014: manifest fast-path. If the previous build wrote a completion
    // manifest AND every recorded class file still exists AND the source set
    // hasn't changed AND no source content changed, we KNOW the prior compile
    // is still valid — skip everything else, return UpToDate immediately.
    //
    // This is the single source of truth for "have we compiled before"; it
    // can't be fooled by resource files in output_dir, fingerprint residue
    // after `rm -rf out`, or any other shared-state pollution that the
    // ADR-013 has_classes heuristic still requires careful guarding against.
    if !all_files.is_empty() && changed.is_empty() {
        if let Some(manifest) = BuildManifest::load(&fp_dir) {
            if manifest.is_consistent_with(&all_files, &config.output_dir) {
                return Ok(super::CompileResult {
                    success: true,
                    outcome: super::CompileOutcome::UpToDate,
                    errors: String::new(),
                    module_abi_hash: Some(aggregate_abi_from_fingerprints(&fingerprints)),
                });
            }
        }
    }

    // ADR-013: detect "have we compiled before" by looking for .class files
    // specifically, NOT by `dir is non-empty`. The build pipeline copies
    // resources (graphqls, properties, ...) into output_dir BEFORE invoking
    // incremental_compile, so a freshly-cleaned out/classes/ becomes non-empty
    // (resource files only, zero .class) by the time we get here.
    //
    // Old logic `dir.next().is_some()`:
    //   1. resources copied → out/classes/graphql/X.graphqls exists
    //   2. has_classes = true (dir non-empty, treated as "already compiled")
    //   3. fall through to else branch → fingerprint check from prior build
    //   4. all sources unchanged + cache fingerprints intact → "missing" check
    //   5. no .class for src + has fingerprint entry → "no-output module" path
    //   6. UpToDate returned, javac never invoked
    //   7. packaging produces a 0-class jar (see 2026-05-03 standard-task-core
    //      750B incident) which then gets published to the maven registry
    //
    // Correct check: "have we ACTUALLY compiled" = "is there at least one
    // .class file under output_dir?" Resource files do not count.
    let has_classes = config.output_dir.exists()
        && walkdir::WalkDir::new(&config.output_dir)
            .into_iter()
            .filter_map(|e| e.ok())
            .any(|e| e.path().extension().and_then(|s| s.to_str()) == Some("class"));

    let files_to_compile = if !has_classes {
        // Output directory missing or empty — clear stale fingerprints and force full compile.
        // Previous logic skipped recompile when all files had fingerprints (assuming "no-output
        // module"), but this also triggered when output was deleted (e.g. ym clean).
        if !fingerprints.entries.is_empty() {
            fingerprints.entries.clear();
            fingerprints.save(&fp_dir);
        }
        // Full compile needed — try build cache first
        if !all_files.is_empty() {
            if let Some(result) = try_restore_build_cache(config, &all_files, &mut fingerprints, &fp_dir)? {
                // ADR-014: cache restore succeeded — record the resulting state as a
                // valid completed build so the next call hits the manifest fast-path.
                if let Err(e) = BuildManifest::write(&fp_dir, &config.output_dir, &all_files) {
                    eprintln!("  Warning: failed to write build manifest after cache restore: {}", e);
                }
                return Ok(result);
            }
        }
        all_files.clone()
    } else if changed.is_empty() {
        // Check for missing .class files (e.g. user deleted out/classes/ contents)
        // But skip source files that were previously compiled successfully with no output
        // (e.g. entirely commented-out .java files that produce no .class)
        let missing: Vec<PathBuf> = all_files
            .iter()
            .filter(|src| {
                if find_class_for_source(src, &config.source_dirs, &config.output_dir).is_some() {
                    return false; // .class exists, not missing
                }
                // No .class file — check if this source was previously compiled successfully
                // (has a fingerprint entry). If so, it's a no-output file, skip it.
                let key = crate::normalize_cache_path(src);
                !fingerprints.entries.contains_key(&key)
            })
            .cloned()
            .collect();
        if missing.is_empty() {
            // ADR-014: write/refresh manifest so the next invocation can take
            // the manifest fast-path instead of recomputing this fingerprint
            // walk + missing check (and so a future caller that ONLY trusts
            // the manifest sees the truthful state).
            if let Err(e) = BuildManifest::write(&fp_dir, &config.output_dir, &all_files) {
                eprintln!("  Warning: failed to write build manifest on up-to-date path: {}", e);
            }
            return Ok(super::CompileResult {
                success: true,
                outcome: super::CompileOutcome::UpToDate,
                errors: String::new(),
                module_abi_hash: Some(aggregate_abi_from_fingerprints(&fingerprints)),
            });
        }
        missing
    } else {
        changed.clone()
    };

    // Include output dir in classpath for incremental compilation
    // so javac can resolve types from previously compiled classes
    let mut classpath = config.classpath.clone();
    if has_classes && !classpath.contains(&config.output_dir) {
        classpath.push(config.output_dir.clone());
    }

    let incremental_config = super::CompileConfig {
        source_dirs: Vec::new(), // We'll pass files directly
        output_dir: config.output_dir.clone(),
        classpath,
        java_version: config.java_version.clone(),
        encoding: config.encoding.clone(),
        annotation_processors: config.annotation_processors.clone(),
        lint: config.lint.clone(),
        extra_args: config.extra_args.clone(),
    };

    let result = compile_files(&incremental_config, &files_to_compile, pool)?;

    let is_full_compile = files_to_compile.len() == all_files.len();

    if result.success {
        // Update fingerprints for compiled files
        for file in &files_to_compile {
            let hash = hash_file(file).unwrap_or_default();
            let mtime = std::fs::metadata(file)
                .ok()
                .and_then(|m| m.modified().ok())
                .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|d| d.as_secs())
                .unwrap_or(0);
            fingerprints.update_source(file, &hash, mtime);

            // Compute ABI hash from corresponding .class file
            // Source: src/main/java/com/Foo.java → Class: output_dir/com/Foo.class
            if let Some(class_file) = find_class_for_source(file, &config.source_dirs, &config.output_dir) {
                if let Ok(abi_hash) = compute_class_abi_hash(&class_file) {
                    fingerprints.update_abi(file, &abi_hash);
                }
            }
        }
        let removed = fingerprints.prune(&all_files);
        // Delete orphan .class files for deleted sources
        for removed_src in &removed {
            let src_path = Path::new(removed_src);
            if let Some(class_file) = find_class_for_source(src_path, &config.source_dirs, &config.output_dir) {
                let _ = std::fs::remove_file(&class_file);
            }
        }
        fingerprints.save(&fp_dir)?;

        // Save to build cache after successful full compilation
        if is_full_compile && !files_to_compile.is_empty() {
            if let Err(e) = save_build_cache(config, &all_files) {
                eprintln!("  Warning: failed to save build cache: {}", e);
            }
        }

        // ADR-014: at this point fingerprints, .class files, and build cache
        // are all coherent — record the completed build state as the LAST
        // step. Next invocation can short-circuit on this manifest without
        // walking output_dir or guessing from fingerprint residue.
        if let Err(e) = BuildManifest::write(&fp_dir, &config.output_dir, &all_files) {
            eprintln!("  Warning: failed to write build manifest: {}", e);
        }
    }

    let abi = if result.success {
        Some(aggregate_abi_from_fingerprints(&fingerprints))
    } else {
        None
    };

    Ok(super::CompileResult {
        success: result.success,
        outcome: if files_to_compile.is_empty() {
            super::CompileOutcome::UpToDate
        } else {
            super::CompileOutcome::Compiled(files_to_compile.len())
        },
        errors: result.errors,
        module_abi_hash: abi,
    })
}

/// Map a source .java file to its corresponding .class file in the output directory.
/// E.g. src/main/java/com/example/Foo.java → output_dir/com/example/Foo.class
///
/// ADR-010 Defense ③: a class file is only considered "present" if its content is valid
/// (size >= 8 bytes + 0xCAFEBABE magic header). 0-byte / truncated files left by an
/// interrupted javac would otherwise be treated as "already compiled" and the source
/// would be skipped on the next incremental build, propagating the corruption.
fn find_class_for_source(source: &Path, source_dirs: &[PathBuf], output_dir: &Path) -> Option<PathBuf> {
    for src_dir in source_dirs {
        if let Ok(rel) = source.strip_prefix(src_dir) {
            let class_rel = rel.with_extension("class");
            let class_file = output_dir.join(class_rel);
            if is_valid_class_file(&class_file) {
                return Some(class_file);
            }
        }
    }
    None
}

/// Validate a .class file by checking size + 0xCAFEBABE magic header.
/// Returns false if the file does not exist, is too small, or has an invalid magic.
/// This catches 0-byte / truncated files left by interrupted javac runs (see ADR-010).
fn is_valid_class_file(path: &Path) -> bool {
    let Ok(metadata) = std::fs::metadata(path) else { return false };
    // Minimum class file = magic(4) + minor_version(2) + major_version(2) = 8 bytes
    if metadata.len() < 8 { return false; }
    let Ok(mut f) = std::fs::File::open(path) else { return false };
    let mut magic = [0u8; 4];
    use std::io::Read;
    if f.read_exact(&mut magic).is_err() { return false; }
    magic == [0xCA, 0xFE, 0xBA, 0xBE]
}

/// ADR-011: verify every .class file under `dir` (recursively) is valid before
/// trusting the cached output. Cache hits previously short-circuited on
/// `dir.exists()` alone, which let corrupt content (0-byte / truncated .class
/// from earlier interrupted builds) propagate into output_dir on every restore
/// — packaging then produced incomplete jars (see 2026-05-01 standard-task-core
/// incident: 18-entry jar with entity/repository class missing).
///
/// Empty dirs and dirs with only non-.class files (resources, graphqls) are
/// considered valid — placeholder modules legitimately have no .class.
fn is_cache_dir_valid(dir: &Path) -> bool {
    walkdir::WalkDir::new(dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("class"))
        .all(|e| is_valid_class_file(e.path()))
}

/// Derive a per-module fingerprint directory from the output dir path.
/// This ensures workspace modules have independent fingerprint files.
fn fingerprint_dir_for(cache_dir: &Path, output_dir: &Path) -> PathBuf {
    let hash = hash_bytes(crate::normalize_cache_path(output_dir).as_bytes());
    cache_dir.join("fingerprints").join(&hash[..16])
}

/// ADR-014: per-output-dir compilation completion record.
///
/// Single source of truth for "has this module's javac been fully run AND
/// produced these specific .class files?". Replaces fragile heuristics like
/// "is output_dir non-empty" (ADR-013) and "does fingerprint have an entry"
/// that get fooled by partial state (resources copied before javac, output
/// rm'd after fingerprint write, etc).
///
/// Lifecycle:
/// - **Write**: only at the very end of a successful full or incremental
///   compile. Atomic (sibling tmp + rename).
/// - **Read**: every incremental_compile entry, before any other staleness
///   check. If a valid manifest exists and is consistent with current sources
///   + on-disk class files, return UpToDate immediately — fastest path.
/// - **Invalidation**: any of (a) sources added/removed/renamed, (b) declared
///   class file missing from disk, (c) ym version changed → manifest no
///   longer trusted, fall through to fingerprint / cache restore / javac.
///
/// Stored at the same fingerprint directory as `fingerprints.json` (keyed by
/// output_dir hash), kept OUT of `output_dir` itself so that packaging walks
/// don't have to special-case it and `ym clean`-ing `out/` doesn't accidentally
/// orphan the manifest.
#[derive(Debug, Serialize, Deserialize)]
pub struct BuildManifest {
    pub ym_version: String,
    pub completed_at: u64,
    /// Source files compiled, normalized (matches `normalize_cache_path`).
    pub source_paths: Vec<String>,
    /// Class files produced, paths relative to `output_dir`.
    pub class_paths: Vec<String>,
}

impl BuildManifest {
    fn manifest_path(fp_dir: &Path) -> PathBuf {
        fp_dir.join(BUILD_MANIFEST_FILE)
    }

    pub fn load(fp_dir: &Path) -> Option<Self> {
        let path = Self::manifest_path(fp_dir);
        let content = std::fs::read_to_string(&path).ok()?;
        serde_json::from_str(&content).ok()
    }

    /// Atomically write the manifest, populated from current source list +
    /// whatever .class files are currently under `output_dir`. Caller must
    /// only invoke this AFTER a successful compile (full or incremental) so
    /// the on-disk state truly matches the recorded state.
    pub fn write(fp_dir: &Path, output_dir: &Path, source_files: &[PathBuf]) -> Result<()> {
        std::fs::create_dir_all(fp_dir)?;

        let source_paths: Vec<String> = {
            let mut v: Vec<String> = source_files.iter()
                .map(|p| crate::normalize_cache_path(p))
                .collect();
            v.sort();
            v
        };

        let class_paths: Vec<String> = {
            let mut v: Vec<String> = walkdir::WalkDir::new(output_dir)
                .into_iter()
                .filter_map(|e| e.ok())
                .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("class"))
                .filter_map(|e| {
                    e.path().strip_prefix(output_dir).ok()
                        .map(|p| p.to_string_lossy().replace('\\', "/"))
                })
                .collect();
            v.sort();
            v
        };

        let manifest = BuildManifest {
            ym_version: env!("CARGO_PKG_VERSION").to_string(),
            completed_at: cache_timestamp(),
            source_paths,
            class_paths,
        };

        let final_path = Self::manifest_path(fp_dir);
        let tmp_path = fp_dir.join(format!("{}.tmp", BUILD_MANIFEST_FILE));
        let _ = std::fs::remove_file(&tmp_path);
        let content = serde_json::to_string(&manifest)?;
        std::fs::write(&tmp_path, content)?;
        std::fs::rename(&tmp_path, &final_path)?;
        Ok(())
    }

    /// True if every recorded class file still exists on disk under
    /// `output_dir` AND the recorded source list matches `current_sources`
    /// (set equality after normalization). Either condition failing means
    /// the prior build's record no longer reflects reality — invalidate.
    ///
    /// Note: we do NOT validate .class CAFEBABE / size here — that's
    /// ADR-011's responsibility on the cache restore path. The manifest's
    /// invariant is only "the build I recorded is reproducible from disk
    /// state I can see". If a recorded .class got truncated externally
    /// after manifest write, ADR-011's is_valid_class_file (called from
    /// find_class_for_source) will catch it on the per-source verification.
    pub fn is_consistent_with(&self, current_sources: &[PathBuf], output_dir: &Path) -> bool {
        let curr: std::collections::HashSet<String> = current_sources.iter()
            .map(|p| crate::normalize_cache_path(p))
            .collect();
        let prior: std::collections::HashSet<&String> = self.source_paths.iter().collect();
        if curr.len() != prior.len() {
            return false;
        }
        for p in &curr {
            if !prior.contains(p) {
                return false;
            }
        }

        for class_path in &self.class_paths {
            let full = output_dir.join(class_path);
            if !full.exists() {
                return false;
            }
        }

        true
    }
}

/// Feed compiler configuration fields into a hasher (shared by both cache key functions).
fn feed_compiler_config(hasher: &mut Sha256, config: &super::CompileConfig) {
    if let Some(ref v) = config.java_version {
        hasher.update(tag::VER);
        hasher.update(v.as_bytes());
    }
    if let Some(ref e) = config.encoding {
        hasher.update(tag::ENC);
        hasher.update(e.as_bytes());
    }
    for l in &config.lint {
        hasher.update(tag::LINT);
        hasher.update(l.as_bytes());
    }
    for arg in &config.extra_args {
        hasher.update(tag::ARG);
        hasher.update(arg.as_bytes());
    }
}

/// Compute a content-addressable key from all compilation inputs.
/// Used internally by incremental_compile for single-module cache.
fn compute_build_cache_key(config: &super::CompileConfig, source_files: &[PathBuf]) -> Result<String> {
    let mut hasher = Sha256::new();

    // Source content hashes (sorted for determinism)
    let mut source_hashes: Vec<(String, String)> = Vec::new();
    for f in source_files {
        let h = hash_file(f)?;
        let rel = crate::normalize_cache_path(f);
        source_hashes.push((rel, h));
    }
    source_hashes.sort_by(|a, b| a.0.cmp(&b.0));
    for (path, hash) in &source_hashes {
        hasher.update(path.as_bytes());
        hasher.update(hash.as_bytes());
    }

    // Classpath (sorted paths)
    let mut cp: Vec<String> = config.classpath.iter()
        .map(|p| crate::normalize_cache_path(p))
        .collect();
    cp.sort();
    for p in &cp {
        hasher.update(tag::CP);
        hasher.update(p.as_bytes());
    }

    feed_compiler_config(&mut hasher, config);
    for ap in &config.annotation_processors {
        hasher.update(tag::AP);
        hasher.update(crate::normalize_cache_path(ap).as_bytes());
    }

    Ok(format!("{:x}", hasher.finalize()))
}

/// Build cache directory: ~/.ym/build-cache/{key}/
fn build_cache_dir(key: &str) -> PathBuf {
    crate::home_dir()
        .join(crate::config::CACHE_DIR)
        .join(crate::config::BUILD_CACHE_DIR)
        .join(key)
}

/// Try to restore compiled classes from the build cache.
/// Returns Some(CompileResult) on cache hit, None on miss.
fn try_restore_build_cache(
    config: &super::CompileConfig,
    source_files: &[PathBuf],
    fingerprints: &mut Fingerprints,
    fp_dir: &Path,
) -> Result<Option<super::CompileResult>> {
    let key = compute_build_cache_key(config, source_files)?;
    let cache_dir = build_cache_dir(&key);

    if !cache_dir.exists() {
        return Ok(None);
    }

    // ADR-011: invalidate corrupt cache rather than restoring 0-byte / truncated
    // .class into output_dir. Without this, a single bad cache entry propagates
    // forever — every restore copies the corrupt content, packaging produces
    // incomplete jars, and the only escape is manually deleting ~/.ym/build-cache.
    if !is_cache_dir_valid(&cache_dir) {
        eprintln!(
            "  Warning: invalidating corrupt build cache at {} (contains 0-byte / non-CAFEBABE .class)",
            cache_dir.display()
        );
        let _ = std::fs::remove_dir_all(&cache_dir);
        return Ok(None);
    }

    // Cache hit — restore .class files
    std::fs::create_dir_all(&config.output_dir)?;
    copy_dir_recursive(&cache_dir, &config.output_dir)?;

    // Rebuild fingerprints from restored files
    for file in source_files {
        let hash = hash_file(file).unwrap_or_default();
        let mtime = std::fs::metadata(file)
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);
        fingerprints.update_source(file, &hash, mtime);

        if let Some(class_file) = find_class_for_source(file, &config.source_dirs, &config.output_dir) {
            if let Ok(abi_hash) = compute_class_abi_hash(&class_file) {
                fingerprints.update_abi(file, &abi_hash);
            }
        }
    }
    fingerprints.save(fp_dir)?;

    Ok(Some(super::CompileResult {
        success: true,
        outcome: super::CompileOutcome::Cached,
        errors: String::new(),
        module_abi_hash: Some(aggregate_abi_from_fingerprints(&fingerprints)),
    }))
}

/// Save compiled output to the build cache.
///
/// ADR-010 Defense ④: writes are atomic — copy into a sibling `.tmp` directory first,
/// then rename to the final cache_dir. Without this, an interrupt mid-copy would leave
/// `cache_dir` partially populated, and the next call's `cache_dir.exists()` check would
/// short-circuit with "already cached", causing future cache hits to restore corrupt
/// (or 0-byte) class files.
fn save_build_cache(config: &super::CompileConfig, source_files: &[PathBuf]) -> Result<()> {
    let key = compute_build_cache_key(config, source_files)?;
    let cache_dir = build_cache_dir(&key);

    if cache_dir.exists() {
        return Ok(()); // Already cached
    }

    // Sibling tmp dir under the same parent — keeps `rename` on the same filesystem
    // (POSIX guarantees rename within a filesystem is atomic).
    let parent = cache_dir.parent()
        .ok_or_else(|| anyhow::anyhow!("build cache dir has no parent: {}", cache_dir.display()))?;
    std::fs::create_dir_all(parent)?;

    let tmp_dir = parent.join(format!("{}.tmp",
        cache_dir.file_name().and_then(|s| s.to_str()).unwrap_or("cache")
    ));
    // Clean up any stale tmp from a previous interrupted run.
    if tmp_dir.exists() {
        std::fs::remove_dir_all(&tmp_dir)?;
    }
    std::fs::create_dir_all(&tmp_dir)?;
    copy_dir_recursive(&config.output_dir, &tmp_dir)?;

    // Atomic publish. If another process raced us and already created cache_dir,
    // discard our tmp and accept their version.
    match std::fs::rename(&tmp_dir, &cache_dir) {
        Ok(()) => Ok(()),
        Err(_) if cache_dir.exists() => {
            let _ = std::fs::remove_dir_all(&tmp_dir);
            Ok(())
        }
        Err(e) => Err(e.into()),
    }
}

/// Recursively hardlink directory contents, falling back to copy on cross-filesystem.
/// Hardlink files when possible (same filesystem), fall back to copy.
/// Detects cross-filesystem (EXDEV) on first failure and switches to copy-only.
fn hardlink_or_copy_dir(src: &Path, dst: &Path) -> Result<()> {
    let mut use_hardlink = true;
    for entry in walkdir::WalkDir::new(src) {
        let entry = entry?;
        let rel = entry.path().strip_prefix(src)?;
        let dest = dst.join(rel);
        if entry.file_type().is_dir() {
            std::fs::create_dir_all(&dest)?;
        } else {
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent)?;
            }
            if use_hardlink {
                match std::fs::hard_link(entry.path(), &dest) {
                    Ok(()) => continue,
                    Err(_) => {
                        use_hardlink = false;
                        std::fs::copy(entry.path(), &dest)?;
                    }
                }
            } else {
                std::fs::copy(entry.path(), &dest)?;
            }
        }
    }
    Ok(())
}

/// Recursively copy directory contents.
pub fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    for entry in walkdir::WalkDir::new(src) {
        let entry = entry?;
        let rel = entry.path().strip_prefix(src)?;
        let dest = dst.join(rel);
        if entry.file_type().is_dir() {
            std::fs::create_dir_all(&dest)?;
        } else {
            if let Some(parent) = dest.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::copy(entry.path(), &dest)?;
        }
    }
    Ok(())
}

/// Compile specific files using javac (or worker pool if available).
fn compile_files(
    config: &super::CompileConfig,
    files: &[PathBuf],
    pool: Option<&super::worker::CompilerPool>,
) -> Result<super::CompileResult> {
    if files.is_empty() {
        return Ok(super::CompileResult {
            success: true,
            outcome: super::CompileOutcome::UpToDate,
            errors: String::new(),
            module_abi_hash: None,
        });
    }

    std::fs::create_dir_all(&config.output_dir)?;

    if let Some(pool) = pool {
        pool.compile(config, files)
    } else {
        compile_with_javac(config, files)
    }
}

/// Direct javac compilation (public for worker fallback).
pub fn compile_files_direct(
    config: &super::CompileConfig,
    files: &[PathBuf],
) -> Result<super::CompileResult> {
    if files.is_empty() {
        return Ok(super::CompileResult {
            success: true,
            outcome: super::CompileOutcome::UpToDate,
            errors: String::new(),
            module_abi_hash: None,
        });
    }
    std::fs::create_dir_all(&config.output_dir)?;
    compile_with_javac(config, files)
}

fn compile_with_javac(
    config: &super::CompileConfig,
    files: &[PathBuf],
) -> Result<super::CompileResult> {
    let mut cmd = std::process::Command::new("javac");
    cmd.arg("-d").arg(&config.output_dir);

    if let Some(ref ver) = config.java_version {
        cmd.arg("--release").arg(ver);
    }

    if let Some(ref enc) = config.encoding {
        cmd.arg("-encoding").arg(enc);
    }

    let _cp_argfile_guard;
    if !config.classpath.is_empty() {
        let sep = if cfg!(windows) { ";" } else { ":" };
        let cp = config
            .classpath
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect::<Vec<_>>()
            .join(sep);
        // Use @argfile for very long classpaths (OS command line limits)
        if cp.len() > 8000 {
            let cp_file = config.output_dir.join(".ym-classpath.txt");
            std::fs::write(&cp_file, format!("-cp\n{}", cp))?;
            cmd.arg(format!("@{}", cp_file.display()));
            _cp_argfile_guard = Some(ArgfileCleanup(cp_file));
        } else {
            _cp_argfile_guard = None;
            cmd.arg("-cp").arg(&cp);
        }
    } else {
        _cp_argfile_guard = None;
    }

    // Annotation processor path
    if !config.annotation_processors.is_empty() {
        let sep = if cfg!(windows) { ";" } else { ":" };
        let ap = config
            .annotation_processors
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect::<Vec<_>>()
            .join(sep);
        cmd.arg("-processorpath").arg(&ap);
    } else {
        cmd.arg("-proc:none");
    }

    // Lint options (-Xlint)
    for lint_opt in &config.lint {
        cmd.arg(format!("-Xlint:{}", lint_opt));
    }

    // Extra compiler arguments
    for arg in &config.extra_args {
        cmd.arg(arg);
    }

    // Use @argfile when file list is large (avoids OS command line length limits)
    let _argfile_guard;
    if files.len() > 50 {
        let argfile = config.output_dir.join(".ym-sources.txt");
        let content = files
            .iter()
            .map(|f| f.to_string_lossy().to_string())
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(&argfile, &content)?;
        cmd.arg(format!("@{}", argfile.display()));
        _argfile_guard = Some(ArgfileCleanup(argfile));
    } else {
        _argfile_guard = None;
        for f in files {
            cmd.arg(f);
        }
    }

    let output = cmd.output()?;
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    Ok(super::CompileResult {
        success: output.status.success(),
        outcome: super::CompileOutcome::Compiled(files.len()),
        errors: stderr,
        module_abi_hash: None,
    })
}

/// RAII guard to clean up argfile after compilation
pub(crate) struct ArgfileCleanup(pub(crate) PathBuf);
impl Drop for ArgfileCleanup {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Content-addressed build cache: public API for workspace wave scheduling
// ═══════════════════════════════════════════════════════════════════════

/// Compute content hashes for all source files in the given directories,
/// using mtime fast path to avoid rehashing unchanged files.
///
/// Returns sorted Vec<(relative_path, content_sha256)>.
pub fn compute_source_content_hashes(
    source_dirs: &[PathBuf],
    cache_dir: &Path,
    output_dir: &Path,
) -> Result<Vec<(String, String)>> {
    let fp_dir = fingerprint_dir_for(cache_dir, output_dir);
    let fingerprints = Fingerprints::load(&fp_dir);

    let mut hashes: Vec<(String, String)> = Vec::new();
    for (path, rel_key, mtime) in walk_java_files(source_dirs)? {
        let content_hash = match fingerprints.entries.get(&rel_key) {
            Some(e) if e.mtime_secs == mtime => e.source_hash.clone(),
            _ => hash_file(&path)?,
        };
        hashes.push((rel_key, content_hash));
    }
    hashes.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(hashes)
}

/// Compute a module-level ABI hash by aggregating ABI hashes of all .class files
/// in the output directory.
///
/// Module ABI hash = SHA-256(sorted(class_file_path + abi_hash))
pub fn compute_module_abi_hash(output_dir: &Path) -> Result<String> {
    let mut entries: Vec<(String, String)> = Vec::new();

    if !output_dir.exists() {
        return Ok(hash_bytes(b"empty"));
    }

    for entry in walkdir::WalkDir::new(output_dir) {
        let entry = entry?;
        if entry.path().extension().and_then(|e| e.to_str()) != Some("class") {
            continue;
        }
        let rel = entry
            .path()
            .strip_prefix(output_dir)
            .unwrap_or(entry.path())
            .to_string_lossy()
            .to_string();
        let abi_hash = compute_class_abi_hash(entry.path()).unwrap_or_else(|_| {
            hash_file(entry.path()).unwrap_or_else(|_| hash_bytes(b"unreadable"))
        });
        entries.push((rel, abi_hash));
    }

    entries.sort_by(|a, b| a.0.cmp(&b.0));

    let mut hasher = Sha256::new();
    for (path, hash) in &entries {
        hasher.update(path.as_bytes());
        hasher.update(hash.as_bytes());
    }
    Ok(format!("{:x}", hasher.finalize()))
}

/// Inputs for computing a content-addressed module cache key.
/// All slice fields must be sorted by first element for deterministic hashing.
pub struct ModuleCacheInput<'a> {
    pub source_hashes: &'a [(String, String)],
    pub dep_abi_hashes: &'a [(String, String)],
    pub maven_jar_sha256s: &'a [(String, String)],
    pub config: &'a super::CompileConfig,
    pub ap_jar_sha256s: &'a [(String, String)],
}

/// Compute a content-addressed module cache key for workspace wave scheduling.
pub fn compute_module_cache_key(input: &ModuleCacheInput) -> String {
    let mut hasher = Sha256::new();

    hasher.update(b"v1:");

    // All input slices are pre-sorted by caller (see ModuleCacheInput doc)
    for (path, hash) in input.source_hashes {
        hasher.update(tag::SRC);
        hasher.update(path.as_bytes());
        hasher.update(hash.as_bytes());
    }
    for (name, abi) in input.dep_abi_hashes {
        hasher.update(tag::DEP);
        hasher.update(name.as_bytes());
        hasher.update(abi.as_bytes());
    }
    for (coord, sha) in input.maven_jar_sha256s {
        hasher.update(tag::MVN);
        hasher.update(coord.as_bytes());
        hasher.update(sha.as_bytes());
    }
    feed_compiler_config(&mut hasher, input.config);
    for (path, sha) in input.ap_jar_sha256s {
        hasher.update(tag::AP);
        hasher.update(path.as_bytes());
        hasher.update(sha.as_bytes());
    }

    format!("{:x}", hasher.finalize())
}

/// Try to restore a module from the content-addressed build cache.
/// Returns Some(abi_hash) on cache hit, None on miss.
pub fn try_restore_module_cache(
    cache_key: &str,
    output_dir: &Path,
) -> Result<Option<String>> {
    let cache_dir = build_cache_dir(cache_key);
    let classes_dir = cache_dir.join("classes");

    if !classes_dir.exists() {
        return Ok(None);
    }

    // ADR-011: invalidate corrupt cache. See is_cache_dir_valid doc comment for context.
    if !is_cache_dir_valid(&classes_dir) {
        eprintln!(
            "  Warning: invalidating corrupt module cache at {} (contains 0-byte / non-CAFEBABE .class)",
            cache_dir.display()
        );
        let _ = std::fs::remove_dir_all(&cache_dir);
        return Ok(None);
    }

    // Clear stale output before restoring to avoid leftover .class files from previous builds
    if output_dir.exists() {
        let _ = std::fs::remove_dir_all(output_dir);
    }
    std::fs::create_dir_all(output_dir)?;
    copy_dir_recursive(&classes_dir, output_dir)?;

    // Read stored ABI hash
    let abi_path = cache_dir.join("abi_hash");
    let abi_hash = std::fs::read_to_string(&abi_path)
        .map(|s| s.trim().to_string())
        .unwrap_or_default();

    // Touch meta.json mtime for LRU eviction (avoids JSON parse overhead on hot path)
    let meta_path = cache_dir.join("meta.json");
    let _ = std::fs::OpenOptions::new().write(true).open(&meta_path);

    Ok(Some(abi_hash))
}

/// Save a module's compilation output to the content-addressed build cache.
pub fn save_module_cache(
    cache_key: &str,
    output_dir: &Path,
    abi_hash: &str,
    module_name: &str,
) -> Result<()> {
    let cache_dir = build_cache_dir(cache_key);
    let classes_dir = cache_dir.join("classes");

    if classes_dir.exists() {
        return Ok(()); // Already cached
    }

    std::fs::create_dir_all(&classes_dir)?;
    hardlink_or_copy_dir(output_dir, &classes_dir)?;

    // Write ABI hash
    std::fs::write(cache_dir.join("abi_hash"), abi_hash)?;

    let now = cache_timestamp();
    let meta = serde_json::json!({
        "created_at": now,
        "last_accessed": now,
        "module": module_name,
    });
    std::fs::write(cache_dir.join("meta.json"), meta.to_string())?;

    Ok(())
}

const CACHE_MAX_AGE_DAYS: u64 = 30;

/// Evict build cache entries not accessed in the last N days.
/// Runs after successful builds; errors are silently ignored to never block compilation.
pub fn evict_stale_build_cache() {
    let cache_root = crate::home_dir()
        .join(crate::config::CACHE_DIR)
        .join(crate::config::BUILD_CACHE_DIR);

    let entries = match std::fs::read_dir(&cache_root) {
        Ok(e) => e,
        Err(_) => return,
    };

    let cutoff = cache_timestamp().saturating_sub(CACHE_MAX_AGE_DAYS * 86400);

    for entry in entries.filter_map(|e| e.ok()) {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        // Use meta.json mtime as last-accessed indicator
        let meta = path.join("meta.json");
        let mtime = std::fs::metadata(&meta)
            .or_else(|_| std::fs::metadata(&path))
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);

        if mtime < cutoff {
            let _ = std::fs::remove_dir_all(&path);
        }
    }
}

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

    /// Build a minimal valid Java class file for testing.
    /// Class: public class Test { public void hello() { ... } }
    fn build_test_class(method_code: &[u8]) -> Vec<u8> {
        let mut data = Vec::new();

        // Magic
        data.extend_from_slice(&[0xCA, 0xFE, 0xBA, 0xBE]);
        // Version: Java 8 (52.0)
        data.extend_from_slice(&[0x00, 0x00, 0x00, 0x34]);

        // Constant pool - 10 entries (count = 11, 1-indexed)
        data.extend_from_slice(&[0x00, 0x0B]); // cp count = 11

        // #1 CONSTANT_Utf8 "Test"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x04]);
        data.extend_from_slice(b"Test");

        // #2 CONSTANT_Class -> #1
        data.push(7);
        data.extend_from_slice(&[0x00, 0x01]);

        // #3 CONSTANT_Utf8 "java/lang/Object"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x10]);
        data.extend_from_slice(b"java/lang/Object");

        // #4 CONSTANT_Class -> #3
        data.push(7);
        data.extend_from_slice(&[0x00, 0x03]);

        // #5 CONSTANT_Utf8 "hello"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x05]);
        data.extend_from_slice(b"hello");

        // #6 CONSTANT_Utf8 "()V"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x03]);
        data.extend_from_slice(b"()V");

        // #7 CONSTANT_Utf8 "Code"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x04]);
        data.extend_from_slice(b"Code");

        // #8 CONSTANT_Utf8 "SourceFile"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x0A]);
        data.extend_from_slice(b"SourceFile");

        // #9 CONSTANT_Utf8 "Test.java"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x09]);
        data.extend_from_slice(b"Test.java");

        // #10 CONSTANT_Utf8 "Exceptions"
        data.push(1);
        data.extend_from_slice(&[0x00, 0x0A]);
        data.extend_from_slice(b"Exceptions");

        // access_flags: ACC_PUBLIC (0x0001)
        data.extend_from_slice(&[0x00, 0x01]);
        // this_class: #2
        data.extend_from_slice(&[0x00, 0x02]);
        // super_class: #4
        data.extend_from_slice(&[0x00, 0x04]);

        // interfaces_count: 0
        data.extend_from_slice(&[0x00, 0x00]);

        // fields_count: 0
        data.extend_from_slice(&[0x00, 0x00]);

        // methods_count: 1
        data.extend_from_slice(&[0x00, 0x01]);

        // Method: public void hello()
        // access_flags: ACC_PUBLIC
        data.extend_from_slice(&[0x00, 0x01]);
        // name_index: #5 "hello"
        data.extend_from_slice(&[0x00, 0x05]);
        // descriptor_index: #6 "()V"
        data.extend_from_slice(&[0x00, 0x06]);
        // attributes_count: 1 (Code)
        data.extend_from_slice(&[0x00, 0x01]);

        // Code attribute
        // attribute_name_index: #7 "Code"
        data.extend_from_slice(&[0x00, 0x07]);
        // attribute_length
        let code_len = method_code.len() as u32 + 12; // max_stack(2)+max_locals(2)+code_length(4)+code+exception_table_length(2)+attributes_count(2)
        data.extend_from_slice(&code_len.to_be_bytes());
        // max_stack: 1
        data.extend_from_slice(&[0x00, 0x01]);
        // max_locals: 1
        data.extend_from_slice(&[0x00, 0x01]);
        // code_length
        data.extend_from_slice(&(method_code.len() as u32).to_be_bytes());
        // code bytes
        data.extend_from_slice(method_code);
        // exception_table_length: 0
        data.extend_from_slice(&[0x00, 0x00]);
        // code attributes_count: 0
        data.extend_from_slice(&[0x00, 0x00]);

        // Class attributes_count: 0
        data.extend_from_slice(&[0x00, 0x00]);

        data
    }

    #[test]
    fn test_extract_abi_bytes_valid_class() {
        let class_data = build_test_class(&[0xB1]); // return void
        let abi = extract_abi_bytes(&class_data);
        assert!(abi.is_some());
    }

    #[test]
    fn test_extract_abi_bytes_invalid_magic() {
        let data = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        assert!(extract_abi_bytes(&data).is_none());
    }

    #[test]
    fn test_extract_abi_bytes_too_short() {
        let data = vec![0xCA, 0xFE, 0xBA, 0xBE];
        assert!(extract_abi_bytes(&data).is_none());
    }

    #[test]
    fn test_abi_unchanged_when_method_body_changes() {
        // Two class files with same signature but different method body
        let class1 = build_test_class(&[0xB1]); // return
        let class2 = build_test_class(&[0x03, 0x57, 0xB1]); // iconst_0, pop, return

        let abi1 = extract_abi_bytes(&class1).unwrap();
        let abi2 = extract_abi_bytes(&class2).unwrap();

        // ABI should be identical since only the Code attribute differs
        assert_eq!(hash_bytes(&abi1), hash_bytes(&abi2));
    }

    #[test]
    fn test_abi_changes_when_signature_changes() {
        let class1 = build_test_class(&[0xB1]);
        let mut class2 = class1.clone();

        // Change the descriptor from "()V" to "()I" by modifying constant pool entry #6
        for i in 0..class2.len() - 2 {
            if &class2[i..i + 3] == b"()V" {
                class2[i + 2] = b'I';
                break;
            }
        }

        let abi1 = extract_abi_bytes(&class1).unwrap();
        let abi2 = extract_abi_bytes(&class2).unwrap();

        // ABI should differ since the method signature changed
        assert_ne!(hash_bytes(&abi1), hash_bytes(&abi2));
    }

    #[test]
    fn test_abi_excludes_private_members() {
        let class1 = build_test_class(&[0xB1]);
        let mut class2 = class1.clone();

        // Change the method from public (0x0001) to private (0x0002)
        // Find: fields_count(00 00) methods_count(00 01) access_flags(00 01)
        for i in 0..class2.len() - 6 {
            if class2[i] == 0x00 && class2[i+1] == 0x00
                && class2[i+2] == 0x00 && class2[i+3] == 0x01
                && class2[i+4] == 0x00 && class2[i+5] == 0x01
            {
                class2[i+5] = 0x02; // Change to PRIVATE
                break;
            }
        }

        let abi1 = extract_abi_bytes(&class1).unwrap();
        let abi2 = extract_abi_bytes(&class2).unwrap();

        // ABI should differ: public method included vs private method excluded
        assert_ne!(hash_bytes(&abi1), hash_bytes(&abi2));
    }

    #[test]
    fn test_is_utf8_constant_lookup() {
        let class_data = build_test_class(&[0xB1]);
        assert!(is_utf8_constant(&class_data, 7, b"Code"));
        assert!(is_utf8_constant(&class_data, 5, b"hello"));
        assert!(is_utf8_constant(&class_data, 1, b"Test"));
        assert!(!is_utf8_constant(&class_data, 1, b"Nope"));
        // CP #2 is a Class ref, not Utf8
        assert!(!is_utf8_constant(&class_data, 2, b"Test"));
    }

    #[test]
    fn test_read_u16_u32_helpers() {
        let data = [0x01, 0x02, 0x03, 0x04];
        assert_eq!(read_u16(&data, 0), Some(0x0102));
        assert_eq!(read_u16(&data, 2), Some(0x0304));
        assert_eq!(read_u32(&data, 0), Some(0x01020304));
        assert_eq!(read_u16(&data, 3), None);
        assert_eq!(read_u32(&data, 2), None);
    }

    #[test]
    fn test_fingerprints_abi_tracking() {
        let mut fp = Fingerprints::default();
        let path = Path::new("src/Foo.java");

        fp.update_source(path, "hash1", 1000);
        fp.update_abi(path, "abi_v1");

        assert!(!fp.abi_changed(path, "abi_v1"));
        assert!(fp.abi_changed(path, "abi_v2"));
        assert!(fp.abi_changed(Path::new("src/Bar.java"), "abi_v1"));
    }

    /// ADR-010 Defense ③: a class file with valid CAFEBABE magic is recognized.
    #[test]
    fn test_is_valid_class_file_valid_magic() {
        let tmp = tempfile::tempdir().unwrap();
        let class_file = tmp.path().join("Foo.class");
        std::fs::write(&class_file, b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();
        assert!(is_valid_class_file(&class_file));
    }

    /// ADR-010 Defense ③: a 0-byte class file (interrupted javac) returns false.
    #[test]
    fn test_is_valid_class_file_rejects_zero_byte() {
        let tmp = tempfile::tempdir().unwrap();
        let class_file = tmp.path().join("Broken.class");
        std::fs::File::create(&class_file).unwrap();
        assert_eq!(std::fs::metadata(&class_file).unwrap().len(), 0);
        assert!(!is_valid_class_file(&class_file), "0-byte class must be invalid");
    }

    /// ADR-010 Defense ③: a truncated class file (size < 8) returns false.
    #[test]
    fn test_is_valid_class_file_rejects_truncated() {
        let tmp = tempfile::tempdir().unwrap();
        let class_file = tmp.path().join("Trunc.class");
        std::fs::write(&class_file, b"\xCA\xFE\xBA").unwrap();
        assert!(!is_valid_class_file(&class_file));
    }

    /// ADR-010 Defense ③: a file without CAFEBABE magic is invalid even if size is large.
    #[test]
    fn test_is_valid_class_file_rejects_wrong_magic() {
        let tmp = tempfile::tempdir().unwrap();
        let class_file = tmp.path().join("Garbage.class");
        std::fs::write(&class_file, b"\x00\x00\x00\x00\x00\x00\x00\x00").unwrap();
        assert!(!is_valid_class_file(&class_file));
    }

    /// ADR-010 Defense ③: missing file returns false (not an error).
    #[test]
    fn test_is_valid_class_file_missing() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(!is_valid_class_file(&tmp.path().join("nope.class")));
    }

    /// ADR-010 Defense ③: find_class_for_source must skip 0-byte class files,
    /// forcing the source to be recompiled.
    #[test]
    fn test_find_class_for_source_skips_zero_byte() {
        let tmp = tempfile::tempdir().unwrap();
        let src_dir = tmp.path().join("src");
        let pkg_dir = src_dir.join("com").join("example");
        std::fs::create_dir_all(&pkg_dir).unwrap();
        let source = pkg_dir.join("Foo.java");
        std::fs::write(&source, "package com.example; class Foo {}").unwrap();

        let out_dir = tmp.path().join("out");
        let out_pkg = out_dir.join("com").join("example");
        std::fs::create_dir_all(&out_pkg).unwrap();
        // Simulate interrupted javac: 0-byte .class.
        std::fs::File::create(out_pkg.join("Foo.class")).unwrap();

        let result = find_class_for_source(&source, &[src_dir], &out_dir);
        assert!(result.is_none(),
            "0-byte class must be treated as missing → triggers recompilation");
    }

    /// ADR-010 Defense ④: save_build_cache must be atomic — sibling tmp + rename.
    /// Verify that after a successful save, both the cache_dir exists and no .tmp leaked.
    #[test]
    fn test_save_build_cache_atomic_no_tmp_leak() {
        let tmp = tempfile::tempdir().unwrap();
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"), b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let config = super::super::CompileConfig {
            source_dirs: vec![],
            output_dir: output_dir.clone(),
            classpath: vec![],
            java_version: Some("17".to_string()),
            encoding: None,
            annotation_processors: vec![],
            lint: vec![],
            extra_args: vec![],
        };
        let source_files = vec![tmp.path().join("Foo.java")];
        std::fs::write(&source_files[0], "class Foo {}").unwrap();

        save_build_cache(&config, &source_files).expect("save_build_cache must succeed");

        // Verify cache_dir exists and contains the class file
        let key = compute_build_cache_key(&config, &source_files).unwrap();
        let cache_dir = build_cache_dir(&key);
        assert!(cache_dir.exists(), "cache_dir must exist after save");
        assert!(cache_dir.join("Foo.class").exists(), "Foo.class must be in cache");

        // Verify no sibling .tmp leaked
        let tmp_sibling = cache_dir.parent().unwrap()
            .join(format!("{}.tmp", cache_dir.file_name().unwrap().to_str().unwrap()));
        assert!(!tmp_sibling.exists(), ".tmp sibling must not leak after rename");

        // Cleanup global cache dir we created
        let _ = std::fs::remove_dir_all(&cache_dir);
    }

    /// ADR-010 Defense ④: a stale .tmp from a prior interrupted run must be cleaned up,
    /// not block the next save.
    #[test]
    fn test_save_build_cache_clears_stale_tmp() {
        let tmp = tempfile::tempdir().unwrap();
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"), b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let config = super::super::CompileConfig {
            source_dirs: vec![],
            output_dir: output_dir.clone(),
            classpath: vec![],
            java_version: Some("21".to_string()),  // distinct version → distinct cache key
            encoding: None,
            annotation_processors: vec![],
            lint: vec![],
            extra_args: vec![],
        };
        let source_files = vec![tmp.path().join("StaleTmp.java")];
        std::fs::write(&source_files[0], "class StaleTmp {}").unwrap();

        // Pre-create a stale .tmp (as if a previous run was interrupted mid-copy)
        let key = compute_build_cache_key(&config, &source_files).unwrap();
        let cache_dir = build_cache_dir(&key);
        let parent = cache_dir.parent().unwrap();
        std::fs::create_dir_all(parent).unwrap();
        let stale_tmp = parent.join(format!("{}.tmp", cache_dir.file_name().unwrap().to_str().unwrap()));
        std::fs::create_dir_all(&stale_tmp).unwrap();
        std::fs::write(stale_tmp.join("garbage"), b"residue").unwrap();

        save_build_cache(&config, &source_files).expect("must clear stale tmp and succeed");

        assert!(cache_dir.exists(), "cache_dir must exist");
        assert!(!cache_dir.join("garbage").exists(),
            "stale residue from old tmp must NOT appear in final cache");
        assert!(cache_dir.join("Foo.class").exists(), "fresh content must be in cache");

        let _ = std::fs::remove_dir_all(&cache_dir);
    }

    /// ADR-013 root-cause regression: simulate the standard-task-core 750B
    /// incident pre-conditions and assert incremental_compile recognises that
    /// no compilation has actually happened (despite resources being present
    /// in output_dir).
    ///
    /// Pre-conditions of the bug:
    ///   1. output_dir was previously cleaned (no .class files)
    ///   2. resource files (e.g. graphqls) WERE copied into output_dir before
    ///      incremental_compile runs (this is what build.rs:2740 does)
    ///   3. fingerprints from a previous successful build still exist
    ///
    /// With OLD `has_classes = dir.next().is_some()`: misjudges as "already
    /// compiled", goes to UpToDate path, never invokes javac.
    /// With NEW `has_classes = any .class file`: correctly reports false,
    /// triggers full compile.
    #[test]
    fn test_has_classes_ignores_resources_only_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let output_dir = tmp.path().join("classes");
        std::fs::create_dir_all(&output_dir).unwrap();
        // Simulate "resources copied but no .class compiled yet" — exactly the
        // state build.rs leaves output_dir in just before calling
        // incremental_compile.
        let res_dir = output_dir.join("graphql");
        std::fs::create_dir_all(&res_dir).unwrap();
        std::fs::write(res_dir.join("Schema.graphqls"), b"type Q {}").unwrap();
        std::fs::write(output_dir.join("application.yml"), b"port: 8080").unwrap();

        // Inline the (small) has_classes check we use in incremental_compile to
        // pin the behaviour down without hauling in the whole compile config.
        let has_classes = output_dir.exists()
            && walkdir::WalkDir::new(&output_dir)
                .into_iter()
                .filter_map(|e| e.ok())
                .any(|e| e.path().extension().and_then(|s| s.to_str()) == Some("class"));

        assert!(!has_classes,
            "resources-only output_dir must NOT count as 'has compiled classes' \
             — otherwise incremental_compile skips javac and packaging produces \
             a 0-class jar (regression of 2026-05-03 standard-task-core)");
    }

    /// Sanity: actual .class file under output_dir does count.
    #[test]
    fn test_has_classes_detects_real_class() {
        let tmp = tempfile::tempdir().unwrap();
        let output_dir = tmp.path().join("classes");
        std::fs::create_dir_all(output_dir.join("com").join("example")).unwrap();
        std::fs::write(output_dir.join("com").join("example").join("Foo.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();
        // Mix in a resource for good measure.
        std::fs::write(output_dir.join("application.yml"), b"port: 8080").unwrap();

        let has_classes = output_dir.exists()
            && walkdir::WalkDir::new(&output_dir)
                .into_iter()
                .filter_map(|e| e.ok())
                .any(|e| e.path().extension().and_then(|s| s.to_str()) == Some("class"));

        assert!(has_classes,
            "output_dir with at least one .class file must count as having compiled classes");
    }

    // ─────────────────────────────────────────────────────────────────────
    // ADR-014: BuildManifest tests
    // ─────────────────────────────────────────────────────────────────────

    /// Round-trip: write a manifest, load it, fields preserved.
    #[test]
    fn test_build_manifest_write_load_roundtrip() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();
        let nested = output_dir.join("com").join("example");
        std::fs::create_dir_all(&nested).unwrap();
        std::fs::write(nested.join("Bar.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let sources = vec![
            tmp.path().join("Foo.java"),
            tmp.path().join("com/example/Bar.java"),
        ];

        BuildManifest::write(&fp_dir, &output_dir, &sources).unwrap();

        let loaded = BuildManifest::load(&fp_dir).expect("manifest must load");
        assert_eq!(loaded.ym_version, env!("CARGO_PKG_VERSION"));
        assert_eq!(loaded.source_paths.len(), 2, "two sources recorded");
        assert_eq!(loaded.class_paths.len(), 2, "two .class files recorded");
        // class paths are sorted, normalized to forward slashes
        assert!(loaded.class_paths.iter().any(|p| p == "Foo.class"));
        assert!(loaded.class_paths.iter().any(|p| p == "com/example/Bar.class"));
    }

    /// Manifest write goes through tmp + rename — no .json.tmp leaks after.
    #[test]
    fn test_build_manifest_write_atomic_no_tmp_leak() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();

        BuildManifest::write(&fp_dir, &output_dir, &[]).unwrap();

        assert!(fp_dir.join("build-manifest.json").exists(), "manifest must exist");
        assert!(!fp_dir.join("build-manifest.json.tmp").exists(),
            ".tmp must not leak after rename");
    }

    /// is_consistent_with returns true when source set + recorded class files all match.
    #[test]
    fn test_build_manifest_consistent_when_all_match() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let sources = vec![tmp.path().join("Foo.java")];
        BuildManifest::write(&fp_dir, &output_dir, &sources).unwrap();
        let manifest = BuildManifest::load(&fp_dir).unwrap();

        assert!(manifest.is_consistent_with(&sources, &output_dir),
            "freshly written manifest must be consistent with the same source list");
    }

    /// is_consistent_with returns false when a recorded .class is gone (user rm'd out/).
    #[test]
    fn test_build_manifest_invalid_when_class_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let sources = vec![tmp.path().join("Foo.java")];
        BuildManifest::write(&fp_dir, &output_dir, &sources).unwrap();
        let manifest = BuildManifest::load(&fp_dir).unwrap();

        // Simulate user `rm -rf out/`: class file vanishes
        std::fs::remove_file(output_dir.join("Foo.class")).unwrap();

        assert!(!manifest.is_consistent_with(&sources, &output_dir),
            "manifest must invalidate when a recorded .class file is missing — \
             prevents 'cache says we built it but it's not on disk' silent failure");
    }

    /// is_consistent_with returns false when source list changes (user added/removed .java).
    #[test]
    fn test_build_manifest_invalid_when_sources_change() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");
        let output_dir = tmp.path().join("out");
        std::fs::create_dir_all(&output_dir).unwrap();
        std::fs::write(output_dir.join("Foo.class"),
            b"\xCA\xFE\xBA\xBE\x00\x00\x00\x42").unwrap();

        let sources_v1 = vec![tmp.path().join("Foo.java")];
        BuildManifest::write(&fp_dir, &output_dir, &sources_v1).unwrap();
        let manifest = BuildManifest::load(&fp_dir).unwrap();

        // Simulate adding a new .java file
        let sources_v2 = vec![
            tmp.path().join("Foo.java"),
            tmp.path().join("Bar.java"),
        ];
        assert!(!manifest.is_consistent_with(&sources_v2, &output_dir),
            "manifest must invalidate when source set grew");

        // Simulate removing a source
        let sources_v3: Vec<PathBuf> = vec![];
        assert!(!manifest.is_consistent_with(&sources_v3, &output_dir),
            "manifest must invalidate when source set shrank");
    }

    /// Critical regression: manifest fast-path does NOT trip on resource-only
    /// output_dir (the standard-task-core 750B incident scenario at the
    /// fingerprint+manifest layer instead of the has_classes layer).
    ///
    /// Before manifest: a fresh build with stale fingerprints would silently
    /// skip javac. With manifest: no manifest exists yet → no fast-path
    /// shortcut → falls through to has_classes / cache restore / javac.
    #[test]
    fn test_build_manifest_absent_means_no_fastpath() {
        let tmp = tempfile::tempdir().unwrap();
        let fp_dir = tmp.path().join("fp");

        // No manifest written.
        assert!(BuildManifest::load(&fp_dir).is_none(),
            "absent manifest → load returns None → no fast-path → falls through");
    }
}