mise 2026.9.10

Dev tools, env vars, and tasks in one CLI
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
//! Pour a bottle: extract -> relocate -> codesign -> receipt -> link.

use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use eyre::{WrapErr, bail};
use serde_json::json;

use super::api::BottleFile;
use super::prefix;
use super::relocate;
use super::resolve::ResolvedFormula;
use crate::file::{ExtractOptions, ExtractionFormat};
use crate::result::Result;
use crate::ui::progress_report::SingleReport;

/// directories linked from a keg into the prefix (brew's Keg::KEG_LINK_DIRECTORIES,
/// minus etc/var which brew handles specially and we defer)
pub(super) const LINK_DIRS: &[&str] = &["bin", "sbin", "include", "lib", "share", "Frameworks"];
const KEG_ONLY_MARKER: &str = ".mise-keg-only";

struct RecordRepair {
    version: String,
    keg: PathBuf,
    destination: PathBuf,
}

pub(super) fn keg_path(name: &str, pkg_version: &str) -> PathBuf {
    prefix::cellar().join(name).join(pkg_version)
}

/// is this keg fully poured and linked? Every pour ends by creating the
/// `opt/<name>` symlink (even for keg-only formulae), so a Cellar directory
/// without it is a remnant of a failed install and must not block a retry.
pub(super) fn keg_installed(name: &str, pkg_version: &str) -> bool {
    keg_path(name, pkg_version).exists() && linked_version(name).as_deref() == Some(pkg_version)
}

/// the version `opt/<name>` points at, if the symlink resolves to an
/// existing keg
pub(super) fn linked_version(name: &str) -> Option<String> {
    let opt = prefix::prefix().join("opt").join(name);
    record_keg(name, &opt).map(|(version, _)| version)
}

/// Return the absolute opt path only when its symlink resolves to a keg directly inside the formula rack.
/// Preserve the configured prefix spelling and report invalid records without repairing them.
pub(super) fn strict_package_root(name: &str) -> Result<PathBuf> {
    if let Some(prefix) = std::env::var_os("MISE_SYSTEM_BREW_PREFIX")
        && prefix.to_str().is_none()
    {
        bail!("the prefix cannot be printed as a single UTF-8 path; use a compatible prefix path");
    }
    let prefix = prefix::prefix();
    let prefix = if prefix.is_absolute() {
        prefix
    } else {
        std::env::current_dir()
            .wrap_err_with(|| {
                format!(
                    "cannot resolve relative Homebrew prefix {}",
                    prefix.display()
                )
            })?
            .join(prefix)
    };
    let opt = prefix.join("opt").join(name);
    let rack = prefix.join("Cellar").join(name);
    let metadata =
        std::fs::symlink_metadata(&opt).map_err(|err| package_root_io_error(name, &opt, err))?;
    if !metadata.is_symlink() {
        bail!(
            "invalid opt record for brew:{name} at {}: expected a symbolic link; inspect it and restore the formula's correct opt link",
            opt.display()
        );
    }
    let target =
        std::fs::canonicalize(&opt).map_err(|err| package_root_io_error(name, &opt, err))?;
    let canonical_rack =
        std::fs::canonicalize(&rack).map_err(|err| package_root_io_error(name, &rack, err))?;
    let metadata =
        std::fs::metadata(&target).map_err(|err| package_root_io_error(name, &target, err))?;
    if !metadata.is_dir() || target.parent() != Some(canonical_rack.as_path()) {
        bail!(
            "invalid opt record for brew:{name} at {}: target {} must be a directory directly inside {}; inspect it and restore the formula's correct opt link",
            opt.display(),
            target.display(),
            canonical_rack.display()
        );
    }
    Ok(opt)
}

/// Retain the filesystem error while adding lookup context and actionable recovery guidance.
fn package_root_io_error(name: &str, path: &Path, err: std::io::Error) -> eyre::Report {
    let context = if err.kind() == std::io::ErrorKind::NotFound {
        format!(
            "brew:{name} has no usable installed opt link: {}; install or reconcile it with `mise bootstrap packages apply brew:{name}`",
            path.display()
        )
    } else {
        format!(
            "cannot inspect brew:{name} at {}; check access or the reported filesystem condition",
            path.display()
        )
    };
    eyre::Report::new(err).wrap_err(context)
}

/// Return the active keg version and whether one of its active records can be repaired locally.
pub(super) fn linked_state(name: &str) -> Option<(String, bool)> {
    let opt = prefix::prefix().join("opt").join(name);
    let active = record_keg(name, &opt).or_else(|| {
        record_needs_replacement(name, &opt)
            .then(|| record_keg(name, &prefix::linked_keg_record(name)))?
    })?;
    Some((active.0, pending_record_repair(name).is_some()))
}

/// Restore one missing or dangling mise-owned active-keg record without relinking the keg.
pub(super) fn repair_link_record(name: &str, dry_run: bool) -> Result<bool> {
    let Some(repair) = pending_record_repair(name) else {
        return Ok(false);
    };
    let record = if repair.destination == prefix::linked_keg_record(name) {
        "linked-keg record"
    } else {
        "opt record"
    };
    if dry_run {
        miseprintln!("repair {name}/{}: {record}", repair.version);
        return Ok(true);
    }
    crate::file::create_dir_all(repair.destination.parent().unwrap())?;
    crate::file::make_symlink(
        &relative_target(&repair.keg, &repair.destination),
        &repair.destination,
    )
    .wrap_err_with(|| {
        format!(
            "failed to repair Homebrew {record}: {}",
            repair.destination.display()
        )
    })?;
    Ok(true)
}

/// Find a single active record that can be reconstructed from its valid counterpart.
fn pending_record_repair(name: &str) -> Option<RecordRepair> {
    let opt = prefix::prefix().join("opt").join(name);
    let linked = prefix::linked_keg_record(name);
    if let Some((version, keg)) = record_keg(name, &opt) {
        if keg.join(KEG_ONLY_MARKER).is_file() {
            return None;
        }
        if record_needs_replacement(name, &linked) && has_public_link_into(&keg) {
            return Some(RecordRepair {
                version,
                keg,
                destination: linked,
            });
        }
        return None;
    }
    if record_needs_replacement(name, &opt)
        && let Some((version, keg)) = record_keg(name, &linked)
    {
        return Some(RecordRepair {
            version,
            keg,
            destination: opt,
        });
    }
    None
}

/// Resolve a record only when it targets an existing direct child of the formula rack.
fn record_keg(name: &str, record: &Path) -> Option<(String, PathBuf)> {
    let target = record_target(name, record)?.canonicalize().ok()?;
    let rack = prefix::cellar().join(name).canonicalize().ok()?;
    if target.parent()? != rack || !target.is_dir() {
        return None;
    }
    let version = target.file_name()?.to_string_lossy().to_string();
    Some((version.clone(), keg_path(name, &version)))
}

/// Resolve a record target within the formula rack without requiring the keg to exist.
fn record_target(name: &str, record: &Path) -> Option<PathBuf> {
    let target = resolved_symlink_target(record)?;
    let rack = prefix::cellar().join(name).canonicalize().ok()?;
    (target.parent()? == rack).then_some(target)
}

/// Return true only for an absent path or a dangling symlink owned by this formula rack.
fn record_needs_replacement(name: &str, path: &Path) -> bool {
    match path.symlink_metadata() {
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => true,
        Ok(metadata) if metadata.file_type().is_symlink() => {
            record_target(name, path).is_some() && record_keg(name, path).is_none()
        }
        Err(_) | Ok(_) => false,
    }
}

/// Check for the standard public-link shape created from a non-keg-only keg.
fn has_public_link_into(keg: &Path) -> bool {
    LINK_DIRS.iter().any(|dir| {
        let root = keg.join(dir);
        root.exists()
            && walkdir::WalkDir::new(root)
                .follow_links(false)
                .into_iter()
                .filter_map(|entry| entry.ok())
                .any(|entry| {
                    entry
                        .path()
                        .strip_prefix(keg)
                        .ok()
                        .map(|relative| prefix::prefix().join(relative))
                        .is_some_and(|link| symlink_points_to(&link, entry.path()))
                })
    })
}

