aube 1.38.1

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

mod advisory;
mod args;
mod bin_linking;
pub(crate) mod control;
mod critical_path;
mod delta;
mod dep_selection;
mod fetch;
mod finalize;
mod frozen;
mod git_prepare;
mod gvs;
mod layout;
mod lifecycle;
mod link;
mod lockfile_dir;
mod lockfile_write_overlap;
mod materialize;
pub(crate) mod node_gyp_bootstrap;
mod resolve;
mod settings;
mod side_effects_cache;
mod startup;
mod summary;
mod sweep;
mod unreviewed_builds;
mod workspace;

use advisory::resolve_osv_routing_settings;
pub use args::{EmbedderInstallOverrides, InstallArgs, InstallOptions};
pub(crate) use bin_linking::{PkgJsonCache, link_dep_bins, materialized_pkg_dir};
pub use control::{
    InstallControl, InstallEvent, InstallOutputLevel, InstallOutputMode, InstallPhase,
    InstallProgressSnapshot, InstallPrompt, InstallPromptFuture, InstallPromptHandler,
    InstallReporter,
};
pub use dep_selection::DepSelection;
pub(super) use fetch::fetch_packages;
use fetch::{
    fetch_packages_with_root, import_local_source, remap_indices_to_contextualized,
    strip_peer_context_suffix, version_from_dep_path,
};
pub use frozen::{FrozenMode, FrozenOverride, GlobalVirtualStoreFlags};
pub(crate) use gvs::detect_existing_global_virtual_store;
pub(crate) use lifecycle::{
    JailBuildPolicy, build_policy_from_manifest_sources, build_policy_from_sources,
    run_dep_lifecycle_scripts,
};
use lifecycle::{
    resolve_link_strategy, run_import_on_blocking, run_root_lifecycle, run_root_lifecycle_script,
    validate_required_scripts,
};

pub(crate) fn resolve_active_lockfile_dir(
    cwd: &std::path::Path,
    manifest: &aube_manifest::PackageJson,
    settings_ctx: &aube_settings::ResolveCtx<'_>,
) -> miette::Result<std::path::PathBuf> {
    layout::resolve_lockfile_location(cwd, manifest, settings_ctx).map(|(dir, _)| dir)
}
use lockfile_dir::{
    parse_lockfile_dir_remapped_with_kind_and_options, write_lockfile_dir_remapped,
};
use materialize::{
    GvsPrewarmInputs, combine_install_pipeline_errors, materialize_channel, spawn_gvs_prewarm,
};
pub(crate) use settings::PeerDependencyRules;
pub(crate) use settings::resolve_minimum_release_age;
pub(crate) use settings::{ResolverConfigInputs, configure_resolver, finalize_lockfile_graph};
pub(crate) use side_effects_cache::{SideEffectsCacheConfig, side_effects_cache_root};

use settings::{
    check_unmet_peers, default_lockfile_network_concurrency, default_streaming_network_concurrency,
    maybe_cleanup_unused_catalogs, resolve_dependency_policy, resolve_git_shallow_hosts,
    resolve_link_concurrency, resolve_network_concurrency, resolve_side_effects_cache,
    resolve_side_effects_cache_readonly, resolve_strict_peer_dependencies,
    resolve_strict_store_pkg_content_check, resolve_verify_store_integrity,
};
use startup::{
    apply_force_state_reset, merge_branch_lockfiles_if_needed, modules_cache_sweep_is_default,
    resolve_project_cwd, try_install_fast_path, warn_accepted_noop_install_settings,
};
use summary::print_already_up_to_date;
use workspace::{
    discover_workspace_plan, filter_graph_to_importers, filter_graph_to_workspace_selection,
    importer_project_dir, merge_member_lockfile_graphs, per_project_write_selection,
    write_per_project_lockfiles,
};

const TRUST_POLICY_VALIDATION_CACHE_DIR: &str = "trust-policy-v1";
const TRUST_POLICY_VALIDATION_CACHE_TTL: std::time::Duration =
    std::time::Duration::from_secs(5 * 60);

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

    fn explicit_options(project_dir: &std::path::Path) -> InstallOptions {
        let mut options = InstallOptions::with_mode(FrozenMode::Prefer);
        options.project_dir = Some(project_dir.to_path_buf());
        options.ignore_scripts = true;
        options.skip_root_lifecycle = true;
        options.network_mode = aube_registry::NetworkMode::Offline;
        options
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn explicit_directory_installs_can_run_concurrently() {
        let first = tempfile::tempdir().unwrap();
        let second = tempfile::tempdir().unwrap();
        std::fs::write(first.path().join("package.json"), "{}\n").unwrap();
        std::fs::write(second.path().join("package.json"), "{}\n").unwrap();

        let (first_result, second_result) = tokio::join!(
            run(explicit_options(first.path())),
            run(explicit_options(second.path())),
        );

        first_result.unwrap();
        second_result.unwrap();
        assert!(first.path().join("aube-lock.yaml").is_file());
        assert!(second.path().join("aube-lock.yaml").is_file());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn guarded_installs_can_run_concurrently() {
        let first = tempfile::tempdir().unwrap();
        let second = tempfile::tempdir().unwrap();
        std::fs::write(first.path().join("package.json"), "{}\n").unwrap();
        std::fs::write(second.path().join("package.json"), "{}\n").unwrap();
        let first_lock = super::super::take_project_lock(first.path()).unwrap();
        let second_lock = super::super::take_project_lock(second.path()).unwrap();

        let (first_result, second_result) = tokio::join!(
            run_with_project_lock(explicit_options(first.path()), &first_lock),
            run_with_project_lock(explicit_options(second.path()), &second_lock),
        );

        first_result.unwrap();
        second_result.unwrap();
        assert!(first.path().join("aube-lock.yaml").is_file());
        assert!(second.path().join("aube-lock.yaml").is_file());
    }
}

pub(crate) fn package_build_is_allowed(
    policy: &aube_scripts::BuildPolicy,
    pkg: &aube_lockfile::LockedPackage,
) -> bool {
    let source_key = pkg.source_approval_key();
    let git_repository_key = pkg.git_repository_approval_key();
    matches!(
        policy.decide_package_with_git_repository(
            pkg.registry_name(),
            &pkg.version,
            source_key.as_deref(),
            git_repository_key.as_deref(),
        ),
        aube_scripts::AllowDecision::Allow
    )
}

#[derive(serde::Deserialize, serde::Serialize)]
struct TrustPolicyValidationStamp {
    key: String,
    validated_at_secs: u64,
}

#[derive(Default)]
struct InstallPhaseTimings {
    path: Option<std::path::PathBuf>,
    phases_ms: BTreeMap<&'static str, u128>,
    /// Last kernel snapshot, captured immediately after the previous
    /// phase recorded. The next [`record`] call diffs against this and
    /// emits a `kernel.<phase>` event with the per-phase user/sys CPU,
    /// peak RSS, and page fault deltas.
    last_kernel_snap: Option<aube_util::diag_kernel::KernelSnapshot>,
}

impl InstallPhaseTimings {
    fn from_env() -> Self {
        Self {
            path: aube_util::env::embedder_env("BENCH_PHASES_FILE").map(std::path::PathBuf::from),
            phases_ms: BTreeMap::new(),
            last_kernel_snap: aube_util::diag_kernel::snapshot(),
        }
    }

    fn record(&mut self, phase: &'static str, elapsed: std::time::Duration) {
        if self.path.is_some() {
            self.phases_ms.insert(phase, elapsed.as_millis());
        }
        aube_util::diag::event(
            aube_util::diag::Category::InstallPhase,
            phase,
            elapsed,
            None,
        );
        // When kernel sampling is on, emit a per-phase kernel delta so
        // user/sys CPU split, page fault counts, and peak RSS land in
        // the trace alongside the wall-time phase event.
        if aube_util::diag_kernel::enabled()
            && let Some(after) = aube_util::diag_kernel::snapshot()
        {
            if let Some(before) = self.last_kernel_snap.take() {
                aube_util::diag_kernel::emit_phase_delta(phase, before, after);
            }
            self.last_kernel_snap = Some(after);
        }
    }

    fn write(
        &self,
        cwd: &std::path::Path,
        total: std::time::Duration,
        packages: usize,
        cached: usize,
        fetched: usize,
    ) {
        let Some(path) = &self.path else {
            return;
        };
        let payload = serde_json::json!({
            "cwd": cwd,
            "scenario": aube_util::env::embedder_env("BENCH_SCENARIO")
                .and_then(|s| s.into_string().ok()),
            "total_ms": total.as_millis(),
            "packages": packages,
            "cached": cached,
            "fetched": fetched,
            "phases_ms": self.phases_ms,
        });
        let Ok(line) = serde_json::to_string(&payload) else {
            return;
        };
        match std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
        {
            Ok(mut file) => {
                let _ = writeln!(file, "{line}");
            }
            Err(e) => tracing::debug!("failed to write install phase timings: {e}"),
        }
    }
}

fn apply_computed_integrities(
    graph: &mut aube_lockfile::LockfileGraph,
    computed: &BTreeMap<String, String>,
) {
    if computed.is_empty() {
        return;
    }
    for pkg in graph.packages.values_mut() {
        if pkg.integrity.is_some() || pkg.local_source.is_some() {
            continue;
        }
        let canonical = strip_peer_context_suffix(&pkg.dep_path);
        if let Some(integrity) = computed.get(canonical) {
            pkg.integrity = Some(integrity.clone());
        }
    }
}

async fn validate_lockfile_trust_policy(
    cwd: &std::path::Path,
    settings_ctx: &aube_settings::ResolveCtx<'_>,
    graph: &aube_lockfile::LockfileGraph,
    network_mode: aube_registry::NetworkMode,
    policy: &aube_resolver::DependencyPolicy,
) -> miette::Result<()> {
    let Some(cache_key) = trust_policy_validation_cache_key(cwd, graph, network_mode, policy)
    else {
        return Ok(());
    };
    let cache_dir = super::resolved_cache_dir_with_ctx(cwd, settings_ctx);
    if trust_policy_validation_cache_hit(&cache_dir, &cache_key) {
        tracing::debug!("trustPolicy=no-downgrade: reused lockfile validation cache");
        return Ok(());
    }

    let client = std::sync::Arc::new(make_client(cwd).with_network_mode(network_mode));
    let full_cache_dir = cache_dir.join("packuments-full-v1");
    let concurrency = default_lockfile_network_concurrency().max(1);
    let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(concurrency));
    let mut seen = std::collections::BTreeSet::new();
    let mut checks: tokio::task::JoinSet<Result<(), aube_resolver::Error>> =
        tokio::task::JoinSet::new();

    for dep_path in reachable_package_dep_paths(graph) {
        let Some(pkg) = graph.packages.get(&dep_path) else {
            continue;
        };
        if pkg.local_source.is_some() {
            continue;
        }
        let name = pkg.registry_name().to_string();
        let version = pkg.version.clone();
        if !seen.insert((name.clone(), version.clone())) {
            continue;
        }

        let client = client.clone();
        let full_cache_dir = full_cache_dir.clone();
        let exclude = policy.trust_policy_exclude.clone();
        let ignore_after = policy.trust_policy_ignore_after;
        let semaphore = semaphore.clone();
        checks.spawn(async move {
            let _permit = semaphore.acquire_owned().await.map_err(|e| {
                aube_resolver::Error::Registry(name.clone(), format!("trust check cancelled: {e}"))
            })?;
            let packument = client
                .fetch_packument_with_time_cached(&name, &full_cache_dir)
                .await
                .map_err(|e| aube_resolver::Error::Registry(name.clone(), e.to_string()))?;
            let picked = packument.versions.get(&version).ok_or_else(|| {
                aube_resolver::Error::Registry(
                    name.clone(),
                    format!("registry packument has no metadata for {name}@{version}"),
                )
            })?;
            aube_resolver::check_no_downgrade(&packument, &version, picked, &exclude, ignore_after)
                .map_err(|e| match e {
                    aube_resolver::TrustCheckError::Downgrade(d) => {
                        aube_resolver::Error::TrustDowngrade(Box::new(d))
                    }
                    aube_resolver::TrustCheckError::MissingTime(d) => {
                        aube_resolver::Error::TrustCheckMissingTime(Box::new(d))
                    }
                })
        });
    }

    while let Some(result) = checks.join_next().await {
        let result = result.map_err(|e| miette!("trust-policy validation task failed: {e}"))?;
        result.map_err(miette::Report::new)?;
    }

    record_lockfile_trust_policy_validation(&cache_dir, &cache_key);
    Ok(())
}

fn trust_policy_validation_cache_key(
    cwd: &std::path::Path,
    graph: &aube_lockfile::LockfileGraph,
    network_mode: aube_registry::NetworkMode,
    policy: &aube_resolver::DependencyPolicy,
) -> Option<String> {
    if policy.trust_policy != aube_resolver::TrustPolicy::NoDowngrade
        || matches!(network_mode, aube_registry::NetworkMode::Offline)
    {
        return None;
    }

    let mut hasher = blake3::Hasher::new();
    hasher.update(b"aube:trust-policy-validation:v1\0");
    hasher.update(env!("CARGO_PKG_VERSION").as_bytes());
    hasher.update(b"\0network=");
    hasher.update(format!("{network_mode:?}").as_bytes());
    hasher.update(b"\0ignore_after=");
    hasher.update(format!("{:?}", policy.trust_policy_ignore_after).as_bytes());
    hasher.update(b"\0exclude=");
    hasher.update(format!("{:?}", policy.trust_policy_exclude).as_bytes());

    let config = super::load_npm_config(cwd);
    hasher.update(b"\0registry=");
    hasher.update(config.registry.as_bytes());
    hasher.update(b"\0scoped_registries=");
    for (scope, url) in config.scoped_registries {
        hasher.update(scope.as_bytes());
        hasher.update(b"\x1f");
        hasher.update(url.as_bytes());
        hasher.update(b"\x1e");
    }

    for dep_path in reachable_package_dep_paths(graph) {
        let Some(pkg) = graph.packages.get(&dep_path) else {
            continue;
        };
        if pkg.local_source.is_some() {
            continue;
        }
        hasher.update(b"\0pkg=");
        hasher.update(dep_path.as_bytes());
        hasher.update(b"\x1f");
        hasher.update(pkg.name.as_bytes());
        hasher.update(b"\x1f");
        hasher.update(pkg.registry_name().as_bytes());
        hasher.update(b"\x1f");
        hasher.update(pkg.version.as_bytes());
        hasher.update(b"\x1f");
        if let Some(alias_of) = &pkg.alias_of {
            hasher.update(alias_of.as_bytes());
        }
        hasher.update(b"\x1f");
        if let Some(integrity) = &pkg.integrity {
            hasher.update(integrity.as_bytes());
        }
        hasher.update(b"\x1f");
        if let Some(tarball_url) = &pkg.tarball_url {
            hasher.update(tarball_url.as_bytes());
        }
    }

    Some(hasher.finalize().to_hex().to_string())
}

fn trust_policy_validation_cache_path(
    cache_dir: &std::path::Path,
    key: &str,
) -> std::path::PathBuf {
    cache_dir
        .join(TRUST_POLICY_VALIDATION_CACHE_DIR)
        .join(format!("{key}.json"))
}

fn trust_policy_validation_cache_hit(cache_dir: &std::path::Path, key: &str) -> bool {
    let path = trust_policy_validation_cache_path(cache_dir, key);
    let Ok(bytes) = std::fs::read(path) else {
        return false;
    };
    let Ok(stamp) = serde_json::from_slice::<TrustPolicyValidationStamp>(&bytes) else {
        return false;
    };
    if stamp.key != key {
        return false;
    }
    let Some(now) = unix_time_secs() else {
        return false;
    };
    let Some(age_secs) = now.checked_sub(stamp.validated_at_secs) else {
        return false;
    };
    age_secs <= TRUST_POLICY_VALIDATION_CACHE_TTL.as_secs()
}

fn record_lockfile_trust_policy_validation(cache_dir: &std::path::Path, cache_key: &str) {
    let Some(validated_at_secs) = unix_time_secs() else {
        return;
    };
    let stamp = TrustPolicyValidationStamp {
        key: cache_key.to_string(),
        validated_at_secs,
    };
    let Ok(bytes) = serde_json::to_vec(&stamp) else {
        return;
    };
    let path = trust_policy_validation_cache_path(cache_dir, cache_key);
    if let Err(e) = aube_util::fs_atomic::atomic_write(&path, &bytes) {
        tracing::debug!("failed to write trust-policy validation cache: {e}");
    }
}

fn maybe_record_lockfile_trust_policy_validation(
    cwd: &std::path::Path,
    settings_ctx: &aube_settings::ResolveCtx<'_>,
    graph: &aube_lockfile::LockfileGraph,
    network_mode: aube_registry::NetworkMode,
    policy: &aube_resolver::DependencyPolicy,
) {
    if let Some(cache_key) = trust_policy_validation_cache_key(cwd, graph, network_mode, policy) {
        let cache_dir = super::resolved_cache_dir_with_ctx(cwd, settings_ctx);
        record_lockfile_trust_policy_validation(&cache_dir, &cache_key);
    }
}

fn can_seed_trust_policy_validation_from_resolve(
    lockfile_enabled: bool,
    had_existing_lockfile_for_resolver: bool,
) -> bool {
    lockfile_enabled && !had_existing_lockfile_for_resolver
}

fn unix_time_secs() -> Option<u64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .map(|d| d.as_secs())
}

fn reachable_package_dep_paths(
    graph: &aube_lockfile::LockfileGraph,
) -> std::collections::BTreeSet<String> {
    let mut reachable = std::collections::BTreeSet::new();
    let mut stack = graph
        .importers
        .values()
        .flat_map(|deps| deps.iter().map(|dep| dep.dep_path.clone()))
        .collect::<Vec<_>>();

    while let Some(dep_path) = stack.pop() {
        if !reachable.insert(dep_path.clone()) {
            continue;
        }
        let Some(pkg) = graph.packages.get(&dep_path) else {
            continue;
        };
        for (name, tail) in &pkg.dependencies {
            if let Some(child) =
                aube_lockfile::resolve_dep_edge(name, tail, |k| graph.packages.contains_key(k))
            {
                stack.push(child);
            }
        }
    }

    reachable
}

pub async fn run(opts: InstallOptions) -> miette::Result<()> {
    let cwd = resolve_project_cwd(&opts)?;
    let _lock = super::take_project_lock(&cwd)?;
    run_scoped(opts, cwd).await
}

/// Run install while reusing a project lock owned by an outer command.
///
/// The guard determines the project directory, making lock reentrancy
/// invocation-scoped: only the command that owns this project's lock can
/// bypass acquisition. Concurrent installs for unrelated projects always
/// acquire their own filesystem lock.
pub(crate) async fn run_with_project_lock(
    mut opts: InstallOptions,
    lock: &super::project_lock::ProjectLock,
) -> miette::Result<()> {
    let cwd = lock.project_dir().to_path_buf();
    opts.project_dir = Some(cwd.clone());
    run_scoped(opts, cwd).await
}

async fn run_scoped(opts: InstallOptions, cwd: std::path::PathBuf) -> miette::Result<()> {
    let control = opts.control.clone();
    // Box the large install state machine before stacking task-local scopes.
    // Keeping it inline overflowed a Tokio worker stack in the parallel-install
    // regression test once runtime and script-settings scopes were added.
    let install = Box::pin(run_inner(opts, cwd));
    control::scope(
        control,
        crate::runtime::scope(aube_scripts::scope(crate::dep_chain::scope(install))),
    )
    .await
}

async fn run_inner(opts: InstallOptions, cwd: std::path::PathBuf) -> miette::Result<()> {
    opts.control.check_cancelled()?;
    let mode = opts.mode;
    let start = std::time::Instant::now();
    let mut phase_timings = InstallPhaseTimings::from_env();
    aube_util::diag::spawn_concurrency_sampler();
    aube_util::diag::instant(aube_util::diag::Category::Install, "begin", None);
    let _diag_install = aube_util::diag::Span::new(aube_util::diag::Category::Install, "total");

    if !opts.dry_run {
        apply_force_state_reset(&cwd, &opts)?;
    }
    if !opts.dry_run
        && let Some(total) =
            try_install_fast_path(&cwd, &opts, mode, modules_cache_sweep_is_default(&cwd))?
    {
        control::complete(total);
        return Ok(());
    }

    // Yaml-only workspace roots (`pnpm-workspace.yaml` only, no root
    // `package.json`) install with a synthesized empty manifest so
    // every workspace member is installed without the root carrying
    // any deps or scripts itself. The synthesized manifest naturally
    // skips root lifecycle hooks, has no required-scripts to validate,
    // and threads through the rest of the pipeline as a manifest with
    // no direct deps would.
    let manifest = super::load_manifest_or_default(&cwd)?;
    let project_name = manifest.name.as_deref().unwrap_or("(unnamed)");

    // Load the workspace yaml *once* — both as the typed
    // `WorkspaceConfig` (used below for `allow_builds_raw` and
    // friends) and as a raw `BTreeMap` (used by
    // `aube_settings::resolved::*` for metadata-driven lookups).
    // Errors propagate here rather than silently defaulting later,
    // so a malformed workspace file surfaces before we start
    // resolving the dep graph. Also load `.npmrc` entries once so
    // the same borrow feeds both the resolve-time settings and the
    // later engine-check settings.
    let files = crate::commands::FileSources::load(&cwd);
    let (ws_config_shared, raw_workspace) = aube_manifest::workspace::load_both(&cwd)
        .into_diagnostic()
        .wrap_err("failed to load workspace config")?;
    // Catalog discovery walks up for the workspace yaml and also pulls
    // from package.json's `workspaces.catalog` / `pnpm.catalog`, so
    // `aube install` run from a monorepo subpackage still sees the root
    // workspace's catalog. See `discover_catalogs` for the precedence
    // order.
    let workspace_catalogs = super::discover_catalogs(&cwd)?;
    let settings_ctx = files.ctx(&raw_workspace, &opts.env_snapshot, &opts.cli_flags);
    let packument_cache_dir =
        super::resolved_cache_dir_with_ctx(&cwd, &settings_ctx).join("packuments-v1");
    let explicit_store_dir_override = has_explicit_store_dir_override(&opts.cli_flags);
    let dependency_policy = resolve_dependency_policy(&manifest, &settings_ctx);
    // Resolve the project's Node runtime before anything can spawn
    // node: the root `preinstall` hooks below must already run on the
    // switched runtime, and the virtual-store keys downstream fold
    // the node major in. The lockfile pin (when recorded) wins over
    // the manifest range, and `--offline` blocks runtime downloads
    // the same way it blocks registry fetches.
    let mut runtime_settings = crate::runtime::RuntimeSettings::from_ctx(&settings_ctx);
    if opts.network_mode == aube_registry::NetworkMode::Offline {
        runtime_settings.network = aube_runtime::NetworkMode::Offline;
    }
    let strict_store_integrity_setting = settings::resolve_strict_store_integrity(&settings_ctx);
    let lockfile_parse_options = aube_lockfile::ParseOptions {
        strict_store_integrity: strict_store_integrity_setting,
    };
    // An embedding host (mise, or a wrapper) can describe how Node is
    // invoked for lifecycle scripts. Seed it into the scoped runtime slot
    // before `ensure` runs — `ensure` returns early when the slot is set,
    // so aube skips its own runtime resolution and scripts invoke the
    // host's Node. A per-call runtime wins over the process-wide one.
    crate::runtime::seed_install_embedder_runtime(opts.embedder_runtime.as_ref());
    if !opts.dry_run {
        crate::runtime::ensure(
            &cwd,
            Some(&manifest),
            runtime_settings,
            crate::runtime::lockfile_node_pin(&cwd, &manifest, lockfile_parse_options).as_ref(),
        )
        .await?;
    }
    if !opts.ignore_scripts {
        super::configure_script_settings(&settings_ctx, Some(opts.script_command));
    }

    let layout::InstallLayoutConfig {
        lockfile_dir,
        lockfile_importer_key,
        modules_dir_name,
        aube_dir,
        lockfile_enabled,
        shared_workspace_lockfile,
        lockfile_only_effective,
        lockfile_include_tarball_url,
    } = layout::resolve_install_layout(
        &cwd,
        &manifest,
        &settings_ctx,
        opts.lockfile_only,
        opts.strict_no_lockfile,
    )?;

    if !opts.dry_run {
        merge_branch_lockfiles_if_needed(
            &cwd,
            &manifest,
            &settings_ctx,
            lockfile_enabled,
            opts.merge_git_branch_lockfiles,
        )?;
    }

    // Resolve the install-wide networking / integrity knobs once up
    // front so every downstream fetch site (the lockfile path, the
    // streaming-resolver path, and the forthcoming `aube fetch`
    // bridge) reads the same values. `network_concurrency_setting`
    // stays `Option<usize>` so each site can apply the dynamic
    // built-in fallback when the setting is absent.
    //
    // `sideEffectsCache` controls whether allowlisted dependency
    // lifecycle scripts can reuse a previously-cached post-build
    // package directory. It still respects aube's security model:
    // packages that are not allowed by BuildPolicy never run scripts
    // and never populate the side-effects cache.
    let network_concurrency_setting = resolve_network_concurrency(&settings_ctx);
    let link_concurrency_setting = resolve_link_concurrency(&settings_ctx);
    let verify_store_integrity_setting = resolve_verify_store_integrity(&settings_ctx);
    let strict_store_pkg_content_check_setting =
        resolve_strict_store_pkg_content_check(&settings_ctx);
    let side_effects_cache_setting = resolve_side_effects_cache(&settings_ctx);
    let side_effects_cache_readonly_setting = resolve_side_effects_cache_readonly(&settings_ctx);
    // `paranoid=true` forces unreviewed dep build scripts to error
    // instead of being silently skipped.
    let strict_dep_builds_setting = aube_settings::resolved::strict_dep_builds(&settings_ctx)
        || aube_settings::resolved::paranoid(&settings_ctx);
    let required_scripts =
        aube_settings::resolved::required_scripts(&settings_ctx).unwrap_or_default();
    validate_required_scripts(&cwd, &manifest, &required_scripts)?;
    warn_accepted_noop_install_settings(&settings_ctx);
    // `dlxCacheMaxAge` has no consumer yet (aube `dlx` uses a
    // tempdir per invocation) but resolving it here keeps the value
    // exercised through the same `ResolveCtx` the rest of the install
    // uses, so a future persistent-dlx-cache change can pick it up
    // without revisiting the resolver wiring.
    let _ = aube_settings::resolved::dlx_cache_max_age(&settings_ctx);
    tracing::debug!(
        "settings: network-concurrency={:?}, link-concurrency={:?}, verify-store-integrity={}, strict-store-pkg-content-check={}, side-effects-cache={}, side-effects-cache-readonly={}, strict-dep-builds={}",
        network_concurrency_setting,
        link_concurrency_setting,
        verify_store_integrity_setting,
        strict_store_pkg_content_check_setting,
        side_effects_cache_setting,
        side_effects_cache_readonly_setting,
        strict_dep_builds_setting,
    );

    // Resolve once for the whole install: both the fetch phase's
    // `AlreadyLinked` fast path and the linker's `aube_dir_entry_name`
    // need to encode `dep_path` into the same `.aube/<name>` filename.
    // Pinning the value here and threading it through both call sites
    // keeps them in lockstep, and the same resolved cap is re-read by
    // `aube list` / `aube why` / `aube patch` / `aube rebuild` so the
    // read-side encoding agrees with what the linker actually wrote.
    let virtual_store_dir_max_length = super::resolve_virtual_store_dir_max_length(&settings_ctx);

    let workspace_plan =
        discover_workspace_plan(&cwd, &manifest, &settings_ctx, &opts.workspace_filter)?;
    let workspace_packages = workspace_plan.workspace_packages;
    let has_workspace = workspace_plan.has_workspace;
    let is_workspace_project = workspace_plan.is_workspace_project;
    let link_all_workspace_importers = workspace_plan.link_all_workspace_importers;
    let manifests = workspace_plan.manifests;
    let ws_package_versions = workspace_plan.ws_package_versions;
    let ws_dirs = workspace_plan.ws_dirs;
    let lifecycle_manifests = workspace_plan.lifecycle_manifests;
    let dangerously_allow_all_builds =
        aube_settings::resolved::dangerously_allow_all_builds(&settings_ctx);
    // Importer keys whose per-project lockfiles a filtered install may
    // (re)write. `None` for an unfiltered install (write every importer).
    // Computed once and shared by the `--lockfile-only` short-circuit and
    // the streaming-install write so both paths stay scoped identically.
    let per_project_write_selection =
        per_project_write_selection(&cwd, &workspace_packages, &opts.workspace_filter)?;
    let (build_policy, policy_warnings) =
        if let Some(override_policy) = opts.build_policy_override.as_deref() {
            (override_policy.clone(), Vec::new())
        } else {
            let (mut build_policy, policy_warnings) = build_policy_from_manifest_sources(
                lifecycle_manifests.iter().map(|(_, manifest)| manifest),
                &ws_config_shared,
                dangerously_allow_all_builds,
            );
            if let Some(inherited) = opts.inherited_build_policy.as_deref() {
                build_policy.merge(inherited);
            }
            (build_policy, policy_warnings)
        };
    let inherited_build_policy_for_git_prepare = Some(std::sync::Arc::new(build_policy.clone()));

    // pnpm's root-only pre-resolution hook. Unlike the ordinary
    // `preinstall` lifecycle below, this runs exactly once from the
    // lockfile/workspace root and never fans out to member manifests.
    // The warm fast path returned above, so an already-current repeat
    // install naturally skips it.
    if opts.run_dev_preinstall {
        run_dev_preinstall(
            &cwd,
            opts.ignore_scripts,
            opts.dry_run,
            lockfile_only_effective,
            None,
        )
        .await?;
    }

    // 1b. Project `preinstall` lifecycle hooks.
    //     Workspace installs run the hook for every physical importer
    //     that will be linked, matching pnpm's recursive install
    //     behavior. Runs before the progress UI starts so script output
    //     cannot collide with the progress display.
    if !opts.dry_run
        && !opts.ignore_scripts
        && !lockfile_only_effective
        && !opts.skip_root_lifecycle
    {
        let phase_start = std::time::Instant::now();
        for (importer_path, importer_manifest) in &lifecycle_manifests {
            let project_dir = importer_project_dir(&cwd, importer_path);
            run_root_lifecycle(
                &project_dir,
                &modules_dir_name,
                importer_manifest,
                aube_scripts::LifecycleHook::PreInstall,
            )
            .await?;
        }
        phase_timings.record("root_preinstall", phase_start.elapsed());
    }
    // Progress UI. `None` on non-TTY stderr, in text mode (e.g. `-v`), or
    // when progress output is otherwise disabled. A normal install produces
    // *no* output other than the bar itself — everything else is tracing at
    // debug level, visible with `aube -v install`. Must be constructed after
    // any lifecycle script that writes to stderr.
    control::check_cancelled()?;
    let prog = InstallProgress::try_new();
    let prog_ref = prog.as_ref();

    let use_global_virtual_store_override =
        gvs::resolve_global_virtual_store_override(&settings_ctx, &manifests, &opts.env_snapshot);

    // Remember which lockfile format the project currently uses so
    // every downstream write site (the `--lockfile-only` short-circuit
    // below *and* the re-resolve branch further down) can preserve it
    // instead of quietly converting the project to another filename.
    // Must happen before the `--lockfile-only` block so that path
    // doesn't bypass the format-preserving write logic. Skipped when
    // `lockfile=false` — no lockfile is read and no format is
    // preserved, so the install always writes nothing (see below).
    let source_kind_before = if lockfile_enabled {
        aube_lockfile::detect_existing_lockfile_kind(&lockfile_dir)
    } else {
        None
    };

    // Hand any parseable lockfile to the resolver as `existing` so
    // unchanged specs reuse their already-pinned versions and only
    // entries whose spec actually drifted get re-resolved. Without
    // this, `aube install` after any manifest edit re-resolves every
    // transitive against the latest packument and silently bumps
    // versions that the previous lockfile had pinned (e.g.
    // `electron-to-chromium@1.5.344` → `1.5.343`), which is the
    // opposite of what pnpm/bun's default `install` does.
    //
    // Scope:
    //   - Fix: existing behavior (`--fix-lockfile`).
    //   - Prefer: default mode; the bug above lives here.
    //   - Frozen: short-circuits to the lockfile-as-truth branch and
    //     never calls the resolver, so parsing is wasted work.
    //   - No (`--no-frozen-lockfile`): kept as fresh-resolve so users
    //     who reach for that flag to bump transitives still get a
    //     fresh pass. Matching pnpm's "lockfile may drift but locked
    //     versions are still preferred" semantics is a separate
    //     decision and would change observable behavior on this path.
    //
    // We parse once and keep both the graph and its kind so the
    // `--lockfile-only` block below can reuse the same result for its
    // freshness check instead of re-reading + re-parsing the same file.
    //
    // Hard-fail on a real parse error: the prior in-arm parse in
    // `FrozenMode::Prefer` propagated parse errors out of
    // `lockfile_result`, and silently swallowing them here would leave
    // a corrupt lockfile masquerading as "no lockfile" and trigger a
    // full re-resolve without surfacing the actionable diagnostic.
    // `NotFound` is the one error we treat as expected — it just means
    // the lockfile is absent, which the downstream arms already handle.
    let lockfile_pre_parse = resolve::pre_parse_lockfile(
        lockfile_enabled,
        mode,
        &lockfile_dir,
        &lockfile_importer_key,
        &manifest,
        lockfile_parse_options,
    )?;
    let lockfile_conflict_marker_warning_emitted = lockfile_pre_parse.is_none()
        && lockfile_enabled
        && matches!(mode, FrozenMode::Fix | FrozenMode::Prefer)
        && aube_lockfile::active_lockfile_has_conflict_markers(&lockfile_dir);
    let existing_for_resolver: Option<&aube_lockfile::LockfileGraph> =
        lockfile_pre_parse.as_ref().map(|(g, _)| g);

    // `--lockfile-only` short-circuit. Resolves (or reuses a fresh
    // lockfile), writes the new lockfile, and exits before any tarball
    // fetch / link / lifecycle work. Runs *before* the FrozenMode match
    // so lockfile-only bypasses drift hard-errors entirely — pnpm's
    // `--lockfile-only` regenerates regardless of frozen mode, and we'd
    // otherwise be preempted by the auto-CI Frozen default.
    // `enableModulesDir=false` follows the same short-circuit so
    // projects that persistently disable node_modules materialization
    // share the exact same control flow. `--dry-run` reuses the resolve
    // and report path without writing the lockfile; unlike
    // `--lockfile-only`, explicit frozen mode still validates drift.
    if lockfile_only_effective || opts.dry_run {
        if opts.dry_run && opts.strict_no_lockfile && matches!(mode, FrozenMode::Frozen) {
            match resolve::select_lockfile_result(resolve::SelectLockfileInput {
                lockfile_enabled,
                mode,
                cwd: &cwd,
                lockfile_dir: &lockfile_dir,
                lockfile_importer_key: &lockfile_importer_key,
                manifest: &manifest,
                parse_options: lockfile_parse_options,
                manifests: &manifests,
                ws_config: &ws_config_shared,
                workspace_catalogs: &workspace_catalogs,
                is_workspace_project,
                lockfile_pre_parse: lockfile_pre_parse.as_ref(),
            })? {
                Ok(_) => {}
                Err(aube_lockfile::Error::NotFound(_)) => {
                    return Err(miette!(
                        "no lockfile found and --frozen-lockfile is set\n\
                         help: commit pnpm-lock.yaml to your repository, or run \
                         `{} --no-frozen-lockfile` to generate one",
                        aube_util::cmd("install")
                    ));
                }
                Err(e) => {
                    return Err(miette::Report::new(e)).wrap_err("failed to parse lockfile");
                }
            }
        }
        resolve::run_lockfile_only(resolve::LockfileOnlyInput {
            cwd: &cwd,
            mode,
            lockfile_dir: &lockfile_dir,
            lockfile_importer_key: &lockfile_importer_key,
            manifest: &manifest,
            parse_options: lockfile_parse_options,
            manifests: &manifests,
            per_project_write_selection: per_project_write_selection.as_ref(),
            ws_config: &ws_config_shared,
            workspace_catalogs: &workspace_catalogs,
            settings_ctx: &settings_ctx,
            dependency_policy: &dependency_policy,
            lockfile_pre_parse: lockfile_pre_parse.as_ref(),
            lockfile_conflict_marker_warning_emitted,
            existing_for_resolver,
            source_kind_before,
            lockfile_enabled,
            lockfile_include_tarball_url,
            shared_workspace_lockfile,
            has_workspace,
            is_workspace_project,
            ignore_pnpmfile: opts.ignore_pnpmfile,
            network_mode: opts.network_mode,
            global_pnpmfile: opts.global_pnpmfile.as_deref(),
            pnpmfile: opts.pnpmfile.as_deref(),
            minimum_release_age_override: opts.minimum_release_age_override,
            ws_package_versions: &ws_package_versions,
            ignore_scripts: opts.ignore_scripts,
            write_lockfile: !opts.dry_run,
            prog_ref,
        })
        .await?;
        return Ok(());
    }

    let planned_gvs =
        gvs::planned_global_virtual_store(use_global_virtual_store_override, &opts.env_snapshot);
    gvs::reset_on_mode_change(
        &cwd,
        &aube_dir,
        &modules_dir_name,
        planned_gvs,
        &settings_ctx,
    )?;

    // 3. Parse or resolve lockfile, streaming tarball fetches during resolution
    let phase_start = std::time::Instant::now();
    let store = std::sync::Arc::new(super::open_store_with_ctx(&cwd, &settings_ctx)?);
    // Pre-create all 256 two-char shard directories in the CAS root.
    // `import_bytes` is called once per stored file (~7.5k for a medium
    // install) and previously did `mkdirp(parent)` per call — a stat
    // syscall that was the #1 hotspot in a dtrace/fs_usage profile.
    // With the shard tree pre-created, every `import_bytes` skips the
    // mkdirp entirely and lets its `create_new` open handle the
    // existence check atomically. Best-effort: a failure here is not
    // fatal because `import_bytes` retains the slow-path mkdirp
    // fallback when shards are missing.
    if let Err(e) = store.ensure_shards_exist() {
        tracing::debug!("ensure_shards_exist failed (slow path will cover): {e}");
    }
    // macOS fast-path gate: take an exclusive `try_lock` on
    // `<store>/v1/.install.lock`. If we get it, no other aube install is
    // running against this store right now, so the CAS write path can
    // skip the tempfile + persist_noclobber dance and write straight to
    // the final content-addressed path (`Store::enable_fast_path`). The
    // guard is held in `_store_lock` for the rest of this `run` call;
    // dropping it at function exit releases the lock. Contention falls
    // back to the safe tempfile path — concurrent installers still
    // proceed, just at the existing speed.
    //
    // Linux is unaffected: `create_cas_file` always uses O_TMPFILE+linkat
    // there, which is already atomic-by-construction and faster than
    // both options. Windows keeps the tempfile path; the fast-path branch
    // in `aube-store` is unix-only (`OpenOptionsExt::mode`), so gating
    // the lock acquisition on macOS too avoids opening a lock file that
    // nothing would consult.
    #[cfg(target_os = "macos")]
    let _store_lock = {
        let lock_dir = store
            .root()
            .parent()
            .map(std::path::Path::to_path_buf)
            .unwrap_or_else(|| store.root().to_path_buf());
        let _ = std::fs::create_dir_all(&lock_dir);
        let lock_path = lock_dir.join(".install.lock");
        match std::fs::OpenOptions::new()
            .create(true)
            .truncate(false)
            .write(true)
            .open(&lock_path)
        {
            Ok(file) => match file.try_lock() {
                Ok(()) => {
                    store.enable_fast_path();
                    tracing::debug!("CAS fast path enabled (exclusive store lock acquired)");
                    Some(file)
                }
                Err(std::fs::TryLockError::WouldBlock) => {
                    tracing::debug!(
                        "another aube install is using this store; staying on tempfile path"
                    );
                    None
                }
                Err(std::fs::TryLockError::Error(e)) => {
                    tracing::debug!("store lock probe failed ({e}); staying on tempfile path");
                    None
                }
            },
            Err(e) => {
                tracing::debug!(
                    "could not open store lock at {} ({e}); staying on tempfile path",
                    lock_path.display()
                );
                None
            }
        }
    };

    let lockfile_result = resolve::select_lockfile_result(resolve::SelectLockfileInput {
        lockfile_enabled,
        mode,
        cwd: &cwd,
        lockfile_dir: &lockfile_dir,
        lockfile_importer_key: &lockfile_importer_key,
        manifest: &manifest,
        parse_options: lockfile_parse_options,
        manifests: &manifests,
        ws_config: &ws_config_shared,
        workspace_catalogs: &workspace_catalogs,
        is_workspace_project,
        lockfile_pre_parse: lockfile_pre_parse.as_ref(),
    })?;

    // Deprecation messages from freshly-resolved packages. Only the
    // no-lockfile branch below populates this; the lockfile-reuse branch
    // has no packument in hand. Rendered right before the install summary
    // once `filter_graph` has culled dropped packages.
    let deprecations: std::sync::Arc<
        std::sync::Mutex<Vec<crate::deprecations::DeprecationRecord>>,
    > = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

    // Per-direct-dep packument snapshot rendered inline by the install
    // summary printer (`+ name@version  deprecated · latest …`). Only
    // populated by the resolve-from-packuments branch — the frozen
    // lockfile reuse path has no cache to read from, so badges silently
    // degrade to empty rather than triggering extra network.
    let mut direct_dep_info: std::collections::HashMap<String, aube_resolver::DirectDepInfo> =
        std::collections::HashMap::new();

    // Captures the prewarm task's `compute_graph_hashes` output so the
    // link phase can reuse it instead of recomputing the same 4-pass
    // BLAKE3 walk over `graph.packages`. Populated by the no-lockfile
    // branch when the prewarm task uses GVS; left `None` on the
    // frozen-lockfile path or when the prewarm short-circuits.
    let mut prewarm_graph_hashes: Option<std::sync::Arc<aube_lockfile::graph_hash::GraphHashes>> =
        None;
    // The cold-install lockfile write runs on a `spawn_blocking` task so it
    // overlaps `filter_graph` + the link phase (see
    // `lockfile_write_overlap`). The handle escapes the resolve match arm
    // and is joined before `run_finalize_phase` re-reads the graph, so a
    // write error still surfaces. `None` on every path that wrote inline
    // (lockfile-matched fast path, killswitch disabled, `lockfile=false`,
    // or after the rare catch-up integrity rewrite joined it early).
    let mut lockfile_write_handle: Option<lockfile_write_overlap::LockfileWriteHandle> = None;
    let (graph, package_indices, cached_count, fetch_count) = match lockfile_result {
        Ok((mut graph, kind)) => {
            // Under `sharedWorkspaceLockfile=false` the project's own
            // lockfile only carries the `.` importer, so the reuse path
            // would hand the linker a root-only graph and never relink
            // members (a deleted/incomplete member `node_modules` would
            // be reported "up to date" yet stay broken). Fold every
            // member's per-project lockfile back in so the linker sees
            // all importers. No-op for shared lockfiles, non-workspace
            // projects, and the cold resolve path (which already
            // produces every importer).
            if !shared_workspace_lockfile && has_workspace {
                merge_member_lockfile_graphs(&cwd, &mut graph, &manifests);
            }
            let graph = resolve::apply_lockfile_graph_platform_rules(
                graph,
                kind,
                &manifest,
                &ws_config_shared,
                &settings_ctx,
            )?;
            validate_lockfile_trust_policy(
                &cwd,
                &settings_ctx,
                &graph,
                opts.network_mode,
                &dependency_policy,
            )
            .await?;
            control::check_cancelled()?;
            let source_label = resolve::lockfile_source_label(kind);
            tracing::debug!(
                "{source_label}: {} packages for {project_name}",
                graph.packages.len()
            );
            tracing::debug!(
                "phase:resolve (from lockfile) {:.1?}",
                phase_start.elapsed()
            );
            phase_timings.record("resolve", phase_start.elapsed());

            // Lockfile path: the total is known upfront, so seed the overall
            // bar with the full package count and enter the fetch phase.
            control::check_cancelled()?;
            if let Some(p) = prog_ref {
                p.set_total(graph.packages.len());
                p.set_phase("fetching");
            }
            // Seed the chain index for diagnostic enrichment on the
            // lockfile fast path. Same effect as the resolve-fresh
            // branch above — error wrappers in `dep_chain` now know
            // each package's ancestor path.
            crate::dep_chain::set_active(&graph);
            aube_registry::slow_metadata::flush_summary();

            // Post-resolve OSV `MAL-*` routing — lockfile-found
            // branch. `fresh_resolution = false` here because the
            // graph came from the lockfile and we never ran the
            // resolver, so the router falls through to the mirror
            // backend unless `osv_transitive_check` or
            // `advisoryCheckEveryInstall` forces the live API.
            // Same helper as the no-lockfile branch — kept here so
            // `aube ci`, `aube install --frozen-lockfile`, and
            // every frozen reinstall actually run the routing
            // (previously skipped, surfaced by review).
            let osv_settings = resolve_osv_routing_settings(&cwd);
            super::add_supply_chain::run_post_resolve_osv_routing(
                &cwd,
                &graph,
                /*fresh_resolution=*/ false,
                opts.osv_transitive_check,
                osv_settings.advisory_check,
                osv_settings.advisory_check_on_install,
                osv_settings.advisory_bloom_check,
                osv_settings.advisory_check_every_install,
            )
            .await?;

            // Check index cache, fetch missing tarballs. Tarball client
            // is lazy because eager construction costs ~20ms even when
            // no request gets sent, dominating no-op install time.
            //
            // Pipeline GVS materialization into the fetch tail. Same
            // shape as the no-lockfile branch. Channel feeds a
            // concurrent materializer that reflinks into GVS, hiding
            // link-step-1 cost behind the fetch tail.
            let phase_start = std::time::Instant::now();
            let network_mode = opts.network_mode;
            let cwd_for_client = cwd.clone();

            let lock_node_version = crate::engines::effective_node_version(
                aube_settings::resolved::node_version(&settings_ctx).as_deref(),
            );
            let lock_build_policy = std::sync::Arc::new(build_policy.clone());
            let lock_strategy = resolve_link_strategy(&cwd, &settings_ctx, planned_gvs)?;
            let (lock_patches, lock_patch_hashes) =
                crate::patches::load_patches_for_linker(&cwd, &graph.patched_dependencies)?;
            let (lock_materialize_tx, lock_materialize_rx) = materialize_channel();
            let lock_materialize_graph = filter_graph_for_install(
                &cwd,
                &workspace_packages,
                &graph,
                &opts,
                has_workspace && !link_all_workspace_importers,
                false,
            )?;
            let lock_prewarm_inputs = GvsPrewarmInputs {
                graph: std::sync::Arc::new(lock_materialize_graph),
                store: store.clone(),
                cwd: cwd.clone(),
                virtual_store_dir_max_length,
                link_strategy: lock_strategy,
                link_concurrency: link_concurrency_setting,
                patches: lock_patches,
                patch_hashes: lock_patch_hashes,
                node_version: lock_node_version,
                build_policy: lock_build_policy,
                use_global_virtual_store_override,
            };
            let lock_materialize_handle =
                spawn_gvs_prewarm(lock_prewarm_inputs, lock_materialize_rx);
            let lock_project_local_dep_paths = if planned_gvs {
                gvs::legacy_vite_project_local_closure(&graph)
            } else {
                Default::default()
            };

            let fetch_result = fetch_packages_with_root(
                &graph.packages,
                &store,
                || {
                    std::sync::Arc::new(
                        make_client(&cwd_for_client).with_network_mode(network_mode),
                    )
                },
                prog_ref,
                &cwd,
                &aube_dir,
                &packument_cache_dir,
                Some(lock_materialize_tx),
                /*skip_already_linked_shortcut=*/
                has_workspace || explicit_store_dir_override,
                &lock_project_local_dep_paths,
                virtual_store_dir_max_length,
                opts.ignore_scripts,
                network_concurrency_setting,
                verify_store_integrity_setting,
                strict_store_integrity_setting,
                strict_store_pkg_content_check_setting,
                opts.git_prepare_depth,
                inherited_build_policy_for_git_prepare.clone(),
                resolve_git_shallow_hosts(&settings_ctx),
            )
            .await;
            // Don't abort the materializer on fetch err: the failing
            // fetch task drops its `tx`, so the materializer's `rx`
            // closes and it exits naturally. Awaiting first lets a real
            // materializer error (the likely root cause of a generic
            // "materializer task exited..." fetch err) surface instead.
            let (indices, cached, fetched, _) = match fetch_result {
                Ok(t) => t,
                Err(e) => {
                    return Err(combine_install_pipeline_errors(lock_materialize_handle, e).await);
                }
            };
            // Materializer stats roll into link via GVS-already-linked
            // fast path. Errors abort install.
            let _ = lock_materialize_handle.await.into_diagnostic()??;
            tracing::debug!(
                "phase:fetch {:.1?} ({fetched} packages)",
                phase_start.elapsed()
            );
            phase_timings.record("fetch", phase_start.elapsed());

            (graph, indices, cached, fetched)
        }
        Err(aube_lockfile::Error::NotFound(_))
            if !(matches!(mode, FrozenMode::Frozen) && opts.strict_no_lockfile) =>
        {
            // No lockfile — resolve + fetch tarballs concurrently
            tracing::debug!("No lockfile found, resolving dependencies for {project_name}...");
            control::check_cancelled()?;
            if let Some(p) = prog_ref {
                // Seed the resolving-phase denominator floor from any
                // existing lockfile on disk. In FrozenMode::Fix /
                // Prefer we already parsed it into
                // `existing_for_resolver`; in FrozenMode::No the
                // pre-parse is skipped (we always re-resolve), so peek
                // the disk lockfile inline. The cost is one extra
                // parse on the fresh-resolve path, dwarfed by the
                // resolve itself — and the resulting estimate lets
                // the resolving bar show real progress instead of an
                // empty placeholder.
                let lockfile_estimate =
                    existing_for_resolver.map(|g| g.packages.len()).or_else(|| {
                        parse_lockfile_dir_remapped_with_kind_and_options(
                            &lockfile_dir,
                            &lockfile_importer_key,
                            &manifest,
                            lockfile_parse_options,
                        )
                        .ok()
                        .map(|(g, _)| g.packages.len())
                    });
                if let Some(n) = lockfile_estimate {
                    p.set_total_floor(n);
                }
                p.set_phase("resolving");
            }
            // Resolve node version + build policy up front so the
            // GVS-prewarm materializer (spawned below the resolver
            // await) can compute the same graph hashes the link phase
            // will. Keeping a single source of truth avoids any
            // subdir-name drift between prewarm and link step 1.
            let node_version_for_prewarm = crate::engines::effective_node_version(
                aube_settings::resolved::node_version(&settings_ctx).as_deref(),
            );
            let build_policy_for_prewarm = std::sync::Arc::new(build_policy.clone());
            let client =
                std::sync::Arc::new(make_client(&cwd).with_network_mode(opts.network_mode));
            // Speculative TLS + TCP + HTTP/2 handshake. Fires while the
            // rest of this function builds the resolver, parses the
            // manifest, and reads the lockfile. By the time the
            // resolver requests its first packument the connection
            // pool is already warm, hiding ~50-150 ms of handshake on
            // cold installs. `AUBE_DISABLE_SPECULATIVE_TLS=1` opts
            // out.
            client.prewarm_connection();
            let tarball_client = client.clone();

            // Set up streaming resolver with disk-backed packument cache.
            // Resolver options are applied via `configure_resolver` so the
            // `--lockfile-only` short-circuit produces an identical lockfile.
            // `AUBE_CONCURRENCY` is an emergency override for users on slow
            // private registries (Artifactory, Nexus) where the default
            // 128 in-flight tarballs trigger 429/503 throttling. Honored
            // ahead of `network_concurrency_setting` so the env var wins
            // over npmrc + workspace yaml.
            let env_concurrency =
                aube_util::concurrency::parse_concurrency_env().map(|n| n as usize);
            let fetch_network_concurrency = env_concurrency
                .or(network_concurrency_setting)
                .unwrap_or_else(default_streaming_network_concurrency);
            // Channel capacity is decoupled from fetch concurrency: the
            // mpsc just buffers ResolvedPackage handoffs so the BFS
            // never blocks on send() while the fetch coordinator is
            // mid-tarball. Sized to absorb deep-tree bursts without
            // backpressure on graphs into the tens of thousands of
            // packages; fetch parallelism is still gated by
            // `fetch_network_concurrency` downstream.
            let stream_capacity = fetch_network_concurrency.saturating_mul(16).max(1024);
            let (resolver, mut resolved_rx) =
                aube_resolver::Resolver::with_stream_capacity(client, stream_capacity);
            let pnpmfile_paths = if opts.ignore_pnpmfile {
                Vec::new()
            } else {
                crate::pnpmfile::ordered_paths(
                    crate::pnpmfile::detect_global(&cwd, opts.global_pnpmfile.as_deref())
                        .as_deref(),
                    crate::pnpmfile::detect(
                        &cwd,
                        opts.pnpmfile.as_deref(),
                        ws_config_shared.pnpmfile_path.as_deref(),
                    )
                    .as_deref(),
                )
            };
            super::run_pnpmfile_pre_resolution(&pnpmfile_paths, &cwd, existing_for_resolver)
                .await?;
            control::check_cancelled()?;
            let (read_package_host, read_package_forwarders) =
                match crate::pnpmfile::ReadPackageHostChain::spawn(&pnpmfile_paths, &cwd)
                    .await
                    .wrap_err("failed to start pnpmfile readPackage host")?
                {
                    Some((h, f)) => (Some(h), f),
                    None => (None, Vec::new()),
                };
            let read_package_hook: Option<Box<dyn aube_resolver::ReadPackageHook>> =
                read_package_host.map(|h| Box::new(h) as Box<dyn aube_resolver::ReadPackageHook>);
            let mut resolver = configure_resolver(
                resolver,
                &cwd,
                &manifest,
                ResolverConfigInputs {
                    settings_ctx: &settings_ctx,
                    workspace_config: &ws_config_shared,
                    workspace_catalogs: &workspace_catalogs,
                    minimum_release_age_override: opts.minimum_release_age_override,
                    // Same disambiguation as the `--lockfile-only` path:
                    // `None` only when no lockfile will be written, so
                    // widening to every common platform doesn't happen
                    // just to be discarded.
                    target_lockfile_kind: lockfile_enabled
                        .then(|| source_kind_before.unwrap_or(aube_lockfile::LockfileKind::Aube)),
                    dependency_policy: Some(dependency_policy.clone()),
                    cache_full_packuments: true,
                    ignore_scripts: opts.ignore_scripts,
                },
                read_package_hook,
            );

            // Spawn the tarball fetch coordinator — it starts fetching as
            // packages arrive from the resolver, overlapping network I/O.
            // Clone the registry client up front so the post-fetch
            // lockfile-write step (below) can still use it to derive
            // tarball URLs when `lockfileIncludeTarballUrl=true` — the
            // `tokio::spawn` below moves one clone into the fetch
            // coordinator's task.
            let post_fetch_client = tarball_client.clone();
            let fetch_store = store.clone();
            let fetch_progress = prog.clone();
            let fetch_project_root = cwd.clone();
            let fetch_local_client = tarball_client.clone();
            let fetch_ignore_scripts = opts.ignore_scripts;
            let fetch_git_prepare_depth = opts.git_prepare_depth;
            let fetch_inherited_build_policy = inherited_build_policy_for_git_prepare.clone();
            let fetch_verify_integrity = verify_store_integrity_setting;
            let fetch_strict_integrity = strict_store_integrity_setting;
            let fetch_strict_pkg_content_check = strict_store_pkg_content_check_setting;
            let fetch_git_shallow_hosts = resolve_git_shallow_hosts(&settings_ctx);
            // Host-side platform filter for the streaming fetch. The
            // resolver widens its graph filter for aube-lock.yaml so
            // the committed lockfile carries native optionals for every
            // common platform, but that widening mustn't make us
            // download every foreign-platform tarball up front — most
            // of them will disappear when `filter_graph` trims optional
            // edges below, and only a vanishingly rare broken-package
            // shape (required dep with platform constraints) actually
            // needs the fetch. A post-resolve catch-up pass picks up
            // those stragglers from the finalized graph; here we just
            // defer. `filter_graph` keys off the same narrow manifest
            // set, so a deferred package that survives the trim is
            // exactly one the catch-up must fetch.
            let (fetch_sup_os, fetch_sup_cpu, fetch_sup_libc) =
                aube_manifest::effective_supported_architectures(&manifest, &ws_config_shared);
            let fetch_supported_arch = aube_resolver::SupportedArchitectures {
                os: fetch_sup_os,
                cpu: fetch_sup_cpu,
                libc: fetch_sup_libc,
                ..Default::default()
            };
            // Each imported (dep_path, index) feeds the GVS-prewarm
            // materializer running concurrently with the rest of fetch.
            /*
             * Materialize channel sized from the cross run learned
             * recommendation when available, falling back to the
             * static default. Tokio mpsc cap is fixed at
             * construction so the only knob we can turn here is
             * the initial size for this process. Bounds 256 to
             * 16384 cap RAM and floor progress.
             */
            let (materialize_tx, materialize_rx) = materialize_channel();
            // Clone the shared deprecations accumulator into the
            // spawned task. The install command reads it back after
            // `filter_graph` prunes the post-resolve graph.
            let fetch_deprecations_tx = deprecations.clone();
            let fetch = Box::pin(async move {
                /*
                 * Adaptive tarball concurrency. Loaded from the
                 * cross run persistent store when available so the
                 * limiter starts where a previous run converged
                 * instead of cold ramping from the ceiling. Falls
                 * back to seed 256 (h2 stream cap) on first ever
                 * run. Floor 4 keeps progress under continuous
                 * 429 / 503. Persisted back at end of fetch phase
                 * so the next invocation benefits.
                 */
                // Honor user-configured `networkConcurrency` (or
                // `AUBE_NETWORK_CONCURRENCY` env override) as the
                // seed. Adaptive grow/shrink still operate around
                // it. Floor 4 keeps progress under continuous
                // throttling regardless of seed.
                let tarball_seed = fetch_network_concurrency.max(4);
                let tarball_max = tarball_seed.max(256);
                let persistent = aube_util::adaptive::global_persistent_state();
                let semaphore = match persistent.as_ref() {
                    Some(state) => aube_util::adaptive::AdaptiveLimit::from_persistent(
                        state,
                        "tarball:default",
                        tarball_seed,
                        4,
                        tarball_max,
                    ),
                    None => aube_util::adaptive::AdaptiveLimit::new(tarball_seed, 4, tarball_max),
                };
                let semaphore_for_persist = std::sync::Arc::clone(&semaphore);
                let persistent_for_save = persistent.clone();
                // Hoist env-driven flags out of the per-tarball loop.
                let streaming_sha512_enabled =
                    aube_util::env::embedder_env("DISABLE_STREAMING_SHA512").is_none();
                let tarball_stream_enabled =
                    aube_util::env::embedder_env("DISABLE_TARBALL_STREAM").is_none();
                // JoinSet over bare Vec<JoinHandle>. If the first
                // fetch errors and we return via `?`, a plain Vec
                // drops the remaining JoinHandles which detaches the
                // tasks. They keep fetching tarballs and writing
                // to the CAS while the CLI has already errored.
                // JoinSet aborts every outstanding task on drop,
                // matches the pattern ensure_dep_scripts uses.
                let mut handles: tokio::task::JoinSet<
                    miette::Result<(String, aube_store::PackageIndex, Option<String>)>,
                > = tokio::task::JoinSet::new();
                let mut indices: BTreeMap<String, aube_store::PackageIndex> = BTreeMap::new();
                let mut cached_count = 0usize;
                // Drives the resolving-phase denominator estimate.
                // `received + pkg.pending` is a non-strict lower bound
                // on the final resolved-package count; raising it via
                // `set_total_floor` makes the bar fill as the
                // BFS-frontier high-water mark grows. Tracked locally
                // because the resolver's view is per-send, not a
                // single shared atomic.
                let mut resolved_received: usize = 0;

                while let Some(pkg) = resolved_rx.recv().await {
                    if let Some(ref msg) = pkg.deprecated {
                        fetch_deprecations_tx.lock().unwrap().push(
                            crate::deprecations::DeprecationRecord {
                                name: pkg.name.clone(),
                                version: pkg.version.clone(),
                                dep_path: pkg.dep_path.clone(),
                                message: msg.clone(),
                            },
                        );
                    }
                    // Each resolved package bumps the overall denominator by
                    // one. Cached packages are immediately credited against
                    // the numerator; missing ones get a transient child row.
                    //
                    // Bumping the denominator *before* the platform-deferred
                    // skip below is intentional: the catch-up pass (after
                    // `filter_graph`) credits surviving deferred packages
                    // against the numerator, and skipping the increment
                    // here would let the numerator overrun the denominator
                    // (the historical "2/1 packages" display bug). The
                    // overcount on dropped optionals is reconciled by a
                    // single `set_total(graph.packages.len())` after
                    // `filter_graph` runs.
                    resolved_received += 1;
                    if let Some(p) = fetch_progress.as_ref() {
                        p.inc_total(1);
                        // Raise the resolving-phase denominator floor
                        // toward the resolver's current frontier so
                        // the bar fills against a meaningful target
                        // instead of an empty placeholder. Stamping
                        // the frontier on each `ResolvedPackage`
                        // keeps the protocol shape unchanged.
                        p.set_total_floor(resolved_received + pkg.pending);
                        if let Some(sz) = pkg.unpacked_size {
                            p.inc_estimated_bytes(&pkg.dep_path, sz);
                        }
                    }

                    // Defer platform-mismatched registry packages to
                    // the post-filter_graph catch-up pass: almost all
                    // of them are optional natives that `filter_graph`
                    // is about to drop, so fetching up front would just
                    // waste bandwidth. Local `file:`/`link:` deps
                    // always fetch here — they carry empty platform
                    // arrays and `is_supported` treats them as
                    // unconstrained.
                    if pkg.local_source.is_none()
                        && !aube_resolver::is_supported(
                            &pkg.os,
                            &pkg.cpu,
                            &pkg.libc,
                            &fetch_supported_arch,
                        )
                    {
                        tracing::debug!(
                            "deferring tarball fetch for {}@{}: platform mismatch (catch-up will cover survivors)",
                            pkg.name,
                            pkg.version
                        );
                        continue;
                    }

                    // Local (`file:` / `link:`) deps materialize from
                    // disk, not the registry — short-circuit the
                    // tarball pipeline.
                    if let Some(ref local) = pkg.local_source {
                        match import_local_source(
                            &fetch_store,
                            &fetch_project_root,
                            local,
                            Some(&fetch_local_client),
                            fetch_ignore_scripts,
                            fetch_git_prepare_depth,
                            fetch_inherited_build_policy.clone(),
                            &fetch_git_shallow_hosts,
                            &pkg.name,
                            &pkg.version,
                        )
                        .await
                        {
                            Ok(Some(index)) => {
                                // Send failure means the materializer
                                // task died. Bail now instead of
                                // continuing to import tarballs into a
                                // half-wired virtual store.
                                materialize_tx
                                    .send((pkg.dep_path.clone(), index.clone()))
                                    .await
                                    .map_err(|_| {
                                        miette!("materializer task exited before fetch finished")
                                    })?;
                                indices.insert(pkg.dep_path, index);
                                cached_count += 1;
                                if let Some(p) = fetch_progress.as_ref() {
                                    p.inc_reused(1);
                                }
                            }
                            Ok(None) => {
                                if let Some(p) = fetch_progress.as_ref() {
                                    p.inc_reused(1);
                                }
                            }
                            Err(e) => return Err(e),
                        }
                        continue;
                    }

                    // Check index cache first. `registry_name()` is
                    // the real package name on the registry — equal
                    // to `name` for the common case, and the alias's
                    // real target for npm-alias entries (where the
                    // alias-qualified name would miss the cache and
                    // later 404 the tarball fetch). Integrity is part
                    // of the cache key so a github-sourced tarball
                    // under the same (name, version) can't return the
                    // registry-cached file list.
                    //
                    // `_verified`: see the matching call in
                    // `fetch_packages_with_root` for the full
                    // rationale — short version, a stat-per-file cache
                    // check is cheap, and dropping a stale index
                    // here re-fetches the tarball cleanly instead of
                    // letting the materializer die later with
                    // `ERR_AUBE_MISSING_STORE_FILE`.
                    let pkg_registry_name = pkg.registry_name().to_string();
                    if let Some(index) = fetch_store.load_index_verified(
                        &pkg_registry_name,
                        &pkg.version,
                        pkg.integrity.as_deref(),
                    ) {
                        materialize_tx
                            .send((pkg.dep_path.clone(), index.clone()))
                            .await
                            .map_err(|_| {
                                miette!("materializer task exited before fetch finished")
                            })?;
                        indices.insert(pkg.dep_path, index);
                        cached_count += 1;
                        if let Some(p) = fetch_progress.as_ref() {
                            p.inc_reused(1);
                        }
                        continue;
                    }

                    let sem = semaphore.clone();
                    let store = fetch_store.clone();
                    let client = tarball_client.clone();
                    let row = fetch_progress
                        .as_ref()
                        .map(|p| p.start_fetch(&pkg.name, &pkg.version));
                    let bytes_progress = fetch_progress.clone();

                    handles.spawn(crate::dep_chain::scope_current(async move {
                        let _row = row;
                        let _diag_tar = aube_util::diag::Span::new(aube_util::diag::Category::Fetch, "tarball")
                            .with_meta_fn(|| format!(r#"{{"name":{},"version":{}}}"#,
                                aube_util::diag::jstr(&pkg.name), aube_util::diag::jstr(&pkg.version)));
                        let _diag_tar_inflight = aube_util::diag::inflight(aube_util::diag::Slot::Tar);
                        let permit_wait = std::time::Instant::now();
                        let permit = sem.acquire().await;
                        let permit_wait_ms = permit_wait.elapsed();
                        let pkg_id_for_diag = format!("{}@{}", pkg.name, pkg.version);
                        if permit_wait_ms.as_millis() > 1 {
                            aube_util::diag::event_lazy(aube_util::diag::Category::Fetch, "tarball_permit_wait", permit_wait_ms, || format!(r#"{{"name":{}}}"#, aube_util::diag::jstr(&pkg.name)));
                        }
                        aube_util::diag::attribute_wait(
                            aube_util::diag::Slot::Tar,
                            &pkg_id_for_diag,
                            permit_wait_ms,
                        );
                        let _tar_holder = aube_util::diag::register_holder(
                            aube_util::diag::Slot::Tar,
                            &pkg_id_for_diag,
                        );
                        let url = pkg.tarball_url.clone().unwrap_or_else(|| {
                            client.tarball_url(&pkg_registry_name, &pkg.version)
                        });

                        tracing::trace!("Fetching {}@{}", pkg.name, pkg.version);

                        let pkg_display_name = pkg.name.clone();
                        let pkg_version = pkg.version.clone();
                        let dep_path = pkg.dep_path.clone();
                        let integrity = pkg.integrity.clone();

                        let stream_eligible = tarball_stream_enabled
                            && integrity
                                .as_deref()
                                .is_none_or(|s| s.starts_with("sha512-"));
                        aube_util::diag::instant_lazy(aube_util::diag::Category::Fetch, "tarball_path", || format!(r#"{{"streaming":{},"name":{}}}"#, stream_eligible, aube_util::diag::jstr(&pkg.name)));
                        if stream_eligible {
                            let streamed = crate::commands::install::lifecycle::fetch_and_import_tarball_streaming(
                                &client,
                                &store,
                                &url,
                                &pkg_display_name,
                                &pkg_registry_name,
                                &pkg_version,
                                integrity.as_deref(),
                                fetch_verify_integrity,
                                fetch_strict_integrity,
                                fetch_strict_pkg_content_check,
                            )
                            .await;
                            let (index, bytes_len, computed_integrity) = match streamed {
                                Ok(v) => {
                                    permit.record_success();
                                    v
                                }
                                Err(e) => {
                                    if e.is_throttle {
                                        permit.record_throttle();
                                    } else {
                                        permit.record_cancelled();
                                    }
                                    return Err(e.into());
                                }
                            };
                            if let Some(p) = bytes_progress.as_ref() {
                                p.inc_downloaded_bytes(bytes_len);
                            }
                            return Ok::<_, miette::Report>((
                                dep_path,
                                index,
                                computed_integrity,
                            ));
                        }

                        let fetch_outcome = if streaming_sha512_enabled {
                            client
                                .fetch_tarball_bytes_streaming_sha512(&url)
                                .await
                                .map(|(b, d)| (b, Some(d)))
                                .map_err(|e| {
                                    let throttled = e.is_throttle();
                                    (
                                        miette!(
                                            "failed to fetch {}@{}: {e}{}",
                                            pkg.name,
                                            pkg.version,
                                            crate::dep_chain::format_chain_for(&pkg.name, &pkg.version)
                                        ),
                                        throttled,
                                    )
                                })
                        } else {
                            client.fetch_tarball_bytes(&url).await.map(|b| (b, None)).map_err(|e| {
                                let throttled = e.is_throttle();
                                (
                                    miette!(
                                        "failed to fetch {}@{}: {e}{}",
                                        pkg.name,
                                        pkg.version,
                                        crate::dep_chain::format_chain_for(&pkg.name, &pkg.version)
                                    ),
                                    throttled,
                                )
                            })
                        };
                        let (bytes, streamed_digest) = match fetch_outcome {
                            Ok(v) => {
                                permit.record_success();
                                v
                            }
                            Err((report, throttled)) => {
                                if throttled {
                                    permit.record_throttle();
                                } else {
                                    permit.record_cancelled();
                                }
                                return Err(report);
                            }
                        };
                        if let Some(p) = bytes_progress.as_ref() {
                            p.inc_downloaded_bytes(bytes.len() as u64);
                        }

                        let computed_integrity = integrity
                            .is_none()
                            .then(|| match streamed_digest.as_ref() {
                                Some(digest) => aube_store::sha512_integrity_from_digest(digest),
                                None => aube_store::sha512_integrity(&bytes),
                            });
                        let (index, _) = run_import_on_blocking(
                            store.clone(),
                            bytes,
                            streamed_digest,
                            pkg_display_name.clone(),
                            pkg_registry_name.clone(),
                            pkg_version.clone(),
                            integrity.clone(),
                            fetch_verify_integrity,
                            fetch_strict_integrity,
                            fetch_strict_pkg_content_check,
                        )
                        .await?;
                        if let Some(integrity) = computed_integrity.as_deref()
                            && let Err(e) =
                                store.save_index(&pkg_registry_name, &pkg_version, Some(integrity), &index)
                        {
                            tracing::warn!(
                                code = aube_codes::warnings::WARN_AUBE_CACHE_WRITE_FAILED,
                                "Failed to cache index for {}@{} with computed integrity: {e}",
                                pkg_display_name,
                                pkg_version
                            );
                        }

                        Ok::<_, miette::Report>((dep_path, index, computed_integrity))
                    }));
                }

                // Collect all fetch results via JoinSet. Drop on
                // error aborts outstanding siblings.
                let fetch_count = handles.len();
                let mut computed_integrities: BTreeMap<String, String> = BTreeMap::new();
                while let Some(joined) = handles.join_next().await {
                    let (dep_path, index, computed_integrity) = joined.into_diagnostic()??;
                    materialize_tx
                        .send((dep_path.clone(), index.clone()))
                        .await
                        .map_err(|_| miette!("materializer task exited before fetch finished"))?;
                    if let Some(integrity) = computed_integrity {
                        computed_integrities
                            .insert(strip_peer_context_suffix(&dep_path).to_owned(), integrity);
                    }
                    indices.insert(dep_path, index);
                }
                // Explicitly drop the materialize sender so the
                // materializer consumer sees the channel close and
                // exits its receive loop.
                drop(materialize_tx);
                if let Some(state) = persistent_for_save.as_ref() {
                    semaphore_for_persist.persist(state, "tarball:default");
                }
                Ok::<_, miette::Report>((indices, cached_count, fetch_count, computed_integrities))
            });
            let fetch = crate::runtime::scope_current(fetch);
            let fetch = aube_scripts::scope_current(fetch);
            let fetch_handle = tokio::spawn(fetch);

            // Run resolution (this streams packages to the fetch coordinator).
            // `existing_for_resolver` is `Some` when Fix / Prefer parsed a
            // lockfile cleanly; the resolver reuses already-pinned versions
            // for unchanged specs and only re-resolves entries whose spec
            // drifted. `No` mode (`--no-frozen-lockfile`) intentionally
            // stays at `None` so the user gets the fresh resolve they
            // asked for.
            aube_util::diag::instant(aube_util::diag::Category::Install, "resolve_begin", None);
            let _diag_resolve =
                aube_util::diag::Span::new(aube_util::diag::Category::Install, "phase_resolve");
            let resolve_result = if has_workspace {
                resolver
                    .resolve_workspace(&manifests, existing_for_resolver, &ws_package_versions)
                    .await
            } else {
                resolver.resolve(&manifest, existing_for_resolver).await
            }
            .map_err(miette::Report::new)
            .wrap_err("failed to resolve dependencies");

            if resolve_result.is_err() {
                fetch_handle.abort();
                return resolve_result.map(|_| unreachable!());
            }
            let mut graph = resolve_result.unwrap();
            // Snapshot per-direct-dep packument facts before dropping the
            // resolver — its `cache` field owns the only copy and the
            // install summary printer runs much later, well after the
            // channel-closing drop below.
            direct_dep_info = resolver.direct_dep_info(&graph);
            // Drop the resolver to close the channel, signaling the fetch
            // coordinator to finish, then drain the readPackage stderr
            // forwarders so every `ctx.log` record from resolve flushes
            // to stdout before afterAllResolved emits its own pnpm:hook
            // records. Doing this in the order drop → drain → hook keeps
            // resolve-time logs strictly ahead of afterAllResolved-time
            // logs in the ndjson stream.
            drop(resolver);
            crate::pnpmfile::ReadPackageHostChain::drain_forwarders(read_package_forwarders).await;
            crate::pnpmfile::run_after_all_resolved_chain(&pnpmfile_paths, &cwd, &mut graph)
                .await?;
            // Overlay per-package metadata the resolver can't recover
            // from abbreviated (corgi) packuments — `license`,
            // `funding_url`, bun's `configVersion` — from the
            // existing lockfile when one was on disk. Without this,
            // `aube install --no-frozen-lockfile` drops those fields
            // on every re-resolve even though the resolved versions
            // didn't change, which churns the lockfile diff against
            // formats (npm, bun) that preserve them.
            // Reuse the pre-parsed lockfile when the resolver already
            // loaded it for seeding (Fix/Prefer modes). Skips a second
            // YAML parse pass over the same 5-50 KB file.
            if let Some((prior, _)) = lockfile_pre_parse.as_ref() {
                graph.overlay_metadata_from(prior);
            } else if let Ok((prior, _)) = parse_lockfile_dir_remapped_with_kind_and_options(
                &lockfile_dir,
                &lockfile_importer_key,
                &manifest,
                lockfile_parse_options,
            ) {
                graph.overlay_metadata_from(&prior);
            }
            // A pnpm lockfile's patchedDependencies block describes the
            // resolution that produced that lockfile; it is not authoritative
            // after manifest/workspace drift forced a fresh resolve. Replace
            // the metadata overlaid above with the current declarations so a
            // deleted patch from the stale lockfile is neither read during
            // materialization nor written back. This also prevents pnpm 11's
            // hash-only scalar entries from being mistaken for file paths.
            if matches!(source_kind_before, Some(aube_lockfile::LockfileKind::Pnpm)) {
                graph.patched_dependencies = crate::patches::read_patched_dependencies(&cwd)?;
            }
            tracing::debug!("Resolved {} packages", graph.packages.len());
            // Seed the chain index for diagnostic enrichment. Any
            // post-resolver error wrapping `(name, version)` via
            // `crate::dep_chain::format_chain_for` now sees a
            // chain back to the importer.
            crate::dep_chain::set_active(&graph);
            aube_registry::slow_metadata::flush_summary();

            // Post-resolve OSV `MAL-*` routing — no-lockfile /
            // re-resolve branch. The lockfile-found branch has the
            // parallel call before its own fetch so both paths
            // run through the same router. See
            // `add_supply_chain::run_post_resolve_osv_routing` for
            // the decision table. Fires before the pluggable
            // scanner so a confirmed-malicious advisory aborts
            // without spawning the scanner.
            let prior_lockfile = lockfile_pre_parse.as_ref().map(|(g, _)| g);
            let fresh_resolution =
                super::add_supply_chain::lockfile_has_new_picks(&cwd, prior_lockfile, &graph);
            let osv_settings = resolve_osv_routing_settings(&cwd);
            super::add_supply_chain::run_post_resolve_osv_routing(
                &cwd,
                &graph,
                fresh_resolution,
                opts.osv_transitive_check,
                osv_settings.advisory_check,
                osv_settings.advisory_check_on_install,
                osv_settings.advisory_bloom_check,
                osv_settings.advisory_check_every_install,
            )
            .await?;
            control::check_cancelled()?;

            // Bun-compatible security scanner runs against the
            // *resolved* graph — full transitive set with concrete
            // versions, matching Bun's contract. Fires before fetch
            // so a `fatal` advisory aborts without wasting bandwidth
            // on tarball downloads. Fail-closed on any subprocess
            // failure (see `commands::security_scanner`); empty
            // `securityScanner` (the default) short-circuits to a
            // no-op without spawning `node`.
            let scanner = super::with_settings_ctx(&cwd, aube_settings::resolved::security_scanner);
            if !scanner.is_empty() {
                let scanner_packages =
                    super::security_scanner::resolved_packages_for_scanner(&graph);
                super::security_scanner::run_scanner(&scanner, &cwd, &scanner_packages).await?;
            }

            control::check_cancelled()?;
            if let Some(p) = prog_ref {
                p.set_phase("fetching");
            }
            tracing::debug!("phase:resolve (fresh) {:.1?}", phase_start.elapsed());
            phase_timings.record("resolve", phase_start.elapsed());
            drop(_diag_resolve);
            aube_util::diag::instant(aube_util::diag::Category::Install, "resolve_end", None);

            // fetch_handle streams imported (dep_path, index) tuples
            // into the materializer, which reflinks each into
            // ~/.cache/aube/virtual-store. Used to run serially after
            // fetch as link step 1. Now overlaps with in-flight
            // downloads and post-resolve bookkeeping. Link step 1
            // below hits pkg_nm_dir.exists() fast path and only writes
            // the per-project .aube/<dep_path> symlink.
            let materialize_phase_start = std::time::Instant::now();
            let materialize_graph_arc = std::sync::Arc::new(filter_graph_for_install(
                &cwd,
                &workspace_packages,
                &graph,
                &opts,
                has_workspace && !link_all_workspace_importers,
                false,
            )?);
            let materialize_strategy = resolve_link_strategy(&cwd, &settings_ctx, planned_gvs)?;
            let (materialize_patches, materialize_patch_hashes) =
                crate::patches::load_patches_for_linker(&cwd, &graph.patched_dependencies)?;
            let materialize_inputs = GvsPrewarmInputs {
                graph: materialize_graph_arc.clone(),
                store: store.clone(),
                cwd: cwd.clone(),
                virtual_store_dir_max_length,
                link_strategy: materialize_strategy,
                link_concurrency: link_concurrency_setting,
                patches: materialize_patches,
                patch_hashes: materialize_patch_hashes,
                node_version: node_version_for_prewarm.clone(),
                build_policy: build_policy_for_prewarm.clone(),
                use_global_virtual_store_override,
            };
            aube_util::diag::instant(
                aube_util::diag::Category::Install,
                "materialize_spawn",
                None,
            );
            let materialize_handle = spawn_gvs_prewarm(materialize_inputs, materialize_rx);

            // On fetch err, await the materializer (don't abort): the
            // failing fetch task drops its `tx`, so the materializer's
            // `rx` closes and it exits naturally. Awaiting first lets a
            // real materializer error (the likely root cause of a
            // generic "materializer task exited..." fetch err) surface
            // instead.
            let _diag_fetch_wait =
                aube_util::diag::Span::new(aube_util::diag::Category::Install, "phase_fetch_await");
            let fetch_phase_start = std::time::Instant::now();
            let fetch_result = match fetch_handle.await.into_diagnostic()? {
                Ok(v) => v,
                Err(e) => {
                    return Err(combine_install_pipeline_errors(materialize_handle, e).await);
                }
            };
            let (canonical_indices, mut cached, mut fetched, computed_integrities) = fetch_result;
            tracing::debug!(
                "phase:fetch {:.1?} ({fetched} packages, {cached} cached)",
                fetch_phase_start.elapsed()
            );
            phase_timings.record("fetch", fetch_phase_start.elapsed());
            drop(_diag_fetch_wait);
            aube_util::diag::instant(aube_util::diag::Category::Install, "fetch_await_end", None);
            // Drain the materializer; its stats get rolled into the
            // final link stats below. Errors abort the install just like
            // a failing link phase would.
            let _diag_mat_wait = aube_util::diag::Span::new(
                aube_util::diag::Category::Install,
                "phase_materialize_await",
            );
            let (prewarm_stats, prewarm_hashes_from_task) =
                materialize_handle.await.into_diagnostic()??;
            drop(_diag_mat_wait);
            aube_util::diag::instant(
                aube_util::diag::Category::Install,
                "materialize_await_end",
                None,
            );
            prewarm_graph_hashes = prewarm_hashes_from_task;
            tracing::debug!(
                "phase:prewarm-gvs {:.1?} ({} packages, {} files)",
                materialize_phase_start.elapsed(),
                prewarm_stats.packages_linked,
                prewarm_stats.files_linked,
            );
            phase_timings.record("prewarm_gvs", materialize_phase_start.elapsed());

            // The fetch coordinator streamed `ResolvedPackage`s from the
            // resolver's *first pass*, which uses canonical `name@version`
            // dep_paths. After the resolver's peer-context post-pass, the
            // graph has contextualized dep_paths — same underlying files,
            // but the indices map needs to be re-keyed to match so the
            // linker can find each variant by the dep_path on its
            // `LockedPackage`. Multiple contextualized variants of the
            // same canonical package share a single set of files, so
            // cloning the PackageIndex is cheap relative to re-extraction.
            let mut indices = remap_indices_to_contextualized(&canonical_indices, &graph);
            apply_computed_integrities(&mut graph, &computed_integrities);

            // Write the lockfile in whatever format the project was
            // already using. If no lockfile existed, create aube's
            // default `aube-lock.yaml`. Skipped entirely when
            // `lockfile=false`.
            let write_kind = source_kind_before.unwrap_or(aube_lockfile::LockfileKind::Aube);
            if lockfile_enabled {
                // When `lockfileIncludeTarballUrl=true`, record the
                // registry tarball URL on every registry-sourced
                // package so the writer can embed it in
                // `resolution.tarball:`. The client's `tarball_url`
                // helper honors per-scope registry overrides read
                // from `.npmrc`, so a `@mycorp:registry=...` override
                // still routes scoped packages through the right host.
                // Non-registry packages (local_source Some) already
                // carry their own URL and are left alone.
                if lockfile_include_tarball_url {
                    graph.settings.lockfile_include_tarball_url = true;
                    for pkg in graph.packages.values_mut() {
                        if pkg.local_source.is_some() {
                            continue;
                        }
                        // Preserve any URL already present — the npm
                        // lockfile reader stashes the `resolved:` URL
                        // for aliased entries at parse time because
                        // `(alias, version)` doesn't resolve against
                        // the registry.
                        if pkg.tarball_url.is_none() {
                            pkg.tarball_url = Some(
                                post_fetch_client.tarball_url(pkg.registry_name(), &pkg.version),
                            );
                        }
                    }
                }
                // Record/refresh the devEngines runtime pin before the
                // graph hits disk (pnpm 10.14+ parity).
                crate::runtime::refresh_lockfile_pin(
                    &mut graph,
                    &manifest,
                    crate::runtime::RuntimeSettings::from_ctx(&settings_ctx),
                    write_kind,
                )
                .await?;
                // Record pnpm's config checksums (pnpm-lock.yaml only) so
                // the written lockfile carries the same drift markers pnpm
                // would. Resolve the local pnpmfile here where `opts` /
                // `ws_config_shared` live; the helper skips non-pnpm formats.
                let local_pnpmfile = if opts.ignore_pnpmfile {
                    None
                } else {
                    crate::pnpmfile::detect(
                        &cwd,
                        opts.pnpmfile.as_deref(),
                        ws_config_shared.pnpmfile_path.as_deref(),
                    )
                };
                settings::stamp_pnpm_config_checksums(
                    &mut graph,
                    write_kind,
                    &manifest,
                    &settings_ctx,
                    local_pnpmfile.as_deref(),
                )
                .await;
                // Annotate the full (pre-host-filter) graph with pnpm-parity
                // snapshot metadata (`optional: true`, `transitivePeerDependencies`)
                // before the write and before the host-only `filter_graph` below.
                crate::commands::prepare_resolved_graph_for_lockfile_write(&mut graph);
                // The serialize + reformat + atomic write is the slowest
                // serial span before the linker (10-55 ms on large trees).
                // When the overlap is on, hand it a clone of the prepared
                // graph and run it on a blocking thread so it overlaps
                // `filter_graph` + the link phase; the handle is joined
                // before `run_finalize_phase`.
                // `AUBE_DISABLE_LOCKFILE_WRITE_OVERLAP=1` reverts to the
                // inline serial write — byte-identical output, same error
                // point, and no graph clone (exactly the pre-overlap cost).
                if lockfile_write_overlap::overlap_enabled() {
                    let write_inputs = lockfile_write_overlap::LockfileWriteInputs {
                        graph: graph.clone(),
                        manifest: manifest.clone(),
                        manifests: manifests.clone(),
                        lockfile_dir: lockfile_dir.clone(),
                        lockfile_importer_key: lockfile_importer_key.clone(),
                        cwd: cwd.clone(),
                        write_kind,
                        shared_workspace_lockfile,
                        has_workspace,
                        per_project_write_selection: per_project_write_selection.clone(),
                    };
                    lockfile_write_handle = Some(lockfile_write_overlap::spawn(write_inputs));
                } else {
                    // Killswitch-disabled inline write: borrow the call-site
                    // values directly (no graph clone — exactly the pre-overlap
                    // cost), same error point.
                    lockfile_write_overlap::write_one(
                        &graph,
                        &manifest,
                        &manifests,
                        &lockfile_dir,
                        &lockfile_importer_key,
                        &cwd,
                        write_kind,
                        shared_workspace_lockfile,
                        has_workspace,
                        per_project_write_selection.as_ref(),
                    )?;
                }
            } else {
                tracing::debug!("lockfile=false: skipping lockfile write");
            }
            let mut lockfile_graph_for_integrity_rewrite = lockfile_enabled.then(|| graph.clone());

            // Trim the in-memory graph down to host-installable optionals
            // before it reaches the linker. When the resolver widened its
            // platform filter for aube-lock.yaml, the graph (and now the
            // lockfile) carries native packages for every major platform;
            // `node_modules` must still only get the host's. Mirrors the
            // filter pass the lockfile-happy branch above runs against a
            // parsed lockfile. A no-op when the manifest didn't trigger
            // widening (graph was already host-only).
            let (sup_os, sup_cpu, sup_libc) =
                aube_manifest::effective_supported_architectures(&manifest, &ws_config_shared);
            let install_supported_architectures = aube_resolver::SupportedArchitectures {
                os: sup_os,
                cpu: sup_cpu,
                libc: sup_libc,
                ..Default::default()
            };
            let install_ignored_optional = aube_manifest::effective_ignored_optional_dependencies(
                &manifest,
                &ws_config_shared,
            );
            aube_resolver::platform::filter_graph(
                &mut graph,
                &install_supported_architectures,
                &install_ignored_optional,
            );

            // Reconcile the progress denominator and the running
            // estimated-download total. The streaming pass bumped
            // `inc_total` once per *resolved* package and recorded
            // each `unpacked_size`; `filter_graph` just dropped the
            // platform-mismatched optionals, so both totals overcount
            // by the culled entries (the historical "stays at 90%"
            // and over-inflated `~X MB` segments). Resetting against
            // the surviving graph produces a stable cur/total ratio
            // and a size estimate that reflects only what will
            // actually install.
            if let Some(p) = prog_ref {
                p.set_total(graph.packages.len());
                p.reconcile_estimated_bytes(graph.packages.keys());
            }

            // Catch-up fetch: the streaming coordinator deferred
            // platform-mismatched registry tarballs on the assumption
            // `filter_graph` would drop them. Anything still in
            // `graph.packages` without a store index is a survivor
            // (i.e. reached via a non-optional edge) and needs its
            // tarball before the linker runs. In practice this set is
            // usually empty: platform-constrained packages are almost
            // always `optionalDependencies`, and `filter_graph` culls
            // those. The rare non-empty case is a broken package that
            // declares `os`/`cpu` without marking itself optional — we
            // still install it with a warning, matching pnpm's
            // `packageIsInstallable` behavior.
            let missing_packages: BTreeMap<String, aube_lockfile::LockedPackage> = graph
                .packages
                .iter()
                // Only non-local registry tarballs are ever deferred by
                // the streaming platform-skip above (it fires solely for
                // `local_source.is_none()`), so the catch-up must scope to
                // those. Local `file:`/`link:` deps already ran their
                // `import_local_source` + `inc_reused` up front; link-only
                // deps legitimately leave no `indices` entry, so a plain
                // `!indices.contains_key` filter would re-import them and
                // double-credit `reused` (reused > resolved →
                // WARN_AUBE_PROGRESS_OVERFLOW).
                .filter(|(dep_path, pkg)| {
                    !indices.contains_key(*dep_path) && pkg.local_source.is_none()
                })
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect();
            if !missing_packages.is_empty() {
                tracing::debug!(
                    "catch-up fetch for {} package(s) deferred by the streaming filter but kept by filter_graph",
                    missing_packages.len()
                );
                let catchup_start = std::time::Instant::now();
                let cwd_for_catchup_client = cwd.clone();
                let catchup_network_mode = opts.network_mode;
                let project_local_dep_paths = if planned_gvs {
                    gvs::legacy_vite_project_local_closure(&graph)
                } else {
                    Default::default()
                };
                let (catchup_indices, catchup_cached, catchup_fetched, catchup_integrities) =
                    fetch_packages_with_root(
                        &missing_packages,
                        &store,
                        || {
                            std::sync::Arc::new(
                                make_client(&cwd_for_catchup_client)
                                    .with_network_mode(catchup_network_mode),
                            )
                        },
                        prog_ref,
                        &cwd,
                        &aube_dir,
                        &packument_cache_dir,
                        /*materialize_tx=*/ None,
                        /*skip_already_linked_shortcut=*/
                        has_workspace || explicit_store_dir_override,
                        &project_local_dep_paths,
                        virtual_store_dir_max_length,
                        opts.ignore_scripts,
                        network_concurrency_setting,
                        verify_store_integrity_setting,
                        strict_store_integrity_setting,
                        strict_store_pkg_content_check_setting,
                        opts.git_prepare_depth,
                        inherited_build_policy_for_git_prepare.clone(),
                        resolve_git_shallow_hosts(&settings_ctx),
                    )
                    .await?;
                if !catchup_integrities.is_empty() {
                    apply_computed_integrities(&mut graph, &catchup_integrities);
                    if let Some(lock_graph) = lockfile_graph_for_integrity_rewrite.as_mut() {
                        apply_computed_integrities(lock_graph, &catchup_integrities);
                        // The integrity rewrite overwrites the lockfile the
                        // overlapped write produced. Join the in-flight write
                        // first so the two never race the same atomic-write
                        // rename and the on-disk result is the rewrite (the
                        // serial ordering the inline path had: write, then
                        // catch-up rewrite). Consumes the handle so the
                        // post-match join is a no-op.
                        if let Some(handle) = lockfile_write_handle.take() {
                            lockfile_write_overlap::join(handle).await?;
                        }
                        if shared_workspace_lockfile || !has_workspace {
                            write_lockfile_dir_remapped(
                                &lockfile_dir,
                                &lockfile_importer_key,
                                lock_graph,
                                &manifest,
                                write_kind,
                            )
                            .into_diagnostic()
                            .wrap_err("failed to write lockfile with computed integrity")?;
                        } else {
                            write_per_project_lockfiles(
                                &cwd,
                                lock_graph,
                                &manifests,
                                write_kind,
                                per_project_write_selection.as_ref(),
                            )?;
                        }
                    }
                }
                indices.extend(catchup_indices);
                cached += catchup_cached;
                fetched += catchup_fetched;
                phase_timings.record("catchup_fetch", catchup_start.elapsed());
            }

            (graph, indices, cached, fetched)
        }
        Err(aube_lockfile::Error::NotFound(_)) => {
            // Reachable when mode == Frozen, strict_no_lockfile == true,
            // and no lockfile is on disk. Today that's `aube ci` /
            // `aube clean-install`, which match `npm ci` semantics.
            return Err(miette!(
                "no lockfile found and --frozen-lockfile is set\n\
                 help: commit pnpm-lock.yaml to your repository, or run \
                 `{} --no-frozen-lockfile` to generate one",
                aube_util::cmd("install")
            ));
        }
        Err(e) => {
            return Err(miette::Report::new(e)).wrap_err("failed to parse lockfile");
        }
    };

    tracing::debug!("Packages: {cached_count} cached, {fetch_count} fetched");

    // `cleanupUnusedCatalogs` (gated by the setting) rewrites
    // `aube-workspace.yaml` / `pnpm-workspace.yaml` to drop entries no
    // importer references. Runs once after we have the final graph so
    // the same helper covers both lockfile-read and fresh-resolve
    // paths (the `--lockfile-only` short-circuit above already handled
    // its own return). Pruning is independent of the lockfile write
    // below since the resolver already recorded the used subset in
    // `graph.catalogs`.
    maybe_cleanup_unused_catalogs(&cwd, &settings_ctx, &workspace_catalogs, &graph.catalogs)?;

    // 5a. Under `strict-peer-dependencies=true`, scan the resolved
    //     graph for unmet required peers and fail the install with the
    //     list. Default (strict=false) is silent, matching bun/npm/yarn
    //     — the previous pnpm-style warn-on-every-mismatch default
    //     produced a lot of noise on real-world trees and buried the
    //     genuinely actionable ones. Optional peers
    //     (peerDependenciesMeta.optional) are skipped either way, and
    //     `peerDependencyRules` escape hatches filter out matches
    //     before the strict check fires.
    //
    //     The `PeerDependencyRules::resolve` call is gated on strict
    //     because it reads across package.json / .npmrc /
    //     pnpm-workspace.yaml to build the three escape-hatch lists —
    //     allocation + file-source iteration nobody consumes on the
    //     silent default path.
    if resolve_strict_peer_dependencies(&settings_ctx) {
        let peer_rules = PeerDependencyRules::resolve(&manifest, &settings_ctx);
        check_unmet_peers(&graph, &peer_rules)?;
    }

    // 5b. Apply --prod / --dev / --no-optional filters. Drops the corresponding
    //     direct dep roots from every importer and prunes transitive packages
    //     only reachable through them. The filtered graph is what gets passed
    //     to the linker, so node_modules won't contain the excluded deps.
    //     The lockfile on disk is untouched.
    let graph_for_link = filter_graph_for_install(
        &cwd,
        &workspace_packages,
        &graph,
        &opts,
        has_workspace && !link_all_workspace_importers,
        true,
    )?;

    // 5c. Validate root + dependency `engines.node` constraints against
    //     the current Node version. Runs against `graph_for_link` so
    //     `--prod` / `--no-optional` excluded packages don't trip
    //     `engine-strict`: a dev-only dep pinning Node >=20 should not
    //     block a Node 18 production install. Defaults to warning on
    //     mismatch; fails the install when `engine-strict` is set in
    //     `.npmrc`. Packages with unparseable versions or ranges are
    //     treated as "no opinion" so malformed fields or unusual Node
    //     builds don't block installs.
    // 5c. Resolve node version, build policy, and validate engines.
    //     All three go through the `settings_ctx` loaded once at the
    //     top of `run`, so there's a single `.npmrc` read and a
    //     single workspace-yaml parse for the whole install.
    let engine_strict = aube_settings::resolved::engine_strict(&settings_ctx);
    // `childConcurrency` caps how many dep lifecycle scripts run in
    // parallel during the post-link allowBuilds phase. Matches pnpm's
    // default of 5 when unset. Zero gets clamped up to 1 inside
    // `run_dep_lifecycle_scripts` so a malformed config can't wedge
    // the install.
    let child_concurrency = aube_settings::resolved::child_concurrency(&settings_ctx) as usize;
    let (jail_policy, jail_policy_warnings) =
        JailBuildPolicy::from_settings(&settings_ctx, &ws_config_shared);
    let node_version_override = aube_settings::resolved::node_version(&settings_ctx);
    let node_version = crate::engines::effective_node_version(node_version_override.as_deref());
    crate::engines::run_checks(
        &aube_dir,
        &manifest,
        &manifests,
        &graph_for_link,
        &package_indices,
        node_version.as_deref(),
        engine_strict,
        virtual_store_dir_max_length,
        aube_util::embedder().self_engines_check,
    )?;

    // Emit policy-config warnings regardless of `--ignore-scripts`.
    // User wants to know about typos in `allowBuilds` even if scripts
    // will not run, otherwise they reenable scripts later and wonder
    // why nothing runs. Bar is active here (set_phase=linking comes
    // soon, set_phase=fetching already ran). Raw eprintln smears
    // output across bar frames. Route through safe_eprintln which
    // pauses the bar and holds the terminal lock for atomic output.
    for w in &policy_warnings {
        control::output(InstallOutputLevel::Warning, None, w.to_string());
    }
    for w in &jail_policy_warnings {
        control::output(InstallOutputLevel::Warning, None, w.to_string());
    }

    let link::LinkPhaseOutput {
        stats,
        node_linker,
        virtual_store_only,
        current_leaf_hashes,
        current_subtree_hashes,
        patch_hashes,
    } = link::run_link_phase(link::LinkPhaseInput {
        cwd: &cwd,
        settings_ctx: &settings_ctx,
        store: store.as_ref(),
        graph_for_link: &graph_for_link,
        package_indices: &package_indices,
        ws_dirs: &ws_dirs,
        manifests: &manifests,
        manifest: &manifest,
        build_policy: &build_policy,
        node_version: node_version.as_deref(),
        prewarm_graph_hashes: prewarm_graph_hashes.as_ref(),
        aube_dir: &aube_dir,
        modules_dir_name: &modules_dir_name,
        virtual_store_dir_max_length,
        link_concurrency_setting,
        use_global_virtual_store_override,
        planned_gvs,
        has_workspace,
        dep_selection_filtered: opts.dep_selection.is_filtered(),
        workspace_filter_empty: opts.workspace_filter.is_empty(),
        ignore_scripts: opts.ignore_scripts,
        prog_ref,
        phase_timings: &mut phase_timings,
    })?;
    // Join the overlapped lockfile write before finalize re-reads the
    // graph. The write ran concurrently with the link phase above; a write
    // error surfaces here (it is not dropped). `None` on every inline-write
    // path, so this is a no-op there.
    if let Some(handle) = lockfile_write_handle.take() {
        lockfile_write_overlap::join(handle).await?;
    }
    finalize::run_finalize_phase(finalize::FinalizePhaseInput {
        cwd: &cwd,
        settings_ctx: &settings_ctx,
        store: store.as_ref(),
        graph: &graph,
        graph_for_link: &graph_for_link,
        manifests: &manifests,
        lifecycle_manifests: &lifecycle_manifests,
        direct_dep_info: &direct_dep_info,
        deprecations: &deprecations,
        build_policy: &build_policy,
        jail_policy: &jail_policy,
        stats: &stats,
        node_linker,
        planned_gvs,
        virtual_store_only,
        current_leaf_hashes,
        current_subtree_hashes,
        patch_hashes,
        modules_dir_name: &modules_dir_name,
        aube_dir: &aube_dir,
        virtual_store_dir_max_length,
        child_concurrency,
        side_effects_cache_setting,
        side_effects_cache_readonly_setting,
        strict_dep_builds_setting,
        ignore_scripts: opts.ignore_scripts,
        skip_root_lifecycle: opts.skip_root_lifecycle,
        workspace_filter_empty: opts.workspace_filter.is_empty(),
        dep_selection: opts.dep_selection,
        cli_flags: &opts.cli_flags,
        cached_count,
        fetch_count,
        start,
        prog_ref,
        phase_timings: &mut phase_timings,
    })
    .await?;
    // A fresh resolve enforces trustPolicy=no-downgrade while picking
    // versions from packuments. If an existing lockfile fed the resolver,
    // `try_lockfile_reuse` may carry locked packages forward without
    // fetching their packuments, so only the explicit lockfile validator
    // may seed the cache in that path.
    if can_seed_trust_policy_validation_from_resolve(
        lockfile_enabled,
        existing_for_resolver.is_some(),
    ) {
        maybe_record_lockfile_trust_policy_validation(
            &cwd,
            &settings_ctx,
            &graph,
            opts.network_mode,
            &dependency_policy,
        );
    }
    Ok(())
}

fn filter_graph_for_install(
    cwd: &std::path::Path,
    workspace_packages: &[std::path::PathBuf],
    graph: &aube_lockfile::LockfileGraph,
    opts: &InstallOptions,
    filter_to_root_importer: bool,
    log_dropped_packages: bool,
) -> miette::Result<aube_lockfile::LockfileGraph> {
    let mut filtered = if opts.dep_selection.is_filtered() {
        let sel = opts.dep_selection;
        let selected = graph.filter_deps(|d| {
            if sel.prod_only() && d.dep_type == aube_lockfile::DepType::Dev {
                return false;
            }
            if sel.dev_only() && d.dep_type != aube_lockfile::DepType::Dev {
                return false;
            }
            if sel.skip_optional() && d.dep_type == aube_lockfile::DepType::Optional {
                return false;
            }
            true
        });
        let dropped = graph.packages.len() - selected.packages.len();
        if log_dropped_packages && dropped > 0 {
            tracing::debug!("{}: skipping {dropped} packages", sel.label());
        }
        selected
    } else {
        graph.clone()
    };

    if !opts.workspace_filter.is_empty() {
        filtered = filter_graph_to_workspace_selection(
            cwd,
            workspace_packages,
            &filtered,
            &opts.workspace_filter,
        )?;
    } else if filter_to_root_importer {
        filtered = filter_graph_to_importers(&filtered, ["."]);
    }

    Ok(filtered)
}

fn has_explicit_store_dir_override(cli_flags: &[(String, String)]) -> bool {
    super::has_embedder_store_override()
        || aube_settings::values::string_from_cli("storeDir", cli_flags).is_some()
}

/// Run pnpm's root-only pre-resolution hook from the workspace/lockfile root.
///
/// Kept as a command-level boundary because `update` resolves before chaining
/// into the install pipeline and must invoke the same hook before its resolver.
pub(crate) async fn run_dev_preinstall(
    project_dir: &std::path::Path,
    ignore_scripts: bool,
    dry_run: bool,
    lockfile_only: bool,
    initialize_environment_for: Option<&str>,
) -> miette::Result<()> {
    if ignore_scripts || dry_run || lockfile_only {
        return Ok(());
    }
    let root_dir =
        crate::dirs::find_workspace_root(project_dir).unwrap_or_else(|| project_dir.to_path_buf());
    if let Some(command) = initialize_environment_for {
        crate::runtime::ensure_for_cwd(&root_dir).await?;
        super::configure_script_settings_for_cwd(&root_dir, Some(command))?;
    }
    let root_manifest = super::load_manifest_or_default(&root_dir)?;
    let modules_dir_name = super::resolve_modules_dir_name_for_cwd(&root_dir);
    run_root_lifecycle_script(
        &root_dir,
        &modules_dir_name,
        &root_manifest,
        "pnpm:devPreinstall",
    )
    .await
}

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

    fn write_project_npmrc(dir: &std::path::Path, registry: &str) {
        std::fs::write(
            dir.join(".npmrc"),
            format!("cache-dir=.cache\nregistry={registry}\n"),
        )
        .unwrap();
    }

    fn graph_with_integrity(integrity: &str) -> aube_lockfile::LockfileGraph {
        let mut graph = aube_lockfile::LockfileGraph::default();
        graph.importers.insert(
            ".".into(),
            vec![aube_lockfile::DirectDep {
                name: "left-pad".into(),
                dep_path: "left-pad@1.3.0".into(),
                dep_type: aube_lockfile::DepType::Production,
                specifier: Some("1.3.0".into()),
            }],
        );
        graph.packages.insert(
            "left-pad@1.3.0".into(),
            aube_lockfile::LockedPackage {
                name: "left-pad".into(),
                version: "1.3.0".into(),
                integrity: Some(integrity.into()),
                dep_path: "left-pad@1.3.0".into(),
                tarball_url: Some(
                    "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz".into(),
                ),
                ..Default::default()
            },
        );
        graph
    }

    fn no_downgrade_policy() -> aube_resolver::DependencyPolicy {
        aube_resolver::DependencyPolicy {
            trust_policy: aube_resolver::TrustPolicy::NoDowngrade,
            ..Default::default()
        }
    }

    #[test]
    fn trust_policy_validation_key_tracks_graph_policy_and_registry() {
        let dir = tempfile::tempdir().unwrap();
        write_project_npmrc(dir.path(), "https://registry.npmjs.org/");
        let graph = graph_with_integrity("sha512-one");
        let policy = no_downgrade_policy();
        let key = trust_policy_validation_cache_key(
            dir.path(),
            &graph,
            aube_registry::NetworkMode::Online,
            &policy,
        )
        .unwrap();

        let changed_graph = graph_with_integrity("sha512-two");
        let changed_graph_key = trust_policy_validation_cache_key(
            dir.path(),
            &changed_graph,
            aube_registry::NetworkMode::Online,
            &policy,
        )
        .unwrap();
        assert_ne!(key, changed_graph_key);

        let mut changed_policy = policy.clone();
        changed_policy.trust_policy_ignore_after = Some(1);
        let changed_policy_key = trust_policy_validation_cache_key(
            dir.path(),
            &graph,
            aube_registry::NetworkMode::Online,
            &changed_policy,
        )
        .unwrap();
        assert_ne!(key, changed_policy_key);

        write_project_npmrc(dir.path(), "https://registry.example.test/");
        let changed_registry_key = trust_policy_validation_cache_key(
            dir.path(),
            &graph,
            aube_registry::NetworkMode::Online,
            &policy,
        )
        .unwrap();
        assert_ne!(key, changed_registry_key);
    }

    #[test]
    fn trust_policy_validation_key_skips_disabled_modes() {
        let dir = tempfile::tempdir().unwrap();
        write_project_npmrc(dir.path(), "https://registry.npmjs.org/");
        let graph = graph_with_integrity("sha512-one");
        let mut policy = no_downgrade_policy();
        policy.trust_policy = aube_resolver::TrustPolicy::Off;

        assert!(
            trust_policy_validation_cache_key(
                dir.path(),
                &graph,
                aube_registry::NetworkMode::Online,
                &policy,
            )
            .is_none()
        );
        assert!(
            trust_policy_validation_cache_key(
                dir.path(),
                &graph,
                aube_registry::NetworkMode::Offline,
                &no_downgrade_policy(),
            )
            .is_none()
        );
    }

    #[test]
    fn trust_policy_validation_cache_hit_checks_key_and_ttl() {
        let dir = tempfile::tempdir().unwrap();
        write_project_npmrc(dir.path(), "https://registry.npmjs.org/");

        record_lockfile_trust_policy_validation(dir.path(), "fresh");
        assert!(trust_policy_validation_cache_hit(dir.path(), "fresh"));
        assert!(!trust_policy_validation_cache_hit(dir.path(), "other"));

        let stale_stamp = TrustPolicyValidationStamp {
            key: "stale".into(),
            validated_at_secs: unix_time_secs()
                .unwrap()
                .saturating_sub(TRUST_POLICY_VALIDATION_CACHE_TTL.as_secs() + 1),
        };
        let stale_bytes = serde_json::to_vec(&stale_stamp).unwrap();
        aube_util::fs_atomic::atomic_write(
            &trust_policy_validation_cache_path(dir.path(), "stale"),
            &stale_bytes,
        )
        .unwrap();
        assert!(!trust_policy_validation_cache_hit(dir.path(), "stale"));

        let future_stamp = TrustPolicyValidationStamp {
            key: "future".into(),
            validated_at_secs: unix_time_secs()
                .unwrap()
                .saturating_add(TRUST_POLICY_VALIDATION_CACHE_TTL.as_secs() + 1),
        };
        let future_bytes = serde_json::to_vec(&future_stamp).unwrap();
        aube_util::fs_atomic::atomic_write(
            &trust_policy_validation_cache_path(dir.path(), "future"),
            &future_bytes,
        )
        .unwrap();
        assert!(!trust_policy_validation_cache_hit(dir.path(), "future"));
    }

    #[test]
    fn resolve_seeds_trust_policy_cache_only_without_existing_lockfile() {
        assert!(can_seed_trust_policy_validation_from_resolve(true, false));
        assert!(!can_seed_trust_policy_validation_from_resolve(true, true));
        assert!(!can_seed_trust_policy_validation_from_resolve(false, false));
    }
}

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

    #[test]
    fn computed_integrity_updates_peer_variants() {
        let mut graph = aube_lockfile::LockfileGraph::default();
        graph.packages.insert(
            "consumer@1.0.0(peer@2.0.0)".into(),
            aube_lockfile::LockedPackage {
                name: "consumer".into(),
                version: "1.0.0".into(),
                dep_path: "consumer@1.0.0(peer@2.0.0)".into(),
                ..Default::default()
            },
        );
        graph.packages.insert(
            "already@1.0.0".into(),
            aube_lockfile::LockedPackage {
                name: "already".into(),
                version: "1.0.0".into(),
                dep_path: "already@1.0.0".into(),
                integrity: Some("sha512-existing".into()),
                ..Default::default()
            },
        );
        let computed = BTreeMap::from([
            ("consumer@1.0.0".into(), "sha512-computed".into()),
            ("already@1.0.0".into(), "sha512-new".into()),
        ]);

        apply_computed_integrities(&mut graph, &computed);

        assert_eq!(
            graph.packages["consumer@1.0.0(peer@2.0.0)"]
                .integrity
                .as_deref(),
            Some("sha512-computed")
        );
        assert_eq!(
            graph.packages["already@1.0.0"].integrity.as_deref(),
            Some("sha512-existing")
        );
    }
}

#[cfg(test)]
mod explicit_store_dir_override_tests {
    use super::has_explicit_store_dir_override;

    #[test]
    fn recognizes_canonical_and_kebab_case_cli_keys() {
        assert!(has_explicit_store_dir_override(&[(
            "storeDir".into(),
            "/store".into(),
        )]));
        assert!(has_explicit_store_dir_override(&[(
            "store-dir".into(),
            "/store".into(),
        )]));
        assert!(!has_explicit_store_dir_override(&[(
            "cache-dir".into(),
            "/cache".into(),
        )]));
    }
}