socket-patch-core 3.2.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
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
use std::collections::HashMap;
use std::path::Path;
#[cfg(unix)]
use std::path::PathBuf;

use crate::hash::git_sha256::compute_git_sha256_from_bytes;
use crate::manifest::schema::PatchFileInfo;
use crate::patch::cow::break_hardlink_if_needed;
use crate::patch::diff::apply_diff;
use crate::patch::file_hash::compute_file_git_sha256;
use crate::patch::package::read_archive_filtered;

/// Status of a file patch verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerifyStatus {
    /// File is ready to be patched (current hash matches beforeHash).
    Ready,
    /// File is already in the patched state (current hash matches afterHash).
    AlreadyPatched,
    /// File hash does not match either beforeHash or afterHash.
    HashMismatch,
    /// File was not found on disk.
    NotFound,
}

/// Result of verifying whether a single file can be patched.
#[derive(Debug, Clone)]
pub struct VerifyResult {
    pub file: String,
    pub status: VerifyStatus,
    pub message: Option<String>,
    pub current_hash: Option<String>,
    pub expected_hash: Option<String>,
    pub target_hash: Option<String>,
}

/// Which patch source actually wrote the patched bytes for a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppliedVia {
    /// Bytes came from a per-package archive in `.socket/packages/`.
    Package,
    /// Bytes were produced by applying a bsdiff delta from
    /// `.socket/diffs/<uuid>.tar.gz`.
    Diff,
    /// Bytes came from a per-file blob in `.socket/blobs/`.
    Blob,
}

impl AppliedVia {
    /// Short lowercase tag, suitable for JSON and human output.
    pub fn as_tag(&self) -> &'static str {
        match self {
            AppliedVia::Package => "package",
            AppliedVia::Diff => "diff",
            AppliedVia::Blob => "blob",
        }
    }
}

/// Patch sources the apply pipeline may use to obtain patched bytes.
///
/// `blobs_path` is always required and serves as the universal fallback.
/// `packages_path` and `diffs_path` are optional opt-ins to the new
/// pathways introduced in socket-patch 2.2.
#[derive(Debug, Clone, Copy)]
pub struct PatchSources<'a> {
    pub blobs_path: &'a Path,
    pub packages_path: Option<&'a Path>,
    pub diffs_path: Option<&'a Path>,
}

impl<'a> PatchSources<'a> {
    /// Construct a `PatchSources` that only knows about the legacy
    /// per-file blob directory. Convenient for tests and existing call
    /// sites that have not been upgraded.
    pub fn blobs_only(blobs_path: &'a Path) -> Self {
        Self {
            blobs_path,
            packages_path: None,
            diffs_path: None,
        }
    }
}

/// Result of applying patches to a single package.
#[derive(Debug, Clone)]
pub struct ApplyResult {
    pub package_key: String,
    pub package_path: String,
    pub success: bool,
    pub files_verified: Vec<VerifyResult>,
    pub files_patched: Vec<String>,
    /// Per-file record of which source produced the patched bytes. Only
    /// populated for files in `files_patched`.
    pub applied_via: HashMap<String, AppliedVia>,
    pub error: Option<String>,
    /// Ecosystem sidecar fixup outcome — a typed
    /// [`SidecarRecord`](crate::patch::sidecars::SidecarRecord) carrying
    /// per-file actions (rewritten / deleted / created) and an
    /// optional structured advisory. `None` when no sidecar
    /// applied (e.g. npm) or when no files were patched.
    ///
    /// Surfaced in the CLI JSON envelope under
    /// `Envelope.sidecars[]` (top-level, not per-event).
    pub sidecar: Option<crate::patch::sidecars::SidecarRecord>,
}

/// Normalize file path by removing the "package/" prefix if present.
/// Patch files come from the API with paths like "package/lib/file.js"
/// but we need relative paths like "lib/file.js" for the actual package directory.
pub fn normalize_file_path(file_name: &str) -> &str {
    const PACKAGE_PREFIX: &str = "package/";
    if let Some(stripped) = file_name.strip_prefix(PACKAGE_PREFIX) {
        stripped
    } else {
        file_name
    }
}

/// Verify a single file can be patched.
pub async fn verify_file_patch(
    pkg_path: &Path,
    file_name: &str,
    file_info: &PatchFileInfo,
) -> VerifyResult {
    let normalized = normalize_file_path(file_name);
    let filepath = pkg_path.join(normalized);

    let is_new_file = file_info.before_hash.is_empty();

    // Check if file exists
    if tokio::fs::metadata(&filepath).await.is_err() {
        // New files (empty beforeHash) are expected to not exist yet.
        if is_new_file {
            return VerifyResult {
                file: file_name.to_string(),
                status: VerifyStatus::Ready,
                message: None,
                current_hash: None,
                expected_hash: None,
                target_hash: Some(file_info.after_hash.clone()),
            };
        }
        return VerifyResult {
            file: file_name.to_string(),
            status: VerifyStatus::NotFound,
            message: Some("File not found".to_string()),
            current_hash: None,
            expected_hash: None,
            target_hash: None,
        };
    }

    // Compute current hash
    let current_hash = match compute_file_git_sha256(&filepath).await {
        Ok(h) => h,
        Err(e) => {
            return VerifyResult {
                file: file_name.to_string(),
                status: VerifyStatus::NotFound,
                message: Some(format!("Failed to hash file: {}", e)),
                current_hash: None,
                expected_hash: None,
                target_hash: None,
            };
        }
    };

    // Check if already patched
    if current_hash == file_info.after_hash {
        return VerifyResult {
            file: file_name.to_string(),
            status: VerifyStatus::AlreadyPatched,
            message: None,
            current_hash: Some(current_hash),
            expected_hash: None,
            target_hash: None,
        };
    }

    // New files (empty beforeHash) with existing content that doesn't match
    // afterHash: treat as Ready (force overwrite).
    if is_new_file {
        return VerifyResult {
            file: file_name.to_string(),
            status: VerifyStatus::Ready,
            message: None,
            current_hash: Some(current_hash),
            expected_hash: None,
            target_hash: Some(file_info.after_hash.clone()),
        };
    }

    // Check if matches expected before hash
    if current_hash != file_info.before_hash {
        return VerifyResult {
            file: file_name.to_string(),
            status: VerifyStatus::HashMismatch,
            message: Some("File hash does not match expected value".to_string()),
            current_hash: Some(current_hash),
            expected_hash: Some(file_info.before_hash.clone()),
            target_hash: Some(file_info.after_hash.clone()),
        };
    }

    VerifyResult {
        file: file_name.to_string(),
        status: VerifyStatus::Ready,
        message: None,
        current_hash: Some(current_hash),
        expected_hash: None,
        target_hash: Some(file_info.after_hash.clone()),
    }
}

/// Select the single variant whose installed bytes match the on-disk
/// distribution — i.e. the "minimally required" release for this
/// environment.
///
/// A package@version may resolve to several patch variants (PyPI
/// `?artifact_id=...` releases, one per wheel/sdist). Only one
/// distribution is ever installed in a given environment, so only one
/// variant can apply. This mirrors the first-file hash check the apply
/// pipeline uses: a variant matches when its first patched file is not
/// in a [`VerifyStatus::HashMismatch`] state against the on-disk
/// package. A variant with no files (nothing to verify) is treated as a
/// match.
///
/// `variants` maps a variant key (typically a qualified PURL) to that
/// variant's patched files. Returns the indices of **every** variant
/// whose first patched file is in a [`VerifyStatus::Ready`] or
/// [`VerifyStatus::AlreadyPatched`] state — i.e. its `beforeHash` (or
/// `afterHash`, if already applied) matches the installed bytes.
///
/// A [`VerifyStatus::NotFound`] (a missing pre-existing file) or
/// [`VerifyStatus::HashMismatch`] does **not** count as a match: those
/// signal the variant describes a distribution that is *not* present on
/// disk. A variant with no files (nothing to verify) is treated as a
/// match.
///
/// Returning all matches (not just the first) is what lets ecosystems
/// whose variants *coexist* on disk work — e.g. Maven, where several
/// classifier jars (`foo-1.0.jar`, `foo-1.0-linux-x86_64.jar`) live in
/// one version directory and each maps to its own file. For PyPI and
/// RubyGems exactly one distribution is installed per environment, so
/// this naturally yields ≤1 index and their behavior is unchanged. The
/// narrow download filter (scan/get) and the rollback dedupe share this
/// helper so release selection stays consistent with apply.
pub async fn select_installed_variants(
    pkg_path: &Path,
    variants: &[(&str, &HashMap<String, PatchFileInfo>)],
) -> Vec<usize> {
    let mut matched = Vec::new();
    for (idx, (_key, files)) in variants.iter().enumerate() {
        // No files to verify — nothing to disqualify the variant.
        let Some((file_name, file_info)) = files.iter().next() else {
            matched.push(idx);
            continue;
        };
        let verify = verify_file_patch(pkg_path, file_name, file_info).await;
        if matches!(
            verify.status,
            VerifyStatus::Ready | VerifyStatus::AlreadyPatched
        ) {
            matched.push(idx);
        }
    }
    matched
}

/// Apply a patch to a single file.
///
/// **Permission policy** (per the user-visible contract — patched
/// files must look identical to pre-patch perms-wise):
///
/// 1. **Existing file**. Snapshot mode + owner + group before writing.
///    If the file is read-only, temporarily grant owner-write so the
///    overwrite succeeds (e.g. Go's module cache marks sources read-only).
///    After the write, restore the **exact** original mode and chown
///    back to the pre-patch uid/gid. Owners stay put even when
///    `tokio::fs::write` truncates and rewrites.
///
/// 2. **New file** (created by the patch). Inherit owner + group from
///    the parent directory and force mode `0o444` (read-only for all).
///    Mirrors how an unpacked tarball treats new package files —
///    consumers expect package sources to be read-only by default.
///
/// On Windows there is no `uid`/`gid`, so the owner/group step is a
/// no-op; the read-only attribute is preserved on existing files and
/// set on new files to honor the read-only-by-default policy.
///
/// Writes the patched content and verifies the resulting hash.
pub async fn apply_file_patch(
    pkg_path: &Path,
    file_name: &str,
    patched_content: &[u8],
    expected_hash: &str,
) -> Result<(), std::io::Error> {
    let normalized = normalize_file_path(file_name);
    let filepath = pkg_path.join(normalized);

    // Hash-check the in-memory content BEFORE touching disk. Removes
    // the prior "wrote bytes, then post-write verify failed, can't
    // restore" failure mode — if the upstream blob is corrupt we
    // error out before any disk write.
    let content_hash = compute_git_sha256_from_bytes(patched_content);
    if content_hash != expected_hash {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "Hash verification failed before patch. Expected: {}, Got: {}",
                expected_hash, content_hash
            ),
        ));
    }

    // Snapshot pre-patch metadata so `restore_file_permissions` can
    // re-apply the original mode + uid/gid to the post-rename inode.
    // `None` means the file is being created by this patch — the
    // new-file branch of restore_file_permissions inherits from the
    // parent dir.
    let existing_meta = tokio::fs::metadata(&filepath).await.ok();

    // Create parent directories if needed (e.g., new files added by a patch).
    if let Some(parent) = filepath.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }

    // The atomic stage+rename below — and the copy-on-write break, which
    // also stages a sibling file — need write permission on the *parent
    // directory*, not just on the file. Go's module cache marks both its
    // files (0o444) and its directories (0o555) read-only, so without
    // this the stage-file creation fails with EACCES (where the old
    // in-place write, like `rollback.rs`, only had to relax the file's
    // own mode). Temporarily grant owner-write on the directory; the
    // guard restores its exact mode below.
    let dir_guard = DirWriteGuard::acquire(filepath.parent()).await;

    // Copy-on-write defense against pnpm / bazel / nix shared inodes.
    // If `filepath` is a symlink into a content store, or a hardlink
    // shared with other projects, give this project a private inode
    // before we mutate. No-op on regular private files (single
    // syscall). See `patch::cow`.
    //
    // Atomic write: stage in the parent directory, fsync, rename onto
    // the target. POSIX `rename(2)` is atomic — observers see either
    // the old bytes or the new bytes, never a truncated half-write.
    //
    // The stage file is created with the user's umask defaults
    // (typically 0o644) — that's how we sidestep the "existing file
    // is 0o444" problem the old in-place write had: we rename a fresh
    // user-writable inode over the target instead of trying to open
    // a read-only file for write. `restore_file_permissions` then
    // re-applies the pre-patch mode + uid/gid to the new inode.
    //
    // Both steps run inside a closure so the directory mode is ALWAYS
    // restored — even if a step errors — before the failure propagates.
    let write_result = async {
        break_hardlink_if_needed(&filepath).await?;
        write_atomic(&filepath, patched_content).await
    }
    .await;
    dir_guard.restore().await;
    write_result?;

    // Restore (or set) the final permissions on the post-rename inode.
    // On Unix this includes chown back to the pre-patch uid/gid (or
    // to the parent dir's uid/gid for new files); on Windows we only
    // manage the readonly attribute.
    restore_file_permissions(&filepath, existing_meta.as_ref()).await?;

    Ok(())
}

/// Guard that temporarily grants owner-write on a directory so the
/// stage+rename write path can create and move files inside it, then
/// restores the directory's original mode.
///
/// Go's module cache (and some Nix/Bazel layouts) mark package
/// directories read-only (`0o555`). Creating the `.socket-stage-*` file
/// and renaming it over the target both require write permission on the
/// directory, so we relax it for the duration of the write and put it
/// back exactly as we found it. [`DirWriteGuard::restore`] is a no-op
/// when nothing was changed (already-writable dir, missing dir, a
/// `set_permissions` failure, or non-Unix — where a directory's
/// read-only attribute does not gate file creation).
pub(crate) struct DirWriteGuard {
    #[cfg(unix)]
    relock: Option<(PathBuf, u32)>,
}

impl DirWriteGuard {
    pub(crate) async fn acquire(dir: Option<&Path>) -> Self {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Some(dir) = dir {
                if let Ok(meta) = tokio::fs::metadata(dir).await {
                    let mode = meta.permissions().mode();
                    // Owner-write bit missing → relax it, remembering the
                    // original mode so `restore` can re-lock the dir.
                    if mode & 0o200 == 0 {
                        let mut perms = meta.permissions();
                        perms.set_mode(mode | 0o200);
                        if tokio::fs::set_permissions(dir, perms).await.is_ok() {
                            return Self {
                                relock: Some((dir.to_path_buf(), mode)),
                            };
                        }
                    }
                }
            }
            Self { relock: None }
        }
        #[cfg(not(unix))]
        {
            let _ = dir;
            Self {}
        }
    }

    pub(crate) async fn restore(self) {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            if let Some((dir, mode)) = self.relock {
                let _ =
                    tokio::fs::set_permissions(&dir, std::fs::Permissions::from_mode(mode)).await;
            }
        }
    }
}

/// Write `content` to `target` atomically via stage + rename.
///
/// Two-phase commit:
///   1. Create `<parent>/.socket-stage-<filename>-<uuid>` (leading dot
///      so editor globs ignore it; uuid suffix so concurrent callers
///      never collide — defense in depth on top of the apply lock).
///   2. `write_all` the content, then `sync_all()` so the bytes are
///      durably on disk before the rename.
///   3. `rename(stage, target)` — atomic on POSIX, best-effort on
///      Windows. On failure unlink the stage so we don't leave a
///      dotfile behind in the package directory.
async fn write_atomic(target: &Path, content: &[u8]) -> std::io::Result<()> {
    let parent = target.parent().unwrap_or_else(|| Path::new("."));
    let stem = target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "anon".to_string());
    let stage = parent.join(format!(".socket-stage-{}-{}", stem, uuid::Uuid::new_v4()));

    let mut file = tokio::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&stage)
        .await?;

    use tokio::io::AsyncWriteExt;
    if let Err(e) = file.write_all(content).await {
        let _ = tokio::fs::remove_file(&stage).await;
        return Err(e);
    }
    if let Err(e) = file.sync_all().await {
        let _ = tokio::fs::remove_file(&stage).await;
        return Err(e);
    }
    drop(file);

    if let Err(e) = tokio::fs::rename(&stage, target).await {
        let _ = tokio::fs::remove_file(&stage).await;
        return Err(e);
    }

    // Durability: `sync_all` above flushed the file's *data*, but the
    // rename only updated the parent directory entry. fsync the
    // directory so the rename itself survives a crash — otherwise a
    // post-crash filesystem could surface the old name (or neither).
    // Unix only; best-effort, since a directory we can't open for fsync
    // must not fail an otherwise-successful write.
    #[cfg(unix)]
    {
        if let Ok(dir) = tokio::fs::File::open(parent).await {
            let _ = dir.sync_all().await;
        }
    }

    Ok(())
}

/// Restore the post-write permission state on `filepath`.
///
/// * `pre_patch` = `Some(meta)` → the file existed before the patch;
///   restore its exact mode + uid/gid.
/// * `pre_patch` = `None` → the file is new; inherit owner/group from
///   the parent dir and set mode `0o444`.
///
/// Split out of `apply_file_patch` to keep that function readable and
/// to make the platform branching unit-testable.
async fn restore_file_permissions(
    filepath: &Path,
    pre_patch: Option<&std::fs::Metadata>,
) -> Result<(), std::io::Error> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        match pre_patch {
            Some(meta) => {
                // Existing file: re-apply the original ownership FIRST,
                // then the mode. Order matters — `chown(2)` clears the
                // setuid/setgid bits for an unprivileged caller (even when
                // the uid/gid are unchanged), so the chmod must run last
                // to restore the mode bit-for-bit, setuid/setgid included.
                let uid = meta.uid();
                let gid = meta.gid();
                chown_blocking(filepath.to_path_buf(), Some(uid), Some(gid)).await?;
                let restored = std::fs::Permissions::from_mode(meta.mode());
                tokio::fs::set_permissions(filepath, restored).await?;
            }
            None => {
                // New file. Inherit owner/group from the parent dir.
                if let Some(parent) = filepath.parent() {
                    if let Ok(parent_meta) = tokio::fs::metadata(parent).await {
                        let uid = parent_meta.uid();
                        let gid = parent_meta.gid();
                        chown_blocking(filepath.to_path_buf(), Some(uid), Some(gid)).await?;
                    }
                }
                // Default new-file mode: read-only for all.
                let readonly = std::fs::Permissions::from_mode(0o444);
                tokio::fs::set_permissions(filepath, readonly).await?;
            }
        }
    }

    #[cfg(windows)]
    {
        match pre_patch {
            Some(meta) => {
                // Re-apply the pre-patch readonly state; tokio::fs::write
                // does not preserve it across the truncate+rewrite.
                let perms = meta.permissions();
                tokio::fs::set_permissions(filepath, perms).await?;
            }
            None => {
                // New file: read-only by default.
                if let Ok(meta) = tokio::fs::metadata(filepath).await {
                    let mut perms = meta.permissions();
                    perms.set_readonly(true);
                    tokio::fs::set_permissions(filepath, perms).await?;
                }
            }
        }
    }

    let _ = filepath;
    let _ = pre_patch;
    Ok(())
}

/// Synchronous `chown` wrapped to run on the blocking pool so we don't
/// stall the async runtime. `std::os::unix::fs::chown` is a thin
/// syscall wrapper — fast in the no-op case (uid/gid already match)
/// but still nominally blocking.
#[cfg(unix)]
async fn chown_blocking(
    path: std::path::PathBuf,
    uid: Option<u32>,
    gid: Option<u32>,
) -> Result<(), std::io::Error> {
    tokio::task::spawn_blocking(move || std::os::unix::fs::chown(&path, uid, gid))
        .await
        .map_err(|e| std::io::Error::other(e.to_string()))?
}

/// Verify and apply patches for a single package.
///
/// For each file in `files`, this function:
/// 1. Verifies the file is ready to be patched (or already patched).
/// 2. If not dry_run, tries patch sources in order: package archive → diff
///    archive → per-file blob. Each strategy is opt-in via `sources`.
/// 3. Returns a summary of what happened.
///
/// `uuid` is the patch UUID. Pass `Some` to enable package- and
/// diff-archive lookup (the corresponding `sources.packages_path` /
/// `sources.diffs_path` must also be set). Pass `None` to restrict the
/// pipeline to per-file blobs only — equivalent to pre-2.2 behavior.
pub async fn apply_package_patch(
    package_key: &str,
    pkg_path: &Path,
    files: &HashMap<String, PatchFileInfo>,
    sources: &PatchSources<'_>,
    uuid: Option<&str>,
    dry_run: bool,
    force: bool,
) -> ApplyResult {
    let mut result = ApplyResult {
        package_key: package_key.to_string(),
        package_path: pkg_path.display().to_string(),
        success: false,
        files_verified: Vec::new(),
        files_patched: Vec::new(),
        applied_via: HashMap::new(),
        error: None,
        sidecar: None,
    };

    // First, verify all files
    for (file_name, file_info) in files {
        let mut verify_result = verify_file_patch(pkg_path, file_name, file_info).await;

        if verify_result.status != VerifyStatus::Ready
            && verify_result.status != VerifyStatus::AlreadyPatched
        {
            if force {
                match verify_result.status {
                    VerifyStatus::HashMismatch => {
                        // Force: treat hash mismatch as ready
                        verify_result.status = VerifyStatus::Ready;
                    }
                    VerifyStatus::NotFound => {
                        // Force: skip files that don't exist (non-new files)
                        result.files_verified.push(verify_result);
                        continue;
                    }
                    _ => {}
                }
            } else {
                let msg = verify_result
                    .message
                    .clone()
                    .unwrap_or_else(|| format!("{:?}", verify_result.status));
                result.error = Some(format!(
                    "Cannot apply patch: {} - {}",
                    verify_result.file, msg
                ));
                result.files_verified.push(verify_result);
                return result;
            }
        }

        result.files_verified.push(verify_result);
    }

    // Check if all files are already patched
    let all_already_patched = result
        .files_verified
        .iter()
        .all(|v| v.status == VerifyStatus::AlreadyPatched);

    if all_already_patched {
        result.success = true;
        return result;
    }

    // Check if all files are either already patched or not found (force mode skip)
    let all_done_or_skipped = result
        .files_verified
        .iter()
        .all(|v| v.status == VerifyStatus::AlreadyPatched || v.status == VerifyStatus::NotFound);

    if all_done_or_skipped {
        // Some or all files were not found but skipped via --force
        let not_found_count = result
            .files_verified
            .iter()
            .filter(|v| v.status == VerifyStatus::NotFound)
            .count();
        result.success = true;
        result.error = Some(format!(
            "All patch files were skipped: {} not found on disk (--force)",
            not_found_count
        ));
        return result;
    }

    // If dry run, stop here
    if dry_run {
        result.success = true;
        return result;
    }

    // Eagerly load the package and diff archives (if any) into memory so
    // we don't reparse the tar.gz once per file. Both are small archives.
    let package_entries = match (uuid, sources.packages_path) {
        (Some(uuid), Some(dir)) => load_archive_if_present(dir, uuid, files).await,
        _ => None,
    };
    let diff_entries = match (uuid, sources.diffs_path) {
        (Some(uuid), Some(dir)) => load_archive_if_present(dir, uuid, files).await,
        _ => None,
    };

    // Apply patches to files that need it. For each file, try package
    // archive first, then diff, then blob.
    for (file_name, file_info) in files {
        let verify_result = result.files_verified.iter().find(|v| v.file == *file_name);
        if let Some(vr) = verify_result {
            if vr.status == VerifyStatus::AlreadyPatched || vr.status == VerifyStatus::NotFound {
                continue;
            }
        }

        let normalized = normalize_file_path(file_name).to_string();

        // ── Strategy 1: package archive ──────────────────────────────
        if try_apply_from_archive(
            package_entries.as_ref(),
            &normalized,
            pkg_path,
            file_name,
            file_info,
        )
        .await
        {
            result.files_patched.push(file_name.clone());
            result
                .applied_via
                .insert(file_name.clone(), AppliedVia::Package);
            continue;
        }

        // ── Strategy 2: per-file diff ────────────────────────────────
        // Diffs only apply cleanly when the on-disk content actually
        // hashes to `before_hash` — otherwise the bsdiff output won't
        // match `after_hash`. We pass the pre-apply current_hash
        // captured by `verify_file_patch` so `try_apply_from_diff` can
        // skip the wasted decompress+apply work when --force is
        // overriding a hash mismatch (force flips status to Ready but
        // the underlying hash is still wrong).
        let current_hash_for_diff = verify_result.and_then(|v| v.current_hash.as_deref());
        if try_apply_from_diff(
            diff_entries.as_ref(),
            &normalized,
            pkg_path,
            file_name,
            file_info,
            current_hash_for_diff,
        )
        .await
        {
            result.files_patched.push(file_name.clone());
            result
                .applied_via
                .insert(file_name.clone(), AppliedVia::Diff);
            continue;
        }

        // ── Strategy 3: per-file blob (legacy fallback) ──────────────
        let blob_path = sources.blobs_path.join(&file_info.after_hash);
        let patched_content = match tokio::fs::read(&blob_path).await {
            Ok(content) => content,
            Err(e) => {
                result.error = Some(format!(
                    "Failed to read blob {}: {}",
                    file_info.after_hash, e
                ));
                return result;
            }
        };

        if let Err(e) =
            apply_file_patch(pkg_path, file_name, &patched_content, &file_info.after_hash).await
        {
            result.error = Some(e.to_string());
            return result;
        }

        result.files_patched.push(file_name.clone());
        result
            .applied_via
            .insert(file_name.clone(), AppliedVia::Blob);
    }

    // Ecosystem sidecar fixup. Best-effort: a failing sidecar does
    // NOT undo the patch (the bytes were committed atomically via
    // stage+rename; nothing to roll back). The error path is
    // converted at this boundary into a `SidecarRecord` carrying
    // `SidecarAdvisoryCode::SidecarFixupFailed` so downstream
    // consumers see a uniform shape regardless of whether the
    // fixup succeeded, was advisory-only, or raised an error.
    if !result.files_patched.is_empty() {
        use crate::patch::sidecars::{
            dispatch_fixup, SidecarAdvisory, SidecarAdvisoryCode, SidecarRecord, SidecarSeverity,
        };
        match dispatch_fixup(package_key, pkg_path, &result.files_patched, files).await {
            Ok(Some(record)) => result.sidecar = Some(record),
            Ok(None) => {}
            Err(e) => {
                let ecosystem = crate::crawlers::Ecosystem::from_purl(package_key)
                    .map(|eco| eco.cli_name().to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                result.sidecar = Some(SidecarRecord {
                    purl: package_key.to_string(),
                    ecosystem,
                    files: Vec::new(),
                    advisory: Some(SidecarAdvisory {
                        code: SidecarAdvisoryCode::SidecarFixupFailed,
                        severity: SidecarSeverity::Error,
                        message: format!("sidecar fixup failed (patch still applied): {}", e),
                    }),
                });
            }
        }
    }

    result.success = true;
    result
}

/// Try to write the patched bytes from `package_entries[normalized_path]`
/// to disk, verifying the post-write hash. Returns `true` on success.
async fn try_apply_from_archive(
    package_entries: Option<&HashMap<String, Vec<u8>>>,
    normalized_path: &str,
    pkg_path: &Path,
    file_name: &str,
    file_info: &PatchFileInfo,
) -> bool {
    let entries = match package_entries {
        Some(e) => e,
        None => return false,
    };
    let bytes = match entries.get(normalized_path) {
        Some(b) => b,
        None => return false,
    };
    if compute_git_sha256_from_bytes(bytes) != file_info.after_hash {
        return false;
    }
    apply_file_patch(pkg_path, file_name, bytes, &file_info.after_hash)
        .await
        .is_ok()
}

/// Try to apply the bsdiff delta from `diff_entries[normalized_path]` to
/// the on-disk file at `pkg_path/normalized_path`. Bails out (returning
/// `false`) for any of:
///   * no diff entry,
///   * `current_hash` is missing or doesn't match `file_info.before_hash`
///     (this is the strong gate — even `--force` promoting a
///     HashMismatch to Ready will still bail here, because the on-disk
///     hash captured by `verify_file_patch` was the real, mismatched
///     value),
///   * `file_info.before_hash` is empty (new files),
///   * read/diff/verify/write failure.
async fn try_apply_from_diff(
    diff_entries: Option<&HashMap<String, Vec<u8>>>,
    normalized_path: &str,
    pkg_path: &Path,
    file_name: &str,
    file_info: &PatchFileInfo,
    current_hash: Option<&str>,
) -> bool {
    let entries = match diff_entries {
        Some(e) => e,
        None => return false,
    };
    let delta = match entries.get(normalized_path) {
        Some(d) => d,
        None => return false,
    };
    if file_info.before_hash.is_empty() {
        // New files have no before content to diff against.
        return false;
    }
    // Strong invariant: only run the diff when on-disk bytes hash to
    // exactly the `before_hash` the delta was authored against. This
    // closes the force-mode loophole — `--force` flips VerifyStatus to
    // Ready, but `current_hash` retains the original on-disk hash, so
    // the comparison below still rejects.
    match current_hash {
        Some(h) if h == file_info.before_hash => {}
        _ => return false,
    }

    let on_disk_path = pkg_path.join(normalized_path);
    let before_bytes = match tokio::fs::read(&on_disk_path).await {
        Ok(b) => b,
        Err(_) => return false,
    };
    let patched = match apply_diff(&before_bytes, delta) {
        Ok(p) => p,
        Err(_) => return false,
    };
    if compute_git_sha256_from_bytes(&patched) != file_info.after_hash {
        return false;
    }
    apply_file_patch(pkg_path, file_name, &patched, &file_info.after_hash)
        .await
        .is_ok()
}

/// Open `<dir>/<uuid>.tar.gz` (if it exists) and return its entries
/// filtered to the patched files in `files`. Errors and missing files
/// both yield `None` so the caller silently falls through to the next
/// strategy.
async fn load_archive_if_present(
    dir: &Path,
    uuid: &str,
    files: &HashMap<String, PatchFileInfo>,
) -> Option<HashMap<String, Vec<u8>>> {
    let archive_path = dir.join(format!("{uuid}.tar.gz"));
    if tokio::fs::metadata(&archive_path).await.is_err() {
        return None;
    }
    // `read_archive_filtered` is synchronous (tar + flate2 are sync). Run
    // it on the blocking pool so we don't stall the executor for large
    // archives.
    let archive_path_owned = archive_path.clone();
    let files_owned = files.clone();
    tokio::task::spawn_blocking(move || read_archive_filtered(&archive_path_owned, &files_owned))
        .await
        .ok()
        .and_then(|r| r.ok())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash::git_sha256::compute_git_sha256_from_bytes;

    #[test]
    fn test_normalize_file_path_with_prefix() {
        assert_eq!(
            normalize_file_path("package/lib/server.js"),
            "lib/server.js"
        );
    }

    #[test]
    fn test_normalize_file_path_without_prefix() {
        assert_eq!(normalize_file_path("lib/server.js"), "lib/server.js");
    }

    #[test]
    fn test_normalize_file_path_just_prefix() {
        assert_eq!(normalize_file_path("package/"), "");
    }

    #[test]
    fn test_normalize_file_path_package_not_prefix() {
        // "package" without trailing "/" should NOT be stripped
        assert_eq!(
            normalize_file_path("packagefoo/bar.js"),
            "packagefoo/bar.js"
        );
    }

    #[tokio::test]
    async fn test_verify_file_patch_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let file_info = PatchFileInfo {
            before_hash: "aaa".to_string(),
            after_hash: "bbb".to_string(),
        };

        let result = verify_file_patch(dir.path(), "nonexistent.js", &file_info).await;
        assert_eq!(result.status, VerifyStatus::NotFound);
    }

    #[tokio::test]
    async fn test_verify_file_patch_ready() {
        let dir = tempfile::tempdir().unwrap();
        let content = b"original content";
        let before_hash = compute_git_sha256_from_bytes(content);
        let after_hash = "bbbbbbbb".to_string();

        tokio::fs::write(dir.path().join("index.js"), content)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: before_hash.clone(),
            after_hash,
        };

        let result = verify_file_patch(dir.path(), "index.js", &file_info).await;
        assert_eq!(result.status, VerifyStatus::Ready);
        assert_eq!(result.current_hash.unwrap(), before_hash);
    }

    #[tokio::test]
    async fn test_verify_file_patch_already_patched() {
        let dir = tempfile::tempdir().unwrap();
        let content = b"patched content";
        let after_hash = compute_git_sha256_from_bytes(content);

        tokio::fs::write(dir.path().join("index.js"), content)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: "aaaa".to_string(),
            after_hash: after_hash.clone(),
        };

        let result = verify_file_patch(dir.path(), "index.js", &file_info).await;
        assert_eq!(result.status, VerifyStatus::AlreadyPatched);
    }

    #[tokio::test]
    async fn test_verify_file_patch_hash_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::write(dir.path().join("index.js"), b"something else")
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: "aaaa".to_string(),
            after_hash: "bbbb".to_string(),
        };

        let result = verify_file_patch(dir.path(), "index.js", &file_info).await;
        assert_eq!(result.status, VerifyStatus::HashMismatch);
    }

    #[tokio::test]
    async fn test_verify_with_package_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let content = b"original content";
        let before_hash = compute_git_sha256_from_bytes(content);

        // File is at lib/server.js but patch refers to package/lib/server.js
        tokio::fs::create_dir_all(dir.path().join("lib"))
            .await
            .unwrap();
        tokio::fs::write(dir.path().join("lib/server.js"), content)
            .await
            .unwrap();

        let file_info = PatchFileInfo {
            before_hash: before_hash.clone(),
            after_hash: "bbbb".to_string(),
        };

        let result = verify_file_patch(dir.path(), "package/lib/server.js", &file_info).await;
        assert_eq!(result.status, VerifyStatus::Ready);
    }

    #[tokio::test]
    async fn test_apply_file_patch_success() {
        let dir = tempfile::tempdir().unwrap();
        let original = b"original";
        let patched = b"patched content";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(dir.path().join("index.js"), original)
            .await
            .unwrap();

        apply_file_patch(dir.path(), "index.js", patched, &patched_hash)
            .await
            .unwrap();

        let written = tokio::fs::read(dir.path().join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_file_patch_hash_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::write(dir.path().join("index.js"), b"original")
            .await
            .unwrap();

        let result =
            apply_file_patch(dir.path(), "index.js", b"patched content", "wrong_hash").await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Hash verification failed"));
    }

    /// Atomic-write contract: if the apply errors mid-flight (here:
    /// in-memory hash mismatch, which fires BEFORE any disk write),
    /// the target file is byte-identical to its pre-call state AND
    /// no `.socket-stage-*` file is left in the parent directory.
    #[tokio::test]
    async fn test_apply_file_patch_hash_mismatch_leaves_original_intact() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.js");
        tokio::fs::write(&path, b"original").await.unwrap();

        let result = apply_file_patch(dir.path(), "index.js", b"patched", "deadbeef").await;
        assert!(result.is_err());

        // Original content untouched.
        assert_eq!(tokio::fs::read(&path).await.unwrap(), b"original");

        // No stage litter (stage files are named `.socket-stage-*`).
        let mut entries = tokio::fs::read_dir(dir.path()).await.unwrap();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            let name = entry.file_name().to_string_lossy().to_string();
            assert!(
                !name.starts_with(".socket-stage-"),
                "stage file leaked into parent dir: {name}"
            );
        }
    }

    /// Apply against a hardlink (the pnpm content-store case) must
    /// only mutate this project's view. The sibling link — which
    /// represents another project's `node_modules/<pkg>` or the
    /// global store entry — must keep the original bytes.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_does_not_propagate_to_hardlinked_sibling() {
        let dir = tempfile::tempdir().unwrap();
        let project = dir.path().join("project-b").join("foo.js");
        let store = dir.path().join("store-a.js");
        tokio::fs::create_dir_all(project.parent().unwrap())
            .await
            .unwrap();

        // Pre-existing store entry; both project and store point at
        // the same inode (this is what pnpm produces with
        // `package-import-method=hardlink`).
        tokio::fs::write(&store, b"original").await.unwrap();
        tokio::fs::hard_link(&store, &project).await.unwrap();

        let patched = b"patched";
        let patched_hash = compute_git_sha256_from_bytes(patched);
        apply_file_patch(project.parent().unwrap(), "foo.js", patched, &patched_hash)
            .await
            .unwrap();

        // Project sees the patched bytes.
        assert_eq!(tokio::fs::read(&project).await.unwrap(), b"patched");
        // Store entry is untouched — the headline pnpm invariant.
        assert_eq!(tokio::fs::read(&store).await.unwrap(), b"original");
    }

    /// Existing read-only file: temporarily made writable for the
    /// overwrite, restored to read-only afterward, content updated.
    /// Mirrors the Go module cache scenario.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_preserves_readonly_mode() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.js");
        let original = b"original";
        let patched = b"patched content";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(&path, original).await.unwrap();
        // 0o444 = r--r--r--. Owner has no write bit.
        tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444))
            .await
            .unwrap();

        apply_file_patch(dir.path(), "index.js", patched, &patched_hash)
            .await
            .unwrap();

        // Content updated.
        let written = tokio::fs::read(&path).await.unwrap();
        assert_eq!(written, patched);
        // Mode preserved bit-for-bit.
        let mode_after = tokio::fs::metadata(&path)
            .await
            .unwrap()
            .permissions()
            .mode()
            & 0o7777;
        assert_eq!(
            mode_after, 0o444,
            "mode must be restored to the pre-patch value after the write"
        );
    }

    /// Non-default mode (e.g. 0o755 for an executable script) survives
    /// the patch round-trip unchanged.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_preserves_executable_mode() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bin.sh");
        let original = b"#!/bin/sh\necho old\n";
        let patched = b"#!/bin/sh\necho new\n";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(&path, original).await.unwrap();
        tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))
            .await
            .unwrap();

        apply_file_patch(dir.path(), "bin.sh", patched, &patched_hash)
            .await
            .unwrap();

        let mode_after = tokio::fs::metadata(&path)
            .await
            .unwrap()
            .permissions()
            .mode()
            & 0o7777;
        assert_eq!(mode_after, 0o755);
    }

    /// New file created by the patch: default mode is read-only (0o444)
    /// and the parent directory's uid/gid get inherited (the uid/gid
    /// check is a smoke test — running as a regular user the new file
    /// would already inherit the user's uid, but the test still locks
    /// in that the new file's uid matches the parent's, which is what
    /// the chown call enforces).
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_new_file_is_readonly_and_inherits_dir_owner() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let dir = tempfile::tempdir().unwrap();
        let nested = "new-dir/new.js";
        let patched = b"brand new file content\n";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        // File does not yet exist — this is the new-file path.
        apply_file_patch(dir.path(), nested, patched, &patched_hash)
            .await
            .unwrap();

        let path = dir.path().join(nested);
        // Default new-file mode is 0o444.
        let mode = tokio::fs::metadata(&path)
            .await
            .unwrap()
            .permissions()
            .mode()
            & 0o7777;
        assert_eq!(mode, 0o444, "new files default to read-only");

        // uid/gid inherited from the parent directory.
        let parent_meta = tokio::fs::metadata(path.parent().unwrap()).await.unwrap();
        let file_meta = tokio::fs::metadata(&path).await.unwrap();
        assert_eq!(file_meta.uid(), parent_meta.uid());
        assert_eq!(file_meta.gid(), parent_meta.gid());
    }

    /// Existing patched file's uid/gid survive the round-trip. We can
    /// only verify "uid stays the same" without root, but that's
    /// enough to catch a regression that accidentally clobbered ownership.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_preserves_uid_gid() {
        use std::os::unix::fs::MetadataExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.js");
        let original = b"orig";
        let patched = b"new";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(&path, original).await.unwrap();
        let pre = tokio::fs::metadata(&path).await.unwrap();

        apply_file_patch(dir.path(), "index.js", patched, &patched_hash)
            .await
            .unwrap();

        let post = tokio::fs::metadata(&path).await.unwrap();
        assert_eq!(pre.uid(), post.uid());
        assert_eq!(pre.gid(), post.gid());
    }

    /// Read-only package directory (Go's module cache marks both files
    /// 0o444 AND directories 0o555). The stage+rename write path needs
    /// owner-write on the directory; `apply_file_patch` must grant it for
    /// the write and then restore the directory to its exact prior mode.
    /// Regression: before the `DirWriteGuard` fix the stage-file creation
    /// failed with EACCES and the patch could not be applied at all.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_in_readonly_dir() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("index.js");
        let original = b"original";
        let patched = b"patched content";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(&path, original).await.unwrap();
        // Read-only file inside a read-only directory.
        tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444))
            .await
            .unwrap();
        tokio::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555))
            .await
            .unwrap();

        apply_file_patch(dir.path(), "index.js", patched, &patched_hash)
            .await
            .expect("apply must succeed even inside a read-only directory");

        // Content updated.
        assert_eq!(tokio::fs::read(&path).await.unwrap(), patched);
        // File mode restored.
        assert_eq!(
            tokio::fs::metadata(&path)
                .await
                .unwrap()
                .permissions()
                .mode()
                & 0o7777,
            0o444
        );
        // Directory mode restored to exactly what it was (0o555).
        assert_eq!(
            tokio::fs::metadata(dir.path())
                .await
                .unwrap()
                .permissions()
                .mode()
                & 0o7777,
            0o555,
            "directory mode must be restored after the write"
        );
        // No stage litter survived in the directory.
        let mut entries = tokio::fs::read_dir(dir.path()).await.unwrap();
        while let Some(entry) = entries.next_entry().await.unwrap() {
            let name = entry.file_name().to_string_lossy().to_string();
            assert!(!name.starts_with(".socket-stage-"), "stage leaked: {name}");
        }

        // Re-grant write so the TempDir can clean itself up.
        tokio::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755))
            .await
            .unwrap();
    }

    /// A brand-new file created by a patch inside a read-only directory:
    /// the directory must be temporarily writable for the create, then
    /// restored, and the new file gets the default 0o444 mode.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_new_file_in_readonly_dir() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let patched = b"brand new\n";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555))
            .await
            .unwrap();

        apply_file_patch(dir.path(), "new.js", patched, &patched_hash)
            .await
            .expect("new-file apply must succeed inside a read-only directory");

        let path = dir.path().join("new.js");
        assert_eq!(tokio::fs::read(&path).await.unwrap(), patched);
        assert_eq!(
            tokio::fs::metadata(&path)
                .await
                .unwrap()
                .permissions()
                .mode()
                & 0o7777,
            0o444
        );
        // Directory mode restored.
        assert_eq!(
            tokio::fs::metadata(dir.path())
                .await
                .unwrap()
                .permissions()
                .mode()
                & 0o7777,
            0o555
        );

        tokio::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755))
            .await
            .unwrap();
    }

    /// setuid/setgid bits survive the patch round-trip. `chown(2)` strips
    /// these bits even when the uid/gid are unchanged, so the restore
    /// must chown BEFORE it chmods. Regression: the prior chmod-then-chown
    /// order silently dropped the setuid bit on every patched file.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_file_patch_preserves_setuid_bit() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("suid-bin");
        let patched = b"new payload";
        let patched_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(&path, b"old payload").await.unwrap();
        // setuid + rwxr-xr-x.
        tokio::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o4755))
            .await
            .unwrap();
        // Guard: skip if the filesystem refused the setuid bit (some
        // mount options strip it) so the test stays meaningful where it
        // can run and never gives a false failure where it can't.
        let pre = tokio::fs::metadata(&path)
            .await
            .unwrap()
            .permissions()
            .mode()
            & 0o7777;
        if pre != 0o4755 {
            return;
        }

        apply_file_patch(dir.path(), "suid-bin", patched, &patched_hash)
            .await
            .unwrap();

        let mode_after = tokio::fs::metadata(&path)
            .await
            .unwrap()
            .permissions()
            .mode()
            & 0o7777;
        assert_eq!(
            mode_after, 0o4755,
            "setuid bit must survive the patch (chown must run before chmod)"
        );
    }

    /// End-to-end blob apply against a fully read-only package directory.
    #[cfg(unix)]
    #[tokio::test]
    async fn test_apply_package_patch_in_readonly_dir() {
        use std::os::unix::fs::PermissionsExt;

        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let patched = b"patched content";
        let before_hash = compute_git_sha256_from_bytes(original);
        let after_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(pkg_dir.path().join("index.js"), original)
            .await
            .unwrap();
        tokio::fs::write(blobs_dir.path().join(&after_hash), patched)
            .await
            .unwrap();
        // Lock both the file and the directory down (Go cache layout).
        tokio::fs::set_permissions(
            pkg_dir.path().join("index.js"),
            std::fs::Permissions::from_mode(0o444),
        )
        .await
        .unwrap();
        tokio::fs::set_permissions(pkg_dir.path(), std::fs::Permissions::from_mode(0o555))
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash: after_hash.clone(),
            },
        );

        let result = apply_package_patch(
            "pkg:golang/example.com/x@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;

        assert!(result.success, "expected success: {:?}", result.error);
        assert_eq!(result.files_patched.len(), 1);
        let written = tokio::fs::read(pkg_dir.path().join("index.js"))
            .await
            .unwrap();
        assert_eq!(written, patched);

        tokio::fs::set_permissions(pkg_dir.path(), std::fs::Permissions::from_mode(0o755))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_apply_package_patch_success() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let patched = b"patched content";
        let before_hash = compute_git_sha256_from_bytes(original);
        let after_hash = compute_git_sha256_from_bytes(patched);

        // Write original file
        tokio::fs::write(pkg_dir.path().join("index.js"), original)
            .await
            .unwrap();

        // Write blob
        tokio::fs::write(blobs_dir.path().join(&after_hash), patched)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash: after_hash.clone(),
            },
        );

        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_patched.len(), 1);
        assert!(result.error.is_none());
    }

    #[tokio::test]
    async fn test_apply_package_patch_dry_run() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let original = b"original content";
        let before_hash = compute_git_sha256_from_bytes(original);

        tokio::fs::write(pkg_dir.path().join("index.js"), original)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash: "bbbb".to_string(),
            },
        );

        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            true,
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_patched.len(), 0); // dry run: nothing actually patched

        // File should still have original content
        let content = tokio::fs::read(pkg_dir.path().join("index.js"))
            .await
            .unwrap();
        assert_eq!(content, original);
    }

    #[tokio::test]
    async fn test_apply_package_patch_all_already_patched() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let patched = b"patched content";
        let after_hash = compute_git_sha256_from_bytes(patched);

        tokio::fs::write(pkg_dir.path().join("index.js"), patched)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash,
            },
        );

        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.files_patched.len(), 0);
    }

    #[tokio::test]
    async fn test_apply_package_patch_hash_mismatch_blocks() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        tokio::fs::write(pkg_dir.path().join("index.js"), b"something unexpected")
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: "bbbb".to_string(),
            },
        );

        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;

        assert!(!result.success);
        assert!(result.error.is_some());
    }

    #[tokio::test]
    async fn test_apply_package_patch_force_hash_mismatch() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let patched = b"patched content";
        let after_hash = compute_git_sha256_from_bytes(patched);

        // Write a file whose hash does NOT match before_hash
        tokio::fs::write(pkg_dir.path().join("index.js"), b"something unexpected")
            .await
            .unwrap();

        // Write blob
        tokio::fs::write(blobs_dir.path().join(&after_hash), patched)
            .await
            .unwrap();

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: after_hash.clone(),
            },
        );

        // Without force: should fail
        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;
        assert!(!result.success);

        // Reset the file
        tokio::fs::write(pkg_dir.path().join("index.js"), b"something unexpected")
            .await
            .unwrap();

        // With force: should succeed
        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            true,
        )
        .await;
        assert!(result.success);
        assert_eq!(result.files_patched.len(), 1);

        let written = tokio::fs::read(pkg_dir.path().join("index.js"))
            .await
            .unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_package_patch_force_not_found_skips() {
        let pkg_dir = tempfile::tempdir().unwrap();
        let blobs_dir = tempfile::tempdir().unwrap();

        let mut files = HashMap::new();
        files.insert(
            "missing.js".to_string(),
            PatchFileInfo {
                before_hash: "aaaa".to_string(),
                after_hash: "bbbb".to_string(),
            },
        );

        // Without force: should fail (NotFound for non-new file)
        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            false,
        )
        .await;
        assert!(!result.success);

        // With force: should succeed by skipping the missing file
        let result = apply_package_patch(
            "pkg:npm/test@1.0.0",
            pkg_dir.path(),
            &files,
            &PatchSources::blobs_only(blobs_dir.path()),
            None,
            false,
            true,
        )
        .await;
        assert!(result.success);
        assert_eq!(result.files_patched.len(), 0);
    }

    // ── Fallback-chain tests ─────────────────────────────────────────
    //
    // Tests below exercise the new strategies introduced in 2.2:
    // package archive (.socket/packages/<uuid>.tar.gz) and per-file diff
    // archive (.socket/diffs/<uuid>.tar.gz), plus the priority order
    // package → diff → blob.

    use flate2::write::GzEncoder;
    use flate2::Compression as GzCompression;
    use qbsdiff::Bsdiff;

    const TEST_UUID: &str = "11111111-1111-4111-8111-111111111111";

    /// Write a tar.gz archive at `<dir>/<uuid>.tar.gz` containing the
    /// given (entry name → bytes) pairs.
    fn write_uuid_archive(dir: &Path, uuid: &str, entries: &[(&str, &[u8])]) {
        let archive_path = dir.join(format!("{uuid}.tar.gz"));
        let file = std::fs::File::create(&archive_path).unwrap();
        let gz = GzEncoder::new(file, GzCompression::default());
        let mut builder = tar::Builder::new(gz);
        for (name, data) in entries {
            let mut header = tar::Header::new_gnu();
            header.set_size(data.len() as u64);
            header.set_mode(0o644);
            header.set_cksum();
            builder.append_data(&mut header, name, *data).unwrap();
        }
        builder.into_inner().unwrap().finish().unwrap();
    }

    fn make_delta(before: &[u8], after: &[u8]) -> Vec<u8> {
        let mut delta = Vec::new();
        Bsdiff::new(before, after)
            .compare(std::io::Cursor::new(&mut delta))
            .unwrap();
        delta
    }

    /// Returns a fully-populated three-source fixture: original file on
    /// disk, all of (package, diff, blob) available with valid patched
    /// content. Caller can then delete sources to test fallback.
    async fn make_fixture() -> (
        tempfile::TempDir,  // root holding pkg/, blobs/, packages/, diffs/
        std::path::PathBuf, // pkg dir
        std::path::PathBuf, // blobs dir
        std::path::PathBuf, // packages dir
        std::path::PathBuf, // diffs dir
        HashMap<String, PatchFileInfo>,
        Vec<u8>, // original bytes
        Vec<u8>, // patched bytes
    ) {
        let root = tempfile::tempdir().unwrap();
        let pkg_dir = root.path().join("pkg");
        let blobs_dir = root.path().join("blobs");
        let packages_dir = root.path().join("packages");
        let diffs_dir = root.path().join("diffs");
        tokio::fs::create_dir_all(&pkg_dir).await.unwrap();
        tokio::fs::create_dir_all(&blobs_dir).await.unwrap();
        tokio::fs::create_dir_all(&packages_dir).await.unwrap();
        tokio::fs::create_dir_all(&diffs_dir).await.unwrap();

        let original: Vec<u8> = b"the original content of the file".to_vec();
        let patched: Vec<u8> = b"the PATCHED content of the file!".to_vec();
        let before_hash = compute_git_sha256_from_bytes(&original);
        let after_hash = compute_git_sha256_from_bytes(&patched);

        // On-disk file at pkg/index.js
        tokio::fs::write(pkg_dir.join("index.js"), &original)
            .await
            .unwrap();

        // Per-file blob at blobs/<after_hash>
        tokio::fs::write(blobs_dir.join(&after_hash), &patched)
            .await
            .unwrap();

        // Package archive containing the patched bytes
        write_uuid_archive(&packages_dir, TEST_UUID, &[("index.js", &patched)]);

        // Diff archive containing bsdiff(original -> patched)
        let delta = make_delta(&original, &patched);
        write_uuid_archive(&diffs_dir, TEST_UUID, &[("index.js", &delta)]);

        let mut files = HashMap::new();
        files.insert(
            "index.js".to_string(),
            PatchFileInfo {
                before_hash,
                after_hash,
            },
        );

        (
            root,
            pkg_dir,
            blobs_dir,
            packages_dir,
            diffs_dir,
            files,
            original,
            patched,
        )
    }

    #[tokio::test]
    async fn test_apply_via_package_when_archive_present() {
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, patched) =
            make_fixture().await;

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            false,
            false,
        )
        .await;

        assert!(result.success, "expected success: {:?}", result.error);
        assert_eq!(result.files_patched, vec!["index.js".to_string()]);
        assert_eq!(
            result.applied_via.get("index.js"),
            Some(&AppliedVia::Package)
        );
        let written = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_falls_back_to_diff_when_no_package() {
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, patched) =
            make_fixture().await;
        // Delete the package archive.
        tokio::fs::remove_file(packages_dir.join(format!("{TEST_UUID}.tar.gz")))
            .await
            .unwrap();

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            false,
            false,
        )
        .await;

        assert!(result.success, "expected success: {:?}", result.error);
        assert_eq!(result.applied_via.get("index.js"), Some(&AppliedVia::Diff));
        let written = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_falls_back_to_blob_when_no_archives() {
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, patched) =
            make_fixture().await;
        // Delete both archives.
        tokio::fs::remove_file(packages_dir.join(format!("{TEST_UUID}.tar.gz")))
            .await
            .unwrap();
        tokio::fs::remove_file(diffs_dir.join(format!("{TEST_UUID}.tar.gz")))
            .await
            .unwrap();

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            false,
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.applied_via.get("index.js"), Some(&AppliedVia::Blob));
        let written = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_uuid_none_disables_alt_sources() {
        // Even if archives exist, passing `uuid = None` must restrict the
        // pipeline to the blob path — preserving pre-2.2 behavior.
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, _patched) =
            make_fixture().await;

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            None,
            false,
            false,
        )
        .await;

        assert!(result.success);
        assert_eq!(result.applied_via.get("index.js"), Some(&AppliedVia::Blob));
    }

    #[tokio::test]
    async fn test_apply_via_diff_falls_through_when_before_hash_mismatch() {
        // Corrupt the on-disk file so its hash no longer matches
        // before_hash. Diff strategy must NOT run (its output would never
        // match after_hash), so we fall through to the blob.
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, patched) =
            make_fixture().await;
        tokio::fs::remove_file(packages_dir.join(format!("{TEST_UUID}.tar.gz")))
            .await
            .unwrap();
        // Overwrite on-disk content with garbage; use --force so verify
        // promotes the HashMismatch to Ready and the pipeline still tries
        // to apply.
        tokio::fs::write(pkg_dir.join("index.js"), b"garbage")
            .await
            .unwrap();

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            false,
            true, // --force
        )
        .await;

        assert!(result.success);
        // Diff would produce wrong output → strategy skipped → blob writes.
        assert_eq!(result.applied_via.get("index.js"), Some(&AppliedVia::Blob));
        let written = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_via_package_skips_when_hash_mismatches() {
        // Package archive contains the WRONG bytes (would not hash to
        // after_hash). The package strategy must refuse the entry and
        // fall back to diff or blob.
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, _orig, patched) =
            make_fixture().await;
        // Replace the package archive with one whose entry is corrupt.
        tokio::fs::remove_file(packages_dir.join(format!("{TEST_UUID}.tar.gz")))
            .await
            .unwrap();
        write_uuid_archive(
            &packages_dir,
            TEST_UUID,
            &[("index.js", b"corrupt package payload")],
        );

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            false,
            false,
        )
        .await;

        assert!(result.success);
        // Package refused → diff succeeded next.
        assert_eq!(result.applied_via.get("index.js"), Some(&AppliedVia::Diff));
        let written = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(written, patched);
    }

    #[tokio::test]
    async fn test_apply_dry_run_does_not_touch_alternative_sources() {
        // Even with package/diff archives present, dry-run must not modify
        // files on disk.
        let (_root, pkg_dir, blobs_dir, packages_dir, diffs_dir, files, original, _patched) =
            make_fixture().await;

        let sources = PatchSources {
            blobs_path: &blobs_dir,
            packages_path: Some(&packages_dir),
            diffs_path: Some(&diffs_dir),
        };
        let result = apply_package_patch(
            "pkg:npm/x@1.0.0",
            &pkg_dir,
            &files,
            &sources,
            Some(TEST_UUID),
            true, // dry-run
            false,
        )
        .await;

        assert!(result.success);
        assert!(result.files_patched.is_empty());
        let on_disk = tokio::fs::read(pkg_dir.join("index.js")).await.unwrap();
        assert_eq!(on_disk, original);
    }

    #[test]
    fn test_applied_via_as_tag() {
        assert_eq!(AppliedVia::Package.as_tag(), "package");
        assert_eq!(AppliedVia::Diff.as_tag(), "diff");
        assert_eq!(AppliedVia::Blob.as_tag(), "blob");
    }

    #[test]
    fn test_patch_sources_blobs_only_disables_other_strategies() {
        let dir = tempfile::tempdir().unwrap();
        let sources = PatchSources::blobs_only(dir.path());
        assert!(sources.packages_path.is_none());
        assert!(sources.diffs_path.is_none());
    }
}