/// Compare a symlink's one-hop target with a destination using resolved parent paths.
fn symlink_points_to(link: &Path, target: &Path) -> bool {
    resolved_symlink_target(link).as_ref() == Some(&resolved_path(target))
}

/// installed versions of this formula; the active keg (per the `opt`
/// symlink, like brew) first, the rest name-sorted
pub(super) fn installed_versions(name: &str) -> Vec<String> {
    let dir = prefix::cellar().join(name);
    let mut versions: Vec<String> = crate::file::ls(&dir)
        .unwrap_or_default()
        .into_iter()
        .filter(|p| p.is_dir())
        .filter_map(|p| {
            let name = p.file_name()?.to_string_lossy().to_string();
            (!name.starts_with(".mise-")).then_some(name)
        })
        .collect();
    versions.sort();
    let opt_target = std::fs::read_link(prefix::prefix().join("opt").join(name))
        .ok()
        .and_then(|t| t.file_name().map(|f| f.to_string_lossy().to_string()));
    if let Some(active) = opt_target
        && let Some(pos) = versions.iter().position(|v| v == &active)
    {
        versions.swap(0, pos);
    }
    versions
}

pub(super) struct PreparedBottle {
    name: String,
    pkg_version: String,
    keg: PathBuf,
    staged_keg: PathBuf,
    // Fields drop in declaration order: unlock before TempDir removes the
    // lock file so cleanup also works on Windows filesystems.
    _staging_lock: fslock::LockFile,
    staging: tempfile::TempDir,
    keg_only: bool,
}

fn create_staging_dir(
    rack: &Path,
    pkg_version: &str,
) -> Result<(tempfile::TempDir, fslock::LockFile)> {
    crate::file::create_dir_all(rack)?;
    // Serialize the short cleanup/create handshake within a formula rack. The
    // per-directory lock then protects active extraction after this lock is
    // released, including work owned by another mise process.
    let _rack_lock = crate::lock_file::LockFile::at(&rack.join(".mise-staging.lock")).lock()?;
    remove_abandoned_staging_dirs(rack)?;
    let staging = tempfile::Builder::new()
        .prefix(&format!(".mise-extract-{pkg_version}-"))
        .tempdir_in(rack)?;
    let staging_lock = crate::lock_file::LockFile::at(&staging.path().join(".mise-lock")).lock()?;
    Ok((staging, staging_lock))
}

fn remove_abandoned_staging_dirs(rack: &Path) -> Result<()> {
    for entry in rack.read_dir()? {
        let entry = entry?;
        let path = entry.path();
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        if !name.starts_with(".mise-extract-") && !name.starts_with(".mise-tmp-") {
            continue;
        }
        let metadata = match path.symlink_metadata() {
            Ok(metadata) => metadata,
            Err(err) if err.kind() == ErrorKind::NotFound => continue,
            Err(err) => return Err(err.into()),
        };
        if !metadata.is_dir() {
            continue;
        }
        // Older mise versions used lockless staging directories. They may
        // still belong to a running process, so only reclaim directories that
        // opt into this cleanup protocol with a regular lock file.
        let lock_path = path.join(".mise-lock");
        let lock_metadata = match lock_path.symlink_metadata() {
            Ok(metadata) => metadata,
            Err(err) if err.kind() == ErrorKind::NotFound => continue,
            Err(err) => return Err(err.into()),
        };
        if !lock_metadata.is_file() {
            continue;
        }
        // Open directly instead of LockFile::at(...).try_lock(), which creates
        // the parent and could resurrect a staging directory removed between
        // the metadata checks above.
        let mut lock = match fslock::LockFile::open(&lock_path) {
            Ok(lock) => lock,
            Err(err) if err.kind() == ErrorKind::NotFound => continue,
            Err(err) => return Err(err.into()),
        };
        if !lock.try_lock()? {
            continue;
        }
        // The rack lock prevents a new owner from appearing after this check.
        // Drop the file handle first so cleanup also works on Windows filesystems.
        drop(lock);
        if let Err(err) = crate::file::remove_all(&path) {
            let disappeared = err.chain().any(|cause| {
                cause
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|err| err.kind() == ErrorKind::NotFound)
            });
            if !disappeared {
                return Err(err);
            }
        }
    }
    Ok(())
}

fn commit_lock_path() -> PathBuf {
    prefix::prefix()
        .join("var/homebrew/locks")
        .join("mise-bootstrap.lock")
}

/// Serialize Cellar and shared-prefix mutations even when operation history is
/// disabled. Bottle download and preparation happen before acquiring this lock;
/// source builds hold it while writing directly into the final Cellar.
pub(super) fn commit_lock(pr: &dyn SingleReport) -> Result<fslock::LockFile> {
    crate::lock_file::LockFile::at(&commit_lock_path()).lock_with_notice(&|| {
        pr.set_message("waiting for another brew install".to_string());
    })
}

/// Extract, relocate, sign, and write the receipt into a formula-specific
/// staging directory. This does not change the active Homebrew prefix links,
/// so independent bottles can be prepared concurrently.
pub(super) fn prepare_bottle(
    rf: &ResolvedFormula,
    tag: &str,
    bottle: &BottleFile,
    tarball: &Path,
    closure: &[ResolvedFormula],
    pr: &dyn SingleReport,
) -> Result<PreparedBottle> {
    let name = &rf.formula.name;
    let pkg_version = rf.formula.pkg_version()?;
    let keg = keg_path(name, &pkg_version);
    let rack = keg.parent().unwrap().to_path_buf();
    let (staging, staging_lock) = create_staging_dir(&rack, &pkg_version)?;
    let staged_keg = staging.path().join(name).join(&pkg_version);
    let prepared = PreparedBottle {
        name: name.clone(),
        pkg_version,
        keg,
        staged_keg,
        _staging_lock: staging_lock,
        staging,
        keg_only: rf.formula.keg_only_for_target(),
    };

    // bottle tarballs contain <name>/<pkg_version>/...
    pr.set_message("extract".to_string());
    crate::file::untar(
        tarball,
        prepared.staging.path(),
        ExtractionFormat::TarGz,
        &ExtractOptions {
            strip_components: 0,
            pr: Some(pr),
            preserve_mtime: true,
        },
    )
    .wrap_err_with(|| format!("failed to extract bottle for {name}"))?;
    if !prepared.staged_keg.exists() {
        bail!(
            "unexpected bottle layout for {name}: missing {name}/{} in archive",
            prepared.pkg_version
        );
    }

    // ":any_skip_relocation" skips binary linkage relocation, but Homebrew
    // still replaces placeholders in text files. On Linux, bottles built by
    // Homebrew < 5.1.15 are incorrectly tagged and still need ELF linkage
    // relocation (brew applies the same version check in
    // extend/os/linux/bottle_specification.rb).
    let skip_linkage = bottle.cellar == ":any_skip_relocation"
        && (cfg!(target_os = "macos")
            || bottled_by_homebrew_at_least(&prepared.staged_keg, (5, 1, 15)));
    pr.set_message("relocate".to_string());
    let report = relocate::relocate_keg(&prepared.staged_keg, name, skip_linkage)?;
    // arm64 macOS kills binaries whose signature doesn't match; Linux ELF
    // files have no signatures to fix
    if cfg!(target_os = "macos") && !report.changed_machos.is_empty() {
        pr.set_message("codesign".to_string());
        relocate::codesign(&report.changed_machos)
            .wrap_err_with(|| format!("failed to re-sign relocated binaries for {name}"))?;
    }

    write_receipt(rf, tag, &prepared.staged_keg, &report, closure, true)?;
    Ok(prepared)
}

/// Commit a prepared bottle into the Cellar and update shared prefix links.
/// Callers keep this step sequential and dependency ordered.
pub(super) fn install_prepared(prepared: PreparedBottle, pr: &dyn SingleReport) -> Result<()> {
    pr.set_message("link".to_string());
    let _commit_lock = commit_lock(pr)?;
    // Another mise process may have completed the same formula while this
    // process prepared its bottle outside the commit lock.
    if keg_installed(&prepared.name, &prepared.pkg_version) {
        return Ok(());
    }
    if prepared.keg.exists() {
        crate::file::remove_all(&prepared.keg)?;
    }
    crate::file::rename(&prepared.staged_keg, &prepared.keg)?;
    // never leave a half-installed keg: if linking fails (conflicts, IO),
    // remove the keg so the next install retries from scratch
    if let Err(err) = link_keg(&prepared.name, &prepared.pkg_version, prepared.keg_only) {
        if let Err(rm_err) = crate::file::remove_all(&prepared.keg) {
            // a keg left behind here is unlinked but looks installed, so
            // future installs would skip it — make that state visible
            warn!(
                "failed to remove {} after link failure: {rm_err}\n\
                 remove it manually, then re-run `mise bootstrap packages apply`",
                prepared.keg.display()
            );
        }
        return Err(err);
    }
    Ok(())
}

/// Was this bottle built by Homebrew >= `min`? Read from the receipt the
/// bottle ships with (brew calls it the tab), before we overwrite it with our
/// own. This mirrors brew's own `parsed_homebrew_version >= "5.1.15"` check —
/// brew's version format is dotted numerics, not an arbitrary tool version.
fn bottled_by_homebrew_at_least(keg: &Path, min: (u64, u64, u64)) -> bool {
    let Ok(receipt) = crate::file::read_to_string(keg.join("INSTALL_RECEIPT.json")) else {
        return false;
    };
    let Ok(json) = serde_json::from_str::<serde_json::Value>(&receipt) else {
        return false;
    };
    let Some(version) = json.get("homebrew_version").and_then(|v| v.as_str()) else {
        return false;
    };
    // "5.1.16-31-ga1b2c3d" -> (5, 1, 16); unparseable -> (0, 0, 0) = old
    let mut parts = version
        .split(['.', '-', ' '])
        .map(|p| p.parse::<u64>().unwrap_or(0));
    let v = (
        parts.next().unwrap_or(0),
        parts.next().unwrap_or(0),
        parts.next().unwrap_or(0),
    );
    v >= min
}

/// brew-compatible INSTALL_RECEIPT.json so a later-installed real Homebrew
/// adopts these kegs (brew list/upgrade/uninstall all work). Written for
/// both poured bottles and source-built kegs; `poured_from_bottle`
/// distinguishes them the same way brew's own tab does.
pub(super) fn write_receipt(
    rf: &ResolvedFormula,
    tag: &str,
    keg: &Path,
    report: &relocate::RelocationReport,
    closure: &[ResolvedFormula],
    poured_from_bottle: bool,
) -> Result<()> {
    let runtime_dependencies: Vec<serde_json::Value> = closure
        .iter()
        .filter(|other| {
            rf.formula
                .dependencies_for(tag)
                .iter()
                .any(|d| d == &other.formula.name || other.formula.aliases.contains(d))
        })
        .filter_map(|dep| {
            let pkg_version = dep.formula.pkg_version().ok()?;
            Some(json!({
                "full_name": dep.formula.name,
                "version": dep.formula.versions.stable,
                "revision": dep.formula.revision,
                "pkg_version": pkg_version,
                "declared_directly": true,
            }))
        })
        .collect();
    let changed_files: Vec<String> = report
        .changed_files
        .iter()
        .filter_map(|p| p.strip_prefix(keg).ok())
        .map(|p| p.to_string_lossy().to_string())
        .collect();
    let receipt = json!({
        // must stay >= 5.1.15: bottled_by_homebrew_at_least gates Linux ELF
        // relocation on the receipt's homebrew_version, and a poured keg's
        // linkage is already final
        "homebrew_version": "5.1.15 (mise)",
        "used_options": [],
        "unused_options": [],
        "built_as_bottle": poured_from_bottle,
        "poured_from_bottle": poured_from_bottle,
        "loaded_from_api": true,
        "installed_as_dependency": !rf.on_request,
        "installed_on_request": rf.on_request,
        "changed_files": changed_files,
        "time": std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0),
        "source_modified_time": 0,
        "compiler": "clang",
        "aliases": rf.formula.aliases,
        "runtime_dependencies": runtime_dependencies,
        "source": {
            "spec": "stable",
            "versions": {
                "stable": rf.formula.versions.stable,
                "head": null,
                "version_scheme": 0,
            },
            "path": null,
            "tap": rf.formula.tap.as_deref().unwrap_or("homebrew/core"),
            "tap_git_head": null,
        },
        "arch": if cfg!(target_arch = "aarch64") { "arm64" } else { "x86_64" },
        "built_on": {},
    });
    crate::file::write(
        keg.join("INSTALL_RECEIPT.json"),
        serde_json::to_string(&receipt)?,
    )?;
    Ok(())
}

/// relative symlink target from `link` to `dest`
fn relative_target(dest: &Path, link: &Path) -> PathBuf {
    let link_dir = link.parent().unwrap();
    let mut common = 0;
    let dest_parts: Vec<_> = dest.components().collect();
    let link_parts: Vec<_> = link_dir.components().collect();
    while common < dest_parts.len()
        && common < link_parts.len()
        && dest_parts[common] == link_parts[common]
    {
        common += 1;
    }
    let mut out = PathBuf::new();
    for _ in common..link_parts.len() {
        out.push("..");
    }
    for part in &dest_parts[common..] {
        out.push(part);
    }
    out
}

/// May we overwrite `dest`? Only if it's a symlink pointing into our Cellar
/// or opt (i.e. something brew/mise created and can re-create), or anything
/// underneath a directory symlink brew created — brew links a directory it
/// owns entirely as a single symlink, so the regular files and the keg's own
/// symlinks inside are still brew's.
fn can_overwrite(dest: &Path) -> bool {
    let Ok(meta) = dest.symlink_metadata() else {
        return true; // doesn't exist
    };
    if brew_owned_ancestor(dest).is_some() {
        return true;
    }
    if !meta.is_symlink() {
        return false;
    }
    points_into_cellar(dest)
}

/// Does this symlink point into our Cellar or opt? Resolve the link itself once,
/// then canonicalize its parent so nested relative links retain their final
/// component while using the Cellar's filesystem spelling.
fn points_into_cellar(link: &Path) -> bool {
    let Some(target) = resolved_symlink_target(link) else {
        return false;
    };
    let cellar = prefix::cellar()
        .canonicalize()
        .unwrap_or_else(|_| prefix::cellar());
    let opt = prefix::prefix()
        .join("opt")
        .canonicalize()
        .unwrap_or_else(|_| prefix::prefix().join("opt"));
    target.starts_with(cellar) || target.starts_with(opt)
}

/// Resolve one symlink hop relative to its parent without chasing the final component.
fn resolved_symlink_target(link: &Path) -> Option<PathBuf> {
    let target = std::fs::read_link(link).ok()?;
    let target = if target.is_absolute() {
        target
    } else {
        link.parent()?.join(target)
    };
    Some(resolved_path(&target))
}

/// Canonicalize the parent of a lexically normalized path while preserving its final component.
fn resolved_path(path: &Path) -> PathBuf {
    let target = lexical_normalize(path);
    match (target.parent(), target.file_name()) {
        (Some(parent), Some(name)) => parent
            .canonicalize()
            .unwrap_or_else(|_| parent.to_path_buf())
            .join(name),
        _ => target,
    }
}

/// Normalize `.` and `..` components without touching the filesystem.
pub(super) fn lexical_normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// The outermost ancestor of `dest` (strictly below the prefix) that is a
/// symlink pointing into the Cellar — i.e. a directory brew linked wholesale.
fn brew_owned_ancestor(dest: &Path) -> Option<PathBuf> {
    let prefix_path = prefix::prefix();
    let mut ancestors: Vec<&Path> = dest
        .ancestors()
        .skip(1)
        .take_while(|p| *p != prefix_path && p.starts_with(&prefix_path))
        .collect();
    ancestors.reverse(); // outermost first
    for anc in ancestors {
        if anc
            .symlink_metadata()
            .map(|m| m.is_symlink())
            .unwrap_or(false)
        {
            return points_into_cellar(anc).then(|| anc.to_path_buf());
        }
    }
    None
}

/// Replace brew-created directory symlinks on the way to `dest` with real
/// directories of symlinks to their old contents — the same expansion brew
/// performs when another keg needs to place files inside a wholesale-linked
/// directory (resolve_any_conflicts). The replacement is fully staged before
/// the symlink is swapped out, so a failure leaves the tree unchanged.
fn materialize_brew_dirs(dest: &Path) -> Result<()> {
    while let Some(link_dir) = brew_owned_ancestor(dest) {
        let raw_target = std::fs::read_link(&link_dir)?;
        let staging = link_dir.parent().unwrap().join(format!(
            ".mise-materialize-{}",
            link_dir.file_name().unwrap().to_string_lossy()
        ));
        let staged = (|| -> Result<()> {
            if staging.exists() {
                crate::file::remove_all(&staging)?;
            }
            crate::file::create_dir_all(&staging)?;
            // a dangling dir symlink (keg already pruned) has nothing to preserve
            let target = lexical_normalize(&link_dir.parent().unwrap().join(&raw_target));
            if target.is_dir() {
                for entry in std::fs::read_dir(&target)? {
                    let entry = entry?;
                    // targets are relative to the link's final location
                    let child_link = link_dir.join(entry.file_name());
                    crate::file::make_symlink(
                        &relative_target(&entry.path(), &child_link),
                        &staging.join(entry.file_name()),
                    )?;
                }
            }
            Ok(())
        })();
        if let Err(err) = staged {
            let _ = crate::file::remove_all(&staging);
            return Err(err);
        }
        // swap: a directory cannot be renamed over a symlink, so remove the
        // link first; if the rename then fails, put the symlink back
        if let Err(err) = crate::file::remove_file(&link_dir) {
            let _ = crate::file::remove_all(&staging);
            return Err(err);
        }
        if let Err(err) = crate::file::rename(&staging, &link_dir) {
            let _ = crate::file::make_symlink(&raw_target, &link_dir);
            let _ = crate::file::remove_all(&staging);
            return Err(err);
        }
    }
    Ok(())
}

/// Create the opt symlink and (unless keg-only) link the keg's public dirs
/// into the prefix. Conflicts are detected before anything is touched, and a
/// failure partway through removes the links already created — the caller
/// rolls the keg back on error, and nothing may be left dangling into it.
pub(super) fn link_keg(name: &str, pkg_version: &str, keg_only: bool) -> Result<()> {
    let prefix_path = prefix::prefix();
    let keg = keg_path(name, pkg_version);
    if keg_only {
        crate::file::write(keg.join(KEG_ONLY_MARKER), "")?;
    }
    // <prefix>/opt/<name> -> ../Cellar/<name>/<version> (always, even keg-only)
    let opt_link = prefix_path.join("opt").join(name);

    let mut conflicts: Vec<PathBuf> = vec![];
    let mut links: Vec<(PathBuf, PathBuf)> = vec![];
    if keg_only {
        debug!(
            "{name} is keg-only, not linking into {}",
            prefix_path.display()
        );
    } else {
        for dir in LINK_DIRS {
            let src_root = keg.join(dir);
            if !src_root.exists() {
                continue;
            }
            for entry in walkdir::WalkDir::new(&src_root).follow_links(false) {
                let entry = entry?;
                if entry.file_type().is_dir() {
                    continue;
                }
                let rel = entry.path().strip_prefix(&keg)?;
                let dest = prefix_path.join(rel);
                if !can_overwrite(&dest) {
                    conflicts.push(dest);
                } else {
                    links.push((dest, entry.path().to_path_buf()));
                }
            }
        }
        let linked = prefix::linked_keg_record(name);
        if can_overwrite(&linked) {
            links.push((linked, keg.clone()));
        } else {
            conflicts.push(linked);
        }
    }
    if can_overwrite(&opt_link) {
        // Create opt last: keg_installed uses it as the completion marker, so a
        // process killed during public linking cannot make a partial pour look
        // complete to another process waiting on the commit lock.
        links.push((opt_link.clone(), keg.clone()));
    } else {
        conflicts.push(opt_link);
    }
    if !conflicts.is_empty() {
        // nothing has been linked yet, and the caller rolls the keg back on
        // this error — so don't claim it remains usable
        bail!(
            "cannot link {name}: these files already exist and were not created by mise or brew:\n{}\n\
             Remove or rename them, then re-run `mise bootstrap packages apply`",
            conflicts
                .iter()
                .map(|p| format!("  {}", p.display()))
                .collect::<Vec<_>>()
                .join("\n"),
        );
    }
    // remember every symlink we overwrite (upgrades replace the previous
    // version's links, opt included) so a failed link restores all of them
    let mut created: Vec<PathBuf> = vec![];
    let mut replaced: Vec<(PathBuf, PathBuf)> = vec![];
    let mut failure: Option<eyre::Report> = None;
    for (dest, target) in &links {
        let made = (|| -> Result<()> {
            // a parent that is a brew directory symlink must become a real
            // directory first — otherwise the link below would be created
            // inside (and delete files from) the old keg it points to
            materialize_brew_dirs(dest)?;
            crate::file::create_dir_all(dest.parent().unwrap())?;
            if dest.symlink_metadata().is_ok() {
                if let Ok(prev) = std::fs::read_link(dest) {
                    replaced.push((dest.clone(), prev));
                }
                crate::file::remove_file(dest)?;
            }
            crate::file::make_symlink(&relative_target(target, dest), dest)?;
            Ok(())
        })();
        if let Err(err) = made {
            failure = Some(err);
            break;
        }
        created.push(dest.clone());
    }
    if let Some(err) = failure {
        for dest in created {
            let _ = crate::file::remove_file(&dest);
        }
        for (dest, prev) in replaced {
            let _ = crate::file::make_symlink(&prev, &dest);
        }
        return Err(err);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::system::packages::brew::package_root;
    use std::os::unix::fs::{PermissionsExt, symlink};
    use tokio::sync::Mutex;

    static ENV_LOCK: Mutex<()> = Mutex::const_new(());

    struct BrewPrefixGuard {
        previous: Option<String>,
    }

    impl BrewPrefixGuard {
        fn set(prefix: &Path) -> Self {
            let previous = crate::env::var("MISE_SYSTEM_BREW_PREFIX").ok();
            crate::env::set_var("MISE_SYSTEM_BREW_PREFIX", prefix);
            Self { previous }
        }
    }

    impl Drop for BrewPrefixGuard {
        fn drop(&mut self) {
            match &self.previous {
                Some(previous) => crate::env::set_var("MISE_SYSTEM_BREW_PREFIX", previous),
                None => crate::env::remove_var("MISE_SYSTEM_BREW_PREFIX"),
            }
        }
    }

    #[test]
    fn removes_abandoned_locking_staging_directories() {
        let rack = tempfile::tempdir().unwrap();
        let extract = rack.path().join(".mise-extract-1.0-abandoned");
        crate::file::create_dir_all(&extract).unwrap();
        drop(
            crate::lock_file::LockFile::at(&extract.join(".mise-lock"))
                .lock()
                .unwrap(),
        );

        remove_abandoned_staging_dirs(rack.path()).unwrap();

        assert!(!extract.exists());
    }

    #[test]
    fn preserves_legacy_lockless_staging_directories() {
        let rack = tempfile::tempdir().unwrap();
        let extract = rack.path().join(".mise-extract-1.0-legacy");
        let legacy_tmp = rack.path().join(".mise-tmp-1.0");
        crate::file::create_dir_all(&extract).unwrap();
        crate::file::create_dir_all(&legacy_tmp).unwrap();

        remove_abandoned_staging_dirs(rack.path()).unwrap();

        assert!(extract.exists());
        assert!(legacy_tmp.exists());
    }

    #[test]
    fn preserves_locked_staging_until_its_owner_finishes() {
        let rack = tempfile::tempdir().unwrap();
        let active = rack.path().join(".mise-extract-1.0-active");
        crate::file::create_dir_all(&active).unwrap();
        let held = crate::lock_file::LockFile::at(&active.join(".mise-lock"))
            .lock()
            .unwrap();

        remove_abandoned_staging_dirs(rack.path()).unwrap();
        assert!(active.exists());

        drop(held);
        remove_abandoned_staging_dirs(rack.path()).unwrap();
        assert!(!active.exists());
    }

    /// keg with a versioned dylib and its unversioned alias (the relative
    /// symlink chain every brew library bottle ships), plus a header dir
    fn write_lib_keg(prefix: &Path, name: &str, version: &str) -> Result<PathBuf> {
        let keg = prefix.join("Cellar").join(name).join(version);
        crate::file::create_dir_all(keg.join("lib"))?;
        crate::file::write(keg.join("lib").join(format!("lib{name}.1.dylib")), version)?;
        crate::file::make_symlink(
            Path::new(&format!("lib{name}.1.dylib")),
            &keg.join("lib").join(format!("lib{name}.dylib")),
        )?;
        crate::file::create_dir_all(keg.join("include").join(name))?;
        crate::file::write(keg.join("include").join(name).join("header.h"), version)?;
        // keg-internal relative symlink inside the dir brew links wholesale
        crate::file::make_symlink(
            Path::new("header.h"),
            &keg.join("include").join(name).join("alias.h"),
        )?;
        Ok(keg)
    }

    /// link a keg the way real brew does: file symlinks for files whose
    /// parent dir is shared, one directory symlink for a dir the keg owns
    fn brew_style_link(prefix: &Path, name: &str, version: &str) -> Result<()> {
        let cellar_rel = Path::new("../Cellar").join(name).join(version);
        crate::file::create_dir_all(prefix.join("opt"))?;
        crate::file::make_symlink(
            &Path::new("../Cellar").join(name).join(version),
            &prefix.join("opt").join(name),
        )?;
        crate::file::create_dir_all(prefix.join("lib"))?;
        for lib in [format!("lib{name}.dylib"), format!("lib{name}.1.dylib")] {
            crate::file::make_symlink(
                &cellar_rel.join("lib").join(&lib),
                &prefix.join("lib").join(&lib),
            )?;
        }
        crate::file::create_dir_all(prefix.join("include"))?;
        crate::file::make_symlink(
            &cellar_rel.join("include").join(name),
            &prefix.join("include").join(name),
        )?;
        Ok(())
    }

    fn canonical_tempdir() -> Result<(tempfile::TempDir, PathBuf)> {
        let tmp = tempfile::tempdir()?;
        let path = tmp.path().canonicalize()?;
        Ok((tmp, path))
    }

    /// the unversioned dylib alias resolves through a relative symlink chain
    /// inside the Cellar and must still be recognized as brew's
    #[test]
    fn test_upgrade_over_brew_file_links() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        brew_style_link(&prefix, "foo", "1.0")?;
        write_lib_keg(&prefix, "foo", "2.0")?;

        link_keg("foo", "2.0", false)?;

        let lib_link = prefix.join("lib").join("libfoo.dylib");
        assert!(lib_link.symlink_metadata()?.is_symlink());
        assert_eq!(std::fs::read_to_string(&lib_link)?, "2.0");
        Ok(())
    }

    /// everything under a brew directory-level symlink is brew's and must
    /// relink without conflicts or modifying the old keg
    #[test]
    fn test_upgrade_over_brew_dir_symlink() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let old_keg = write_lib_keg(&prefix, "foo", "1.0")?;
        brew_style_link(&prefix, "foo", "1.0")?;
        write_lib_keg(&prefix, "foo", "2.0")?;

        link_keg("foo", "2.0", false)?;

        let header = prefix.join("include").join("foo").join("header.h");
        assert_eq!(std::fs::read_to_string(&header)?, "2.0");
        // a keg-internal relative symlink under the dir symlink is brew's too
        assert_eq!(
            std::fs::read_to_string(prefix.join("include").join("foo").join("alias.h"))?,
            "2.0"
        );
        // the old keg's own files survive untouched
        assert_eq!(
            std::fs::read_to_string(old_keg.join("include").join("foo").join("header.h"))?,
            "1.0"
        );
        Ok(())
    }

    /// a link into the Cellar whose target continues outside it (bottles
    /// ship symlinks to system libraries) is still brew's own link
    #[test]
    fn test_upgrade_over_link_whose_cellar_target_leaves_the_cellar() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        for version in ["1.0", "2.0"] {
            let keg = prefix.join("Cellar").join("foo").join(version);
            crate::file::create_dir_all(keg.join("lib"))?;
            crate::file::make_symlink(
                Path::new("/usr/lib/libSystem.B.dylib"),
                &keg.join("lib").join("libsys.dylib"),
            )?;
        }
        crate::file::create_dir_all(prefix.join("opt"))?;
        crate::file::make_symlink(
            Path::new("../Cellar/foo/1.0"),
            &prefix.join("opt").join("foo"),
        )?;
        crate::file::create_dir_all(prefix.join("lib"))?;
        crate::file::make_symlink(
            Path::new("../Cellar/foo/1.0/lib/libsys.dylib"),
            &prefix.join("lib").join("libsys.dylib"),
        )?;

        link_keg("foo", "2.0", false)?;

        assert_eq!(
            std::fs::read_link(prefix.join("lib").join("libsys.dylib"))?,
            PathBuf::from("../Cellar/foo/2.0/lib/libsys.dylib")
        );
        Ok(())
    }

    /// a regular file that is NOT under a brew directory symlink is foreign
    /// and must still be reported as a conflict
    #[test]
    fn test_foreign_regular_file_still_conflicts() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "2.0")?;
        crate::file::create_dir_all(prefix.join("include").join("foo"))?;
        crate::file::write(prefix.join("include").join("foo").join("header.h"), "mine")?;

        let err = link_keg("foo", "2.0", false).unwrap_err();
        assert!(err.to_string().contains("not created by mise or brew"));
        assert_eq!(
            std::fs::read_to_string(prefix.join("include").join("foo").join("header.h"))?,
            "mine"
        );
        Ok(())
    }

    /// a shared dir linked wholesale to another keg is expanded into a real
    /// directory keeping that keg's entries visible, like brew does
    #[test]
    fn test_materialize_shared_dir_owned_by_other_keg() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        // other keg owns share/xml via a dir symlink
        let other = prefix.join("Cellar").join("other").join("1.0");
        crate::file::create_dir_all(other.join("share").join("xml"))?;
        crate::file::write(other.join("share").join("xml").join("other.dtd"), "other")?;
        crate::file::create_dir_all(prefix.join("share"))?;
        crate::file::make_symlink(
            Path::new("../Cellar/other/1.0/share/xml"),
            &prefix.join("share").join("xml"),
        )?;
        // new keg wants a file inside share/xml
        let keg = prefix.join("Cellar").join("foo").join("2.0");
        crate::file::create_dir_all(keg.join("share").join("xml"))?;
        crate::file::write(keg.join("share").join("xml").join("foo.dtd"), "foo")?;

        link_keg("foo", "2.0", false)?;

        let xml = prefix.join("share").join("xml");
        assert!(!xml.symlink_metadata()?.is_symlink());
        assert_eq!(std::fs::read_to_string(xml.join("other.dtd"))?, "other");
        assert_eq!(std::fs::read_to_string(xml.join("foo.dtd"))?, "foo");
        // the other keg must not have been polluted
        assert!(!other.join("share").join("xml").join("foo.dtd").exists());
        Ok(())
    }

    #[test]
    fn test_nested_relative_link_is_brew_owned() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = prefix.join("Cellar/foo/1.0/lib");
        crate::file::create_dir_all(&keg)?;
        crate::file::write(keg.join("libfoo.1.dylib"), "")?;
        let lib = prefix.join("lib");
        crate::file::create_dir_all(&lib)?;
        crate::file::make_symlink(Path::new("../Cellar/foo/1.0/lib"), &lib.join("foo"))?;
        let nested = lib.join("libfoo.dylib");
        crate::file::make_symlink(Path::new("foo/libfoo.1.dylib"), &nested)?;

        assert!(can_overwrite(&nested));
        Ok(())
    }

    #[test]
    fn test_link_keg_maintains_homebrew_linked_record() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        link_keg("foo", "1.0", false)?;
        let linked = prefix::linked_keg_record("foo");
        assert_eq!(
            std::fs::read_link(&linked)?,
            PathBuf::from("../../../Cellar/foo/1.0")
        );

        write_lib_keg(&prefix, "foo", "2.0")?;
        link_keg("foo", "2.0", false)?;
        assert_eq!(
            std::fs::read_link(&linked)?,
            PathBuf::from("../../../Cellar/foo/2.0")
        );

        let bar_keg = write_lib_keg(&prefix, "bar", "1.0")?;
        link_keg("bar", "1.0", true)?;
        assert!(prefix.join("opt/bar").is_symlink());
        assert!(prefix::linked_keg_record("bar").symlink_metadata().is_err());
        assert_eq!(linked_state("bar"), Some(("1.0".to_string(), false)));
        crate::file::make_symlink(
            &bar_keg.join("lib/libbar.1.dylib"),
            &prefix.join("lib/libbar.1.dylib"),
        )?;
        assert!(!repair_link_record("bar", false)?);
        assert!(prefix::linked_keg_record("bar").symlink_metadata().is_err());

        let linked = prefix::linked_keg_record("bar");
        crate::file::create_dir_all(linked.parent().unwrap())?;
        crate::file::make_symlink(Path::new("../../../Cellar/bar/1.0"), &linked)?;
        std::fs::remove_file(prefix.join("opt/bar"))?;
        assert_eq!(linked_state("bar"), Some(("1.0".to_string(), true)));
        assert!(repair_link_record("bar", false)?);
        assert_eq!(
            std::fs::read_link(prefix.join("opt/bar"))?,
            PathBuf::from("../Cellar/bar/1.0")
        );
        Ok(())
    }

    #[test]
    fn test_repairs_active_records_without_relinking_the_keg() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        brew_style_link(&prefix, "foo", "1.0")?;
        let public = prefix.join("lib/libfoo.dylib");
        let public_target = std::fs::read_link(&public)?;

        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), true)));
        assert!(repair_link_record("foo", false)?);
        assert_eq!(std::fs::read_link(&public)?, public_target);
        assert_eq!(
            std::fs::read_link(prefix::linked_keg_record("foo"))?,
            PathBuf::from("../../../Cellar/foo/1.0")
        );

        crate::file::remove_file(prefix.join("opt/foo"))?;
        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), true)));
        assert!(repair_link_record("foo", false)?);
        assert_eq!(
            std::fs::read_link(prefix.join("opt/foo"))?,
            PathBuf::from("../Cellar/foo/1.0")
        );
        assert_eq!(std::fs::read_link(&public)?, public_target);
        Ok(())
    }

    #[test]
    fn test_repairs_dangling_owned_records_but_not_foreign_records() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        brew_style_link(&prefix, "foo", "1.0")?;
        let linked = prefix::linked_keg_record("foo");
        crate::file::create_dir_all(linked.parent().unwrap())?;
        crate::file::make_symlink(Path::new("../../../Cellar/foo/0.9"), &linked)?;

        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), true)));
        assert!(repair_link_record("foo", false)?);
        assert_eq!(
            std::fs::read_link(&linked)?,
            PathBuf::from("../../../Cellar/foo/1.0")
        );

        let opt = prefix.join("opt/foo");
        crate::file::make_symlink(Path::new("../Cellar/foo/0.9"), &opt)?;
        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), true)));
        assert!(repair_link_record("foo", false)?);
        assert_eq!(
            std::fs::read_link(&opt)?,
            PathBuf::from("../Cellar/foo/1.0")
        );

        crate::file::make_symlink(Path::new("/custom/missing-foo"), &linked)?;
        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), false)));
        assert!(!repair_link_record("foo", false)?);
        assert_eq!(
            std::fs::read_link(&linked)?,
            PathBuf::from("/custom/missing-foo")
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_manager_repairs_linked_record_without_repouring() -> Result<()> {
        use std::os::unix::fs::MetadataExt;

        use crate::system::packages::{
            InstallOpts, PackageRequest, PackageState, SystemPackageManager,
        };

        let _lock = ENV_LOCK.lock().await;
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = write_lib_keg(&prefix, "foo", "1.0")?;
        crate::file::write(keg.join("INSTALL_RECEIPT.json"), "{}")?;
        brew_style_link(&prefix, "foo", "1.0")?;
        let public = prefix.join("lib/libfoo.dylib");
        let request = PackageRequest {
            name: "foo".to_string(),
            version: None,
            tap_url: None,
            desired: crate::system::packages::PackageDesiredState::Present,
        };
        let keg_inode = keg.metadata()?.ino();
        let receipt_modified = keg.join("INSTALL_RECEIPT.json").metadata()?.modified()?;
        let public_inode = public.symlink_metadata()?.ino();

        let manager = super::super::BrewManager::new();
        let mismatched = PackageRequest {
            version: Some("2.0".to_string()),
            ..request.clone()
        };
        let err = manager
            .install(std::slice::from_ref(&mismatched), &InstallOpts::default())
            .await
            .unwrap_err();
        assert!(err.to_string().contains("pin via the formula name"));
        assert!(prefix::linked_keg_record("foo").symlink_metadata().is_err());

        let status = manager.installed(std::slice::from_ref(&request)).await?;
        assert_eq!(
            status[0].state,
            PackageState::NeedsRepair {
                installed: "1.0".to_string()
            }
        );

        manager
            .install(std::slice::from_ref(&request), &InstallOpts::default())
            .await?;

        assert_eq!(keg.metadata()?.ino(), keg_inode);
        assert_eq!(
            keg.join("INSTALL_RECEIPT.json").metadata()?.modified()?,
            receipt_modified
        );
        assert_eq!(public.symlink_metadata()?.ino(), public_inode);
        assert_eq!(
            std::fs::read_link(prefix::linked_keg_record("foo"))?,
            PathBuf::from("../../../Cellar/foo/1.0")
        );
        assert_eq!(
            manager.installed(std::slice::from_ref(&request)).await?[0].state,
            PackageState::Installed {
                version: "1.0".to_string()
            }
        );
        Ok(())
    }

    #[test]
    fn test_does_not_infer_a_linked_record_without_public_links() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        crate::file::create_dir_all(prefix.join("opt"))?;
        crate::file::make_symlink(Path::new("../Cellar/foo/1.0"), &prefix.join("opt/foo"))?;

        assert_eq!(linked_state("foo"), Some(("1.0".to_string(), false)));
        assert!(!repair_link_record("foo", false)?);
        assert!(prefix::linked_keg_record("foo").symlink_metadata().is_err());
        Ok(())
    }

    #[test]
    fn test_runtime_loader_does_not_make_glibc_look_linked() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = prefix.join("Cellar/glibc/1.0");
        crate::file::create_dir_all(keg.join("lib"))?;
        crate::file::write(keg.join("lib/ld-linux-x86-64.so.2"), "")?;
        crate::file::create_dir_all(prefix.join("opt"))?;
        crate::file::make_symlink(Path::new("../Cellar/glibc/1.0"), &prefix.join("opt/glibc"))?;
        crate::file::create_dir_all(prefix.join("lib"))?;
        crate::file::make_symlink(
            &keg.join("lib/ld-linux-x86-64.so.2"),
            &prefix.join("lib/ld.so"),
        )?;

        assert_eq!(linked_state("glibc"), Some(("1.0".to_string(), false)));
        assert!(!repair_link_record("glibc", false)?);
        assert!(
            prefix::linked_keg_record("glibc")
                .symlink_metadata()
                .is_err()
        );
        Ok(())
    }

    #[test]
    fn test_foreign_linked_record_blocks_linking_before_changes() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        let linked = prefix::linked_keg_record("foo");
        crate::file::create_dir_all(linked.parent().unwrap())?;
        crate::file::write(&linked, "foreign")?;

        let err = link_keg("foo", "1.0", false).unwrap_err();

        assert!(err.to_string().contains("not created by mise or brew"));
        assert_eq!(crate::file::read_to_string(&linked)?, "foreign");
        assert!(prefix.join("opt/foo").symlink_metadata().is_err());
        Ok(())
    }

    #[test]
    fn test_foreign_opt_file_blocks_linking_before_changes() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        write_lib_keg(&prefix, "foo", "1.0")?;
        let opt = prefix.join("opt/foo");
        crate::file::create_dir_all(opt.parent().unwrap())?;
        crate::file::write(&opt, "foreign")?;

        let err = link_keg("foo", "1.0", false).unwrap_err();

        assert!(err.to_string().contains("not created by mise or brew"));
        assert_eq!(crate::file::read_to_string(&opt)?, "foreign");
        assert!(prefix.join("lib/libfoo.dylib").symlink_metadata().is_err());
        Ok(())
    }

    #[test]
    fn test_relative_target() {
        assert_eq!(
            relative_target(
                Path::new("/opt/homebrew/Cellar/jq/1.7/bin/jq"),
                Path::new("/opt/homebrew/bin/jq"),
            ),
            PathBuf::from("../Cellar/jq/1.7/bin/jq")
        );
        assert_eq!(
            relative_target(
                Path::new("/opt/homebrew/Cellar/jq/1.7"),
                Path::new("/opt/homebrew/opt/jq"),
            ),
            PathBuf::from("../Cellar/jq/1.7")
        );
    }

    /// Create the minimal rack layout needed to test lookup independently of installation metadata.
    fn query_keg(prefix: &Path, name: &str, version: &str) -> Result<PathBuf> {
        let keg = prefix.join("Cellar").join(name).join(version);
        std::fs::create_dir_all(&keg)?;
        std::fs::create_dir_all(prefix.join("opt"))?;
        Ok(keg)
    }

    /// Require stable absolute opt output and verify that it resolves to the expected keg.
    fn assert_query_target(name: &str, opt: &Path, keg: &Path) -> Result<()> {
        let root = package_root(name)?;
        assert_eq!(root, opt);
        assert!(root.is_absolute());
        assert_eq!(root.canonicalize()?, keg.canonicalize()?);
        Ok(())
    }

    #[test]
    /// Treat version suffixes literally and qualified requests as names for the same local rack.
    fn package_root_normalizes_plain_versioned_and_qualified_names() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        for name in ["widget", "openssl@3", "widget@latest", "widget@1.2"] {
            let keg = query_keg(&prefix, name, "opaque-active")?;
            let opt = prefix.join("opt").join(name);
            symlink(&keg, &opt)?;
            for request in [
                name.to_string(),
                format!("homebrew/core/{name}"),
                format!("owner/tap/{name}"),
                format!("another/tap/{name}"),
            ] {
                assert_query_target(&request, &opt, &keg)?;
            }
        }
        Ok(())
    }

    #[test]
    /// Validate names before touching the prefix so malformed requests receive identifier diagnostics.
    fn package_root_rejects_invalid_identifiers_before_filesystem_lookup() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix.join("missing-prefix"));
        for name in [
            "",
            ".",
            "..",
            "/widget",
            "../widget",
            "owner/widget",
            "a/b/c/d",
            "a//widget",
            "a/b/widget/",
            "a/./widget",
            "../b/widget",
            "a/../widget",
            "a/b/..",
            "a/b/.",
            "widget:name",
            "a:b/c/widget",
            "a/b/widget:name",
            "widget\\name",
            "a\\b/c/widget",
            " widget",
            "wid get",
            "a/ b/widget",
            "widget\n",
            "widget\r",
            "wid\tget",
            "a/b/wid\0get",
            "a/b/wid\u{7f}get",
            "wid\u{a0}get",
        ] {
            let error = format!("{:#}", package_root(name).unwrap_err());
            assert!(error.contains("brew:"), "{name:?}: {error}");
            assert!(!error.contains("missing-prefix"), "{name:?}: {error}");
        }
        Ok(())
    }

    #[test]
    /// Keep cask requests separate even when a same-named formula is installed.
    fn package_root_rejects_the_cask_namespace() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        symlink(keg, prefix.join("opt/widget"))?;
        let error = format!("{:#}", package_root("homebrew/cask/widget").unwrap_err());
        assert!(error.contains("cask"), "{error}");
        Ok(())
    }

    #[test]
    /// Allow minimal keg-only installations whose only active record is a relative opt symlink.
    fn package_root_accepts_relative_opt_without_receipts_or_public_links() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        let opt = prefix.join("opt/widget");
        symlink("../Cellar/widget/active", &opt)?;
        assert_query_target("widget", &opt, &keg)?;
        assert!(!prefix.join("bin").exists());
        assert!(!prefix.join("var/homebrew/linked/widget").exists());
        assert_eq!(std::fs::read_dir(keg)?.count(), 0);
        Ok(())
    }

    #[test]
    /// Use the active opt target instead of version ordering, leaving both keg payloads unchanged.
    fn package_root_follows_only_the_active_opaque_version_and_preserves_records() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let old = query_keg(&prefix, "widget", "old-channel")?;
        let new = query_keg(&prefix, "widget", "2099.12.31")?;
        let opt = prefix.join("opt/widget");
        std::fs::write(old.join("payload"), "old")?;
        std::fs::write(new.join("payload"), "new")?;
        symlink(&old, &opt)?;
        assert_query_target("widget", &opt, &old)?;
        assert_eq!(std::fs::read_link(&opt)?, old);
        std::fs::remove_file(&opt)?;
        symlink(&new, &opt)?;
        assert_query_target("widget", &opt, &new)?;
        assert_eq!(std::fs::read_link(&opt)?, new);
        assert_eq!(std::fs::read_to_string(old.join("payload"))?, "old");
        assert_eq!(std::fs::read_to_string(new.join("payload"))?, "new");
        Ok(())
    }

    #[test]
    /// Return the user-facing prefix spelling while validating its canonical filesystem target.
    fn package_root_preserves_symlinked_prefix_and_spaces() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, base) = canonical_tempdir()?;
        let prefix = base.join("prefix with spaces");
        let alias = base.join("prefix alias");
        let keg = query_keg(&prefix, "widget", "active")?;
        symlink(&prefix, &alias)?;
        symlink(&keg, prefix.join("opt/widget"))?;
        let _guard = BrewPrefixGuard::set(&alias);
        assert_query_target("widget", &alias.join("opt/widget"), &keg)
    }

    #[test]
    /// Anchor relative prefix settings to the current directory before returning a usable path.
    fn package_root_makes_relative_prefix_absolute() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let cwd = std::env::current_dir()?;
        let tmp = tempfile::tempdir_in(&cwd)?;
        let relative = tmp.path().strip_prefix(&cwd)?;
        let _guard = BrewPrefixGuard::set(relative);
        let keg = query_keg(tmp.path(), "widget", "active")?;
        symlink("../Cellar/widget/active", tmp.path().join("opt/widget"))?;
        assert_query_target("widget", &cwd.join(relative).join("opt/widget"), &keg)
    }

    #[test]
    /// Require an active opt record rather than inferring one from Cellar or linked-keg entries.
    fn package_root_requires_opt_even_with_cellar_or_linked_keg() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, base) = canonical_tempdir()?;
        for state in [
            "missing-prefix",
            "empty-prefix",
            "cellar-only",
            "linked-only",
        ] {
            let prefix = base.join(state);
            let _guard = BrewPrefixGuard::set(&prefix);
            if state != "missing-prefix" {
                std::fs::create_dir_all(&prefix)?;
            }
            if matches!(state, "cellar-only" | "linked-only") {
                let keg = query_keg(&prefix, "widget", "active")?;
                if state == "linked-only" {
                    std::fs::create_dir_all(prefix.join("var/homebrew/linked"))?;
                    symlink(keg, prefix.join("var/homebrew/linked/widget"))?;
                }
            }
            let error = format!("{:#}", package_root("widget").unwrap_err());
            assert!(error.contains("widget"), "{state}: {error}");
            assert!(
                error.contains(&prefix.display().to_string()),
                "{state}: {error}"
            );
            assert!(error.contains("apply brew:widget"), "{state}: {error}");
            assert!(!prefix.join("opt/widget").exists());
        }
        Ok(())
    }

    #[test]
    /// Report a missing target with installation guidance while preserving the link for inspection.
    fn package_root_rejects_dangling_opt_without_repairing_it() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        std::fs::create_dir_all(prefix.join("opt"))?;
        let opt = prefix.join("opt/widget");
        let target = Path::new("../Cellar/widget/missing");
        symlink(target, &opt)?;
        let error = format!("{:#}", package_root("widget").unwrap_err());
        assert!(error.contains(&opt.display().to_string()), "{error}");
        assert!(error.contains("apply brew:widget"), "{error}");
        assert_eq!(std::fs::read_link(opt)?, target);
        Ok(())
    }

    #[test]
    /// Require opt symlinks and preserve invalid entries for explicit user repair.
    fn package_root_rejects_regular_directory_and_file_opt_records() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, base) = canonical_tempdir()?;
        for directory in [true, false] {
            let prefix = base.join(directory.to_string());
            let _guard = BrewPrefixGuard::set(&prefix);
            query_keg(&prefix, "widget", "active")?;
            let opt = prefix.join("opt/widget");
            if directory {
                std::fs::create_dir(&opt)?;
            } else {
                std::fs::write(&opt, "untouched")?;
            }
            let error = format!("{:#}", package_root("widget").unwrap_err());
            assert!(error.contains(&opt.display().to_string()), "{error}");
            assert!(!opt.symlink_metadata()?.is_symlink());
            if !directory {
                assert_eq!(std::fs::read_to_string(opt)?, "untouched");
            }
        }
        Ok(())
    }

    #[test]
    /// Accept only a direct keg directory in the requested rack, preserving rejected link targets.
    fn package_root_rejects_foreign_nested_rack_and_file_targets() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        let foreign = query_keg(&prefix, "foreign", "active")?;
        std::fs::create_dir(keg.join("nested"))?;
        let file = prefix.join("Cellar/widget/file");
        std::fs::write(&file, "untouched")?;
        let opt = prefix.join("opt/widget");
        for target in [
            foreign,
            keg.join("nested"),
            prefix.join("Cellar/widget"),
            file,
        ] {
            symlink(&target, &opt)?;
            let error = format!("{:#}", package_root("widget").unwrap_err());
            assert!(error.contains(&opt.display().to_string()), "{error}");
            assert_eq!(std::fs::read_link(&opt)?, target);
            std::fs::remove_file(&opt)?;
        }
        Ok(())
    }

    #[test]
    /// Validate the final canonical target rather than rejecting a legitimate intermediary symlink.
    fn package_root_accepts_outside_intermediary_resolving_to_its_keg() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        let intermediary = prefix.join("intermediary");
        symlink(&keg, &intermediary)?;
        let opt = prefix.join("opt/widget");
        symlink(intermediary, &opt)?;
        assert_query_target("widget", &opt, &keg)
    }

    #[test]
    /// Resolve symlinks before parent traversal so lexical normalization cannot disguise a foreign keg.
    fn package_root_uses_filesystem_dotdot_semantics_to_reject_foreign_target() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        let outside = prefix.join("outside");
        std::fs::create_dir_all(outside.join("child"))?;
        std::fs::create_dir(outside.join("active"))?;
        symlink(outside.join("child"), prefix.join("Cellar/widget/jump"))?;
        let opt = prefix.join("opt/widget");
        symlink("../Cellar/widget/jump/../active", &opt)?;
        assert_ne!(opt.canonicalize()?, keg);
        assert!(package_root("widget").is_err());
        Ok(())
    }

    #[test]
    /// Accept a valid keg reached through symlinks and parent traversal under filesystem semantics.
    fn package_root_uses_filesystem_dotdot_semantics_to_accept_local_target() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        std::fs::create_dir(prefix.join("outside"))?;
        std::fs::create_dir(prefix.join("Cellar/widget/child"))?;
        symlink(
            prefix.join("Cellar/widget/child"),
            prefix.join("outside/jump"),
        )?;
        let opt = prefix.join("opt/widget");
        symlink("../outside/jump/../active", &opt)?;
        assert_query_target("widget", &opt, &keg)
    }

    #[test]
    /// Preserve the OS loop error and failing opt path for filesystem diagnosis.
    fn package_root_preserves_symlink_loop_io_error_and_path() -> Result<()> {
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        query_keg(&prefix, "widget", "active")?;
        let opt = prefix.join("opt/widget");
        symlink("widget", &opt)?;
        let expected = opt.canonicalize().unwrap_err();
        let error = package_root("widget").unwrap_err();
        assert!(format!("{error:#}").contains(&opt.display().to_string()));
        let io = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<std::io::Error>());
        assert_eq!(
            io.expect("retain underlying filesystem error")
                .raw_os_error(),
            expected.raw_os_error()
        );
        assert_eq!(std::fs::read_link(opt)?, Path::new("widget"));
        Ok(())
    }

    #[test]
    /// Retain permission diagnostics on non-root hosts and restore fixture access for cleanup.
    fn package_root_preserves_permission_denial_and_path() -> Result<()> {
        if nix::unistd::geteuid().is_root() {
            return Ok(());
        }
        let _lock = ENV_LOCK.blocking_lock();
        let (_tmp, prefix) = canonical_tempdir()?;
        let _guard = BrewPrefixGuard::set(&prefix);
        let keg = query_keg(&prefix, "widget", "active")?;
        let opt = prefix.join("opt/widget");
        symlink(&keg, &opt)?;
        let rack = prefix.join("Cellar/widget");
        let permissions = rack.metadata()?.permissions();
        std::fs::set_permissions(&rack, std::fs::Permissions::from_mode(0o0))?;
        let result = package_root("widget");
        std::fs::set_permissions(&rack, permissions)?;
        let error = result.unwrap_err();
        assert!(format!("{error:#}").contains(&opt.display().to_string()));
        let io = error
            .chain()
            .find_map(|cause| cause.downcast_ref::<std::io::Error>());
        assert_eq!(
            io.expect("retain underlying filesystem error").kind(),
            std::io::ErrorKind::PermissionDenied
        );
        Ok(())
    }
}