vivacity 0.26.2

Fast, Composer-compatible installer for PHP projects: install, update, require, remove, dump-autoload
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
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
//! `install`: lay out the lock — `InstallCommand`, the install half of
//! `Installer::run`, and the plugins vivacity emulates while doing it.

use super::*;

/// `Installer::doInstall` solves the lock again (`Solver.php:231`): its
/// duration at VERBOSE, after the stale-lock warning and the missing
/// requirements, before the problems or the operation count. Never for the
/// install that follows an update (`$alreadySolved`). The duration is the
/// SAT's alone, measured on the verification thread, as Composer's timer
/// wraps `runSat` only.
fn say_lock_resolution(sat: std::time::Duration) {
    vivacity_core::say_verbose!(
        "Dependency resolution completed in {:.3} seconds",
        sat.as_secs_f64()
    );
}

/// What a phase of `run_install` that can end the command returns:
/// `Break(code)` is the exit code of the command, `Continue` carries what
/// the phases after it need.
type Flow<T = ()> = std::ops::ControlFlow<i32, T>;

/// `?` for a [`Flow`] inside `run_install`: the value it carries, or
/// `return Ok(code)`.
macro_rules! proceed {
    ($flow:expr) => {
        match $flow {
            std::ops::ControlFlow::Continue(value) => value,
            std::ops::ControlFlow::Break(code) => return Ok(code),
        }
    };
}

/// `InstallCommand` then `Installer::run` / `doInstall`, phase by phase.
/// The lock verification (the list filter's network wait, the platform,
/// the solve) runs on its own thread while the local-repository
/// transaction, the scope and (for a no-op) the autoloader are computed in
/// silence; it is joined before anything is printed or written past that
/// point, after the missing requirements, in `doInstall`'s order.
pub(crate) fn run_install(args: &InstallArgs) -> anyhow::Result<i32> {
    // `BaseCommand::initialize` loads the root package first: its version
    // warning precedes everything below. The install that follows an update
    // runs in the update's `Composer`, which already wrote it.
    if !args.after_update() {
        if let Ok(project) = project_dir(args.working_dir.as_deref()) {
            hold_root_version_warning(&project);
            hold_ignored_lock_warning(&project);
        }
    }
    // `InstallCommand` and `Factory::create`.
    let run = proceed!(read_manifests(args)?);
    let run = proceed!(merge_plugin(run)?);
    // `secure-http` on the lock's dists, before the command prints or runs
    // anything (an install after an update was decided on its solved lock).
    // A dry run downloads nothing.
    if !args.after_update() && !args.dry_run {
        if let Some(reason) = insecure_dist_reason(
            &run.project,
            &run.manifest,
            &run.lock,
            run.with_dev,
            !args.no_plugins,
        ) {
            let scope = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::Layout(reason)],
                skipped_plugins: vec![],
                layout: None,
            };
            return fallback_or_fail(args, &scope);
        }
    }
    // A local repository whose lists the `install` scope's filters cannot
    // read as Composer does: before the command prints anything.
    if !args.after_update() {
        if let Some(reason) = crate::fallback::local_install_issue(&run.manifest) {
            let scope = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::Layout(reason)],
                skipped_plugins: vec![],
                layout: None,
            };
            return fallback_or_fail(args, &scope);
        }
    }
    // `InstallCommand::execute` dispatches `PluginEvents::COMMAND` before
    // `Installer::run` (InstallCommand.php:111); `update`, `require` and
    // `remove` dispatch theirs before their resolution.
    if !args.after_update() {
        bamarni_command_event(&run.project, &run.manifest, !args.no_plugins);
    }
    // `Installer::run`.
    let run = proceed!(pre_install_cmd(run)?);
    // `Installer::doInstall`. Under `secure-http`'s trigger, the headline
    // and what follows are held until the downloads end: a refused
    // redirect then hands over with nothing printed (the archives it
    // cached taken back). An `http://` dist of the lock was handed over
    // before anything (`insecure_dist_reason`, above).
    if crate::fallback::hold_trigger(&run.manifest) {
        crate::fallback::start_holding("the downloads end");
    }
    proceed!(headline(&run)?);
    let verification = spawn_verification(&run)?;
    let root = verification.as_ref().map(|v| root_package(&run, v));
    let tx = local_repository_transaction(&run, root.as_ref())?;
    let mut scope = analyze_scope(&run);
    // `PluginInstaller::prepare`: a plugin the transaction installs or
    // updates that `allow-plugins` does not cover stops Composer in the
    // middle of it (an install after an update was decided on its lock).
    if let Some(report) = scope
        .as_mut()
        .filter(|_| !args.after_update() && !args.no_plugins)
    {
        let targets: Vec<(String, bool)> =
            crate::plugin_allow::installed_by(&run.project, &run.manifest, &run.lock, run.with_dev);
        report.issues.extend(crate::plugin_allow::install_issue(
            &run.project,
            &run.manifest,
            targets.iter().map(|(n, o)| (n.as_str(), *o)),
        ));
    }
    let early_dump = plan_autoload_early(&run, &tx, scope.as_ref());
    // `if (!$alreadySolved)`: the missing requirements (exit 4) before the
    // pool exists, then the solve on the locked pool (exit 2, or 4). None
    // of it after an update, which installs the lock it just solved.
    if let Some(verification) = verification {
        let mut verification = verification;
        proceed!(report_missing(&run, &tx.missing, &mut verification)?);
        proceed!(join_verification(&run, verification)?);
    }
    report_operations(&tx);
    if args.dry_run {
        return dry_run(&run, &tx);
    }
    let layout = proceed!(native_layout(&run, scope)?);
    // `PRE_INSTALL_CMD` listeners that print, once the run is known to stay
    // native (a hand-over after them would have Composer print them again);
    // nothing else reaches stdout before this point.
    if !args.after_update() {
        crate::effect_plugins::patcher_pre(
            &run.project,
            &run.manifest,
            &layout,
            run.with_dev,
            !args.no_plugins,
        )?;
    }
    // `InstallationManager::execute` handles the signals itself while the
    // operations run: `require`'s revert does not apply there.
    vivacity_core::signals::suspend();
    let executed = execute_operations(&run, &tx, &layout);
    vivacity_core::signals::resume();
    let installed = proceed!(executed?);
    // `Installer::run`, after `doInstall`.
    let (autoload_note, cleaner_counts) = if args.no_autoloader {
        (String::new(), None)
    } else {
        proceed!(dump_autoloader(
            &run,
            &tx,
            &layout,
            &installed.report,
            early_dump
        )?)
    };
    proceed!(post_install(
        &run,
        &layout,
        &installed.report,
        &tx,
        cleaner_counts.as_ref()
    )?);
    say_summary(&run, &installed.report, &autoload_note);
    Ok(0)
}

/// What the phases of one install share, fixed before the first line is
/// printed: built by `read_manifests`, the root package replaced by
/// `merge_plugin`, the scripts runner set by `pre_install_cmd`.
struct Run<'a> {
    args: &'a InstallArgs,
    /// The start of the command: the `trace` origin, and the duration the
    /// closing line reports.
    t0: std::time::Instant,
    project: PathBuf,
    /// composer.json as written: the content-hash and `config.lock` read the
    /// file, not the root package below.
    manifest_text: String,
    /// The root package Composer works with: the effective
    /// `preferred-install` written in, then merged by composer-merge-plugin.
    manifest: serde_json::Value,
    merged: Option<vivacity_resolver::merge_plugin::Merged>,
    lock_value: serde_json::Value,
    lock: vivacity_core::lock::Lock,
    with_dev: bool,
    /// `--ignore-platform-reqs` / `--ignore-platform-req` as
    /// `BaseCommand::initialize` leaves them: the environment fills what the
    /// command line left empty.
    ignore_platform_reqs: bool,
    ignore_platform_req: Vec<String>,
    runner: Option<scripts::Runner>,
}

/// `InstallCommand`'s refusals, then the manifest (with the effective
/// `preferred-install`) and the lock as `Factory::create` reads them.
fn read_manifests(args: &InstallArgs) -> anyhow::Result<Flow<Run<'_>>> {
    let (ignore_platform_reqs, ignore_platform_req) = platform_requirement_options(args);
    if args.no_install {
        vivacity_core::say!("Invalid option \"--no-install\". Use \"composer update --no-install\" instead if you are trying to update the composer.lock file.");
        return Ok(Flow::Break(1));
    }
    let t0 = std::time::Instant::now();
    let project = project_dir(args.working_dir.as_deref())?;
    let manifest_path = project.join("composer.json");
    let lock_path = project.join("composer.lock");
    refuse_alternate_manifest()?;
    if let Some(code) = refuse_missing_manifest(&project) {
        return Ok(Flow::Break(code));
    }

    let manifest_text = std::fs::read_to_string(&manifest_path)
        .with_context(|| format!("cannot read {}", manifest_path.display()))?;
    let manifest: serde_json::Value = match &args.virtual_manifest {
        Some(v) => v.clone(),
        None => serde_json::from_str(&manifest_text).context("invalid composer.json")?,
    };
    // Before the lock is even looked at: Composer refuses the manifest before
    // it reads the lock, so a stale lock is not the error to report.
    if let Some(code) = refuse_invalid_root(&manifest) {
        return Ok(Flow::Break(code));
    }
    // Then the installed plugins, judged by `allow-plugins` (an install
    // that follows an update runs in the update's `Composer`).
    if !args.after_update() {
        if let Some(code) = crate::plugin_allow::at_load(
            &project,
            &manifest,
            None,
            !args.no_plugins,
            args.no_fallback,
        )? {
            return Ok(Flow::Break(code));
        }
    }
    // `--prefer-source` / `--prefer-dist` / `--prefer-install` are what
    // `getPreferredInstallOptions` makes of them: the effective
    // `preferred-install` this run uses. Written into the manifest vivacity
    // analyses, so the scope detector judges it per package exactly as it
    // judges the config — a source install then hands the command over.
    let mut manifest = manifest;
    match vivacity_core::scope::effective_preferred_install(
        &manifest,
        args.prefer_source,
        args.prefer_dist,
        args.prefer_install.as_deref(),
    ) {
        Err(message) => {
            vivacity_core::say_always!("{message}");
            return Ok(Flow::Break(1));
        }
        Ok(Some(value)) => {
            if let Some(config) = manifest.get_mut("config").and_then(|c| c.as_object_mut()) {
                config.insert("preferred-install".to_owned(), value);
            } else if let Some(root) = manifest.as_object_mut() {
                root.insert(
                    "config".to_owned(),
                    serde_json::json!({"preferred-install": value}),
                );
            }
        }
        Ok(None) => {}
    }
    // `remove` takes the removed plugins out of `allow-plugins` after its
    // `Composer` was built: the `PluginManager` keeps the rules it read
    // (RemoveCommand.php:216-222, then :242-252), so the rest of the run
    // judges plugins by them — as they were, order included (the first
    // matching rule wins).
    if let Some(allow) = args
        .post_update
        .as_ref()
        .and_then(|u| u.allow_plugins_at_load.clone())
    {
        if let Some(root) = manifest.as_object_mut() {
            let config = root
                .entry("config")
                .or_insert_with(|| serde_json::json!({}));
            if let Some(config) = config.as_object_mut() {
                config.insert("allow-plugins".to_owned(), allow);
            }
        }
    }
    let manifest = manifest;
    // Parsed once: the `Value` serves the transaction, the abandoned
    // warnings and the missing-requirement check; the `Lock` everything else.
    let lock_value: serde_json::Value = match &args.virtual_lock {
        // A dry-run update (or one that writes no lock) installs from its
        // unwritten lock.
        Some(v) => serde_json::from_str(&vivacity_core::phpjson::php_json_encode_with(
            v,
            vivacity_core::phpjson::FLAGS_JSONFILE,
        )?)
        .context("invalid composer.lock")?,
        None => {
            // `Installer::run`: without a lock to install (`isLocked()`
            // false — `config.lock: false`, whose `Locker` reads
            // `/dev/null`, no file, no `packages`), the install updates. An
            // unreadable lock is Composer's ParsingException.
            let enabled = config_lock_enabled(&manifest_text);
            let text = match std::fs::read_to_string(&lock_path) {
                Ok(text) if enabled => text,
                Err(e) if enabled && e.kind() != std::io::ErrorKind::NotFound => {
                    return Err(anyhow::Error::new(e)
                        .context(format!("cannot read {}", lock_path.display())));
                }
                _ => return Ok(Flow::Break(install_without_lock(args, enabled)?)),
            };
            let value: serde_json::Value =
                serde_json::from_str(&text).context("invalid composer.lock")?;
            if !value.get("packages").is_some_and(|p| !p.is_null()) {
                return Ok(Flow::Break(install_without_lock(args, enabled)?));
            }
            value
        }
    };
    let lock = vivacity_core::lock::Lock::from_value(&lock_value);
    trace("read manifests", t0);

    let with_dev = !args.no_dev && !env_no_dev();
    Ok(Flow::Continue(Run {
        args,
        t0,
        project,
        manifest_text,
        manifest,
        merged: None,
        lock_value,
        lock,
        with_dev,
        ignore_platform_reqs,
        ignore_platform_req,
        runner: None,
    }))
}

/// `Installer::run` (Installer.php:277-285) when there is no lock to
/// install: it says so, then runs as `update` with install — the lock
/// written unless `config.lock` is false, in which case the install phase
/// reads it from memory. Entered with `install`'s own options only (none of
/// the `COMPOSER_PREFER_*`/`COMPOSER_WITH_*` variables `update` reads).
/// `--check-scope` (no network, no write) and `--run-scripts` (update's
/// scripts, which vivacity's `update` does not run) stop or hand over.
fn install_without_lock(args: &InstallArgs, lock_enabled: bool) -> anyhow::Result<i32> {
    let line = format!(
        "{} Updating dependencies to latest instead of installing from lock file. See https://getcomposer.org/install for more information.",
        if lock_enabled {
            "No composer.lock file present."
        } else {
            "Lockfile creation is disabled in config."
        }
    );
    if args.check_scope || args.run_scripts {
        let report = vivacity_core::scope::ScopeReport {
            issues: vec![vivacity_core::scope::ScopeIssue::Layout(format!(
                "no lock to install: Composer resolves instead ({})",
                if lock_enabled {
                    "no composer.lock"
                } else {
                    "config.lock is false"
                }
            ))],
            ..Default::default()
        };
        return fallback_or_fail(args, &report);
    }
    // Under -v, the lines of this resolution are kept until the solved lock
    // is accepted, as for `update` (`run_once`): a plugin it would activate
    // may still hand the run to Composer, which prints them itself.
    if vivacity_core::io::level() == vivacity_core::io::Verbosity::Verbose
        && !args.no_plugins
        && !args.dry_run
    {
        vivacity_core::io::defer();
    }
    let project = project_dir(args.working_dir.as_deref())?;
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(project.join("composer.json"))?)
            .context("invalid composer.json")?;
    if let Some(code) = resolution_fallback(
        &project,
        &manifest,
        vivacity_core::scope::ResolutionCommand::Update,
        args.no_plugins,
        args.no_fallback,
        !args.dry_run,
        !args.dry_run,
        !(args.no_dev || env_no_dev()),
        &PoolStart::default(),
    )? {
        return Ok(code);
    }
    let update_args = UpdateArgs {
        minimal_changes: false,
        compat: GlobalCompatArgs {
            no_interaction: args.compat.no_interaction,
            no_ansi: args.compat.no_ansi,
            ..GlobalCompatArgs::default()
        },
        no_progress: args.no_progress,
        packages: Vec::new(),
        with: Vec::new(),
        with_dependencies: false,
        with_all_dependencies: false,
        no_install: false,
        dry_run: args.dry_run,
        no_dev: args.no_dev,
        no_autoloader: args.no_autoloader,
        optimize_autoloader: args.optimize_autoloader,
        classmap_authoritative: args.classmap_authoritative,
        apcu_autoloader: args.apcu_autoloader,
        apcu_autoloader_prefix: args.apcu_autoloader_prefix.clone(),
        no_scripts: args.no_scripts,
        no_plugins: args.no_plugins,
        // `install` audits only on `--audit`.
        no_audit: true,
        no_blocking: args.no_blocking,
        no_security_blocking: args.no_security_blocking,
        prefer_stable: false,
        prefer_lowest: false,
        ignore_platform_reqs: args.ignore_platform_reqs,
        ignore_platform_req: args.ignore_platform_req.clone(),
        no_fallback: args.no_fallback,
        offline: args.offline,
        working_dir: args.working_dir.clone(),
        prefer_source: args.prefer_source,
        prefer_dist: args.prefer_dist,
        prefer_install: args.prefer_install.clone(),
        command_dispatched: false,
        lockless_install: Some(line),
        allow_plugins_at_load: None,
        resolution_command: None,
    };
    let options = vivacity_resolver::session::UpdateOptions {
        no_blocking: args.no_blocking || args.no_security_blocking,
        ..Default::default()
    };
    run_update_resolved(&update_args, options, false, false, &|| Ok(())).map(|e| e.status)
}

/// `BaseCommand::initialize`'s reading of the environment
/// ([`platform_requirement_env`]). The install that follows an update reads
/// it without warning: the update already did.
fn platform_requirement_options(args: &InstallArgs) -> (bool, Vec<String>) {
    platform_requirement_env(
        args.ignore_platform_reqs,
        &args.ignore_platform_req,
        !args.after_update(),
    )
}

/// `wikimedia/composer-merge-plugin`: the root package Composer works
/// with is the merged one (INIT, before any output — a merge error
/// fails Composer inside Factory::create). Everything after reads the
/// merged manifest; the content-hash keeps reading the file.
fn merge_plugin(run: Run<'_>) -> anyhow::Result<Flow<Run<'_>>> {
    let merged = match merge_plugin_root(
        &run.project,
        &run.lock,
        &run.manifest,
        run.with_dev,
        !run.args.no_plugins,
    ) {
        Ok(m) => m,
        Err(reason) => {
            let report = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::MergePlugin(reason)],
                ..Default::default()
            };
            return Ok(Flow::Break(fallback_or_fail(run.args, &report)?));
        }
    };
    let manifest = match &merged {
        Some(m) => m.manifest.clone(),
        None => run.manifest,
    };
    Ok(Flow::Continue(Run {
        manifest,
        merged,
        ..run
    }))
}

/// `--run-scripts`: the declared events go to `composer run-script` at
/// Composer's own points; `pre-install-cmd` fires first in
/// `Installer::run` (after the command's `COMMAND` event, before the
/// headline and the lock validation).
fn pre_install_cmd(run: Run<'_>) -> anyhow::Result<Flow<Run<'_>>> {
    let args = run.args;
    let runner = if args.run_scripts && !args.no_scripts {
        match scripts::Runner::new(&run.project, &run.manifest, run.with_dev, which_composer()) {
            Ok(r) => r,
            Err(e) => {
                vivacity_core::say_always!("vivacity: {e}");
                return Ok(Flow::Break(3));
            }
        }
    } else {
        None
    };
    // Decided before the first script runs: a hand-over after it would
    // have Composer run it a second time.
    if runner.is_some() {
        if let Some(issue) = crate::effect_plugins::replay_issue(
            &run.manifest,
            &run.lock,
            run.with_dev,
            !args.no_plugins,
            true,
            &[
                scripts::PRE_INSTALL_CMD,
                scripts::POST_INSTALL_CMD,
                scripts::PRE_AUTOLOAD_DUMP,
                scripts::POST_AUTOLOAD_DUMP,
            ],
        ) {
            let report = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::Layout(issue)],
                ..Default::default()
            };
            return Ok(Flow::Break(fallback_or_fail(args, &report)?));
        }
    }
    if let Some(r) = &runner {
        let code = r.run(scripts::PRE_INSTALL_CMD)?;
        if code != 0 {
            return Ok(Flow::Break(code));
        }
    }
    Ok(Flow::Continue(Run { runner, ..run }))
}

/// bamarni/composer-bin-plugin's `COMMAND` listener: its deprecation
/// lines, when the plugin is already installed and allowed (loaded from
/// installed.json before the command). Every command that dispatches the
/// event calls this at the point where Composer's command does.
pub(crate) fn bamarni_command_event(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    plugins_enabled: bool,
) {
    // Loaded the way `Factory::createComposer` loads it: installed, its
    // classes on disk (`loaded_plugins`), allowed (`active_plugins`).
    let composer_dir = composer_dir_of(project, manifest);
    let loaded = plugins_enabled
        && plugin_order::loaded_plugins(
            &plugin_order::installed_json_packages(&composer_dir),
            &composer_dir,
            plugin_order::global_composer_dir().as_deref(),
        )
        .iter()
        .any(|p| p == vivacity_core::bamarni_bin::PLUGIN_NAME);
    if loaded
        && vivacity_core::scope::active_plugins(project, manifest, plugins_enabled)
            .iter()
            .any(|p| p == vivacity_core::bamarni_bin::PLUGIN_NAME)
    {
        // Under -v: Composer's line for the listener, then the plugin's
        // `logDebug` (BamarniBinPlugin.php:110, `Logger::log` at VERBOSE).
        crate::verbose_listeners::announce(
            vivacity_core::bamarni_bin::PLUGIN_NAME,
            crate::verbose_listeners::COMMAND,
            manifest,
        );
        vivacity_core::say_verbose!("[bamarni-bin] Calling onCommandEvent().");
        if let Ok(cfg) = vivacity_core::bamarni_bin::config(manifest.get("extra")) {
            vivacity_core::bamarni_bin::print_deprecations(&cfg);
        }
    }
}

/// `Installer::doInstall`: the headline, the locked repository (which a lock
/// without `packages-dev` refuses in dev mode), then the platform
/// verification notice (the lock is solved against the platform when not
/// coming straight from an update), then the freshness warning.
fn headline(run: &Run<'_>) -> anyhow::Result<Flow> {
    let config_lock = config_lock_enabled(&run.manifest_text);
    if config_lock {
        vivacity_core::say!(
            "Installing dependencies from lock file{}",
            if run.with_dev {
                " (including require-dev)"
            } else {
                ""
            }
        );
    }
    // `$this->locker->getLockedRepository($this->devMode)` (Locker.php:157-165):
    // `isset($lockData['packages-dev'])`, else a RuntimeException — exit 1,
    // its message shown even under `-q`, before "Verifying…". Printed
    // without Symfony Console's box, like `RootPackageLoader`'s refusals.
    // An update's lock always has the key.
    if run.with_dev && !run.args.after_update() {
        refuse_lock_without_dev(run)?;
    }
    if !run.args.after_update() {
        vivacity_core::say!("Verifying lock file contents can be installed on current platform.");
        // Lock freshness: same behaviour as Composer, a warning.
        if let (Ok(actual), Some(expected)) = (
            vivacity_core::content_hash::content_hash(&run.manifest_text),
            run.lock.content_hash.as_deref(),
        ) {
            if actual != expected {
                vivacity_core::say_always!(
                    "Warning: The lock file is not up to date with the latest changes in composer.json. \
                     You may be getting outdated dependencies. It is recommended that you run `composer update` or `composer update <package name>`."
                );
            }
        }
    }
    Ok(Flow::Continue(()))
}

/// `Locker::getLockedRepository(true)` on a lock without `packages-dev`
/// (`isset` false: the key absent or null): Composer's exception.
fn refuse_lock_without_dev(run: &Run<'_>) -> anyhow::Result<()> {
    if run
        .lock_value
        .get("packages-dev")
        .is_none_or(serde_json::Value::is_null)
    {
        return Err(anyhow::Error::new(ComposerException(
            vivacity_resolver::repository::LOCK_WITHOUT_DEV.to_owned(),
        )));
    }
    Ok(())
}

/// The lock verification running on its own thread, and the channel the
/// root version reaches it by. Dropped without being joined (the command
/// stopped before the join), it tells the thread to stop after its network
/// wait.
struct Verification {
    handle: Option<
        std::thread::JoinHandle<
            Result<
                vivacity_resolver::session::InstallVerification,
                vivacity_resolver::session::SessionError,
            >,
        >,
    >,
    root_version: Option<std::sync::mpsc::Sender<vivacity_core::root_version::RootVersion>>,
    abandoned: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// `--ignore-platform-reqs` (or `--ignore-platform-req=*`): no warning
    /// without php.
    ignores_all: bool,
    /// The lock has platform requirements to check (the warning without
    /// php).
    lock_platform: bool,
}

impl Verification {
    /// The command stops (or hands over) before the join: the thread skips
    /// what is left after its network wait.
    fn abandon(&self) {
        self.abandoned
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    /// Abandons the thread and waits for it, its result dropped: before a
    /// Composer process is started, so that the two never write the
    /// repository cache at the same time (the thread may be in its network
    /// wait, about to write `packages.json` or the filter summary).
    fn abandon_and_wait(&mut self) {
        self.abandon();
        drop(self.root_version.take());
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

impl Drop for Verification {
    fn drop(&mut self) {
        if self.handle.is_some() {
            self.abandon();
        }
    }
}

/// `Installer::doInstall` solves the lock again before laying it out
/// (`session::verify_install`): the locked packages through the list
/// filter in install scope (one conditional request per install,
/// Composer's `loadFilterSummary`, `packages.json` cached 600 s — the only
/// network wait of an install from lock), then the platform probed and the
/// solve. On its own thread while the transaction and the scope are
/// computed; joined before anything is printed or written past this point.
/// None after an update (`$alreadySolved`).
fn spawn_verification(run: &Run<'_>) -> anyhow::Result<Option<Verification>> {
    let args = run.args;
    if args.after_update() {
        return Ok(None);
    }
    let abandoned = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let input = vivacity_resolver::session::InstallVerifyInput {
        project_dir: run.project.clone(),
        composer_home: vivacity_core::fetch::composer_home(),
        http: Some(http_transport(&run.project, args.offline)?),
        cache_repo_dir: Some(vivacity_core::fetch::composer_cache_dir().join("repo")),
        manifest_text: run.manifest_text.clone(),
        root_manifest: run.manifest.clone(),
        dev_mode: run.with_dev,
        no_blocking: args.no_blocking || args.no_security_blocking,
        ignore_platform_reqs: run.ignore_platform_reqs,
        ignore_platform_req: run.ignore_platform_req.clone(),
        // `prependRepositories` runs when the plugin is activated: on a bare
        // vendor it is not yet, and `doInstall`'s filter never sees them.
        prepended_repositories: run
            .merged
            .as_ref()
            .filter(|_| {
                installed_packages(&run.project, &run.manifest)
                    .iter()
                    .any(|p| {
                        p.get("name").and_then(serde_json::Value::as_str)
                            == Some(vivacity_resolver::merge_plugin::PLUGIN_NAME)
                    })
            })
            .map(|m| m.repository_definitions.clone())
            .unwrap_or_default(),
        abandoned: abandoned.clone(),
    };
    let (root_version, received) = std::sync::mpsc::channel();
    let handle =
        std::thread::spawn(move || vivacity_resolver::session::verify_install(input, received));
    Ok(Some(Verification {
        handle: Some(handle),
        root_version: Some(root_version),
        abandoned,
        ignores_all: run.ignore_platform_reqs || run.ignore_platform_req.iter().any(|p| p == "*"),
        lock_platform: !run.lock.platform.is_empty()
            || (run.with_dev && !run.lock.platform_dev.is_empty()),
    }))
}

/// The root package (`RootPackageLoader`) the missing requirements are
/// checked against: its version guessed once (git), and handed to the
/// verification thread, which waits for it only after its network wait.
fn root_package(run: &Run<'_>, verification: &Verification) -> vivacity_core::state::RootPackage {
    let rv = vivacity_core::root_version::detect(&run.manifest, &run.project);
    // A thread that already ended (an error) has dropped its receiver: its
    // error is reported at the join.
    if let Some(sender) = &verification.root_version {
        let _ = sender.send(rv.clone());
    }
    vivacity_core::state::RootPackage::with_version(&run.manifest, rv, run.with_dev)
}

/// The local repository against the lock, and the root requirements the
/// lock does not satisfy.
struct LocalTransaction {
    /// The packages of both repositories (left empty by the no-op proof).
    arena: Vec<vivacity_resolver::package::Package>,
    /// installed.json's packages, as arena indices.
    present: Vec<usize>,
    /// The no-op proof: the present names, in installed.json order.
    unchanged_names: Option<Vec<String>>,
    transaction: vivacity_resolver::transaction::Transaction,
    /// `Locker::getMissingRequirementInfo`'s lines (empty: nothing missing).
    missing: Vec<String>,
    /// The plugins in the order Composer activates them for this command
    /// (`plugin_order`): the order of their listeners.
    listeners: Vec<String>,
}

/// `LocalRepoTransaction` (installed.json against the lock) and
/// `Locker::getMissingRequirementInfo`, computed in silence: reported by
/// `report_missing`, `report_operations` and `dry_run`.
fn local_repository_transaction(
    run: &Run<'_>,
    root: Option<&vivacity_core::state::RootPackage>,
) -> anyhow::Result<LocalTransaction> {
    let mut arena: Vec<vivacity_resolver::package::Package> = Vec::new();
    // installed.json as written: the plugins Composer loads (before the
    // purge), then the local repository, purged of the packages whose
    // install path is gone (`Factory::purgePackages`).
    let composer_dir = composer_dir_of(&run.project, &run.manifest);
    let installed_raw = plugin_order::installed_json_packages(&composer_dir);
    let plugins_enabled = !run.args.no_plugins;
    let loaded = if plugins_enabled {
        plugin_order::loaded_plugins(
            &installed_raw,
            &composer_dir,
            plugin_order::global_composer_dir().as_deref(),
        )
    } else {
        Vec::new()
    };
    // The entries as loaded, for the classes the plugins declare.
    let installed_raw_names = installed_raw.clone();
    let installed_now = present_packages(
        &run.project,
        &run.manifest,
        &run.lock,
        run.with_dev,
        plugins_enabled,
        &composer_dir,
        installed_raw,
    );
    trace("installed.json", run.t0);
    // Nothing to do at all (the commonest install): proved on the raw
    // entries, so the two repositories are not loaded into the arena —
    // ~8 ms of constraint parsing on a 100-package lock. `None` falls back
    // to the full computation.
    let unchanged_names = unchanged_local_repository(&installed_now, &run.lock_value, run.with_dev);
    let (present, result) = if unchanged_names.is_some() {
        (Vec::new(), Vec::new())
    } else {
        let as_lock = serde_json::json!({"packages": installed_now, "packages-dev": []});
        let present =
            vivacity_resolver::repository::locked_repository_with(&as_lock, &mut arena, true)
                .map_err(|e| anyhow::anyhow!("installed.json: {}", e.0))?;
        let result = vivacity_resolver::repository::locked_repository_with(
            &run.lock_value,
            &mut arena,
            run.with_dev,
        )
        .map_err(|e| anyhow::anyhow!("composer.lock: {}", e.0))?;
        (present, result)
    };
    // `Locker::getMissingRequirementInfo`: a root requirement the lock does
    // not satisfy (a hand-edited composer.json) stops with code 4
    // (`report_missing`). Not after an update (`$alreadySolved`): no root
    // was detected for it then.
    let merged_links = run
        .merged
        .as_ref()
        .map(|m| (m.requires.as_slice(), m.requires_dev.as_slice()));
    let missing = match root {
        None => Vec::new(),
        Some(root) => missing_requirement_info(
            &run.manifest,
            &run.lock_value,
            run.with_dev,
            &root.version,
            &root.pretty_version,
            merged_links,
        )?,
    };
    trace("local repositories", run.t0);
    let transaction = vivacity_resolver::transaction::Transaction::new(&arena, &present, &result);
    note_plugin_operations(run, &loaded, &installed_raw_names, &arena, &transaction);
    let listeners = plugin_order::activation_order(loaded, &arena, &transaction.operations);
    Ok(LocalTransaction {
        arena,
        present,
        unchanged_names,
        transaction,
        missing,
        listeners,
    })
}

/// The plugin classes this run loads, for the names the `-v` lines print
/// (`verbose_listeners`): the first `Composer` loads the installed plugins
/// (`loaded`, from installed.json as written), then each plugin operation
/// of the transaction registers its target (`PluginInstaller::install` —
/// unless that plugin is registered already — and `update`).
fn note_plugin_operations(
    run: &Run<'_>,
    loaded: &[String],
    installed: &[serde_json::Value],
    arena: &[vivacity_resolver::package::Package],
    transaction: &vivacity_resolver::transaction::Transaction,
) {
    if run.args.no_plugins {
        return;
    }
    crate::verbose_listeners::first_load(&run.manifest, loaded, installed);
    let locked: Vec<&serde_json::Value> = ["packages", "packages-dev"]
        .iter()
        .filter_map(|k| run.lock_value.get(*k).and_then(serde_json::Value::as_array))
        .flatten()
        .collect();
    let target_of = |name: &str| {
        locked.iter().copied().find(|p| {
            p.get("name")
                .and_then(serde_json::Value::as_str)
                .is_some_and(|n| n.eq_ignore_ascii_case(name))
        })
    };
    let plugin_type = |p: &vivacity_resolver::package::Package| {
        matches!(
            p.package_type.as_str(),
            "composer-plugin" | "composer-installer"
        )
    };
    let allowed = |name: &str| {
        matches!(
            vivacity_core::layout::plugin_allowed(&run.manifest, name),
            vivacity_core::layout::PluginVerdict::Allowed
        )
    };
    let mut registered: Vec<String> = loaded.iter().filter(|n| allowed(n)).cloned().collect();
    use vivacity_resolver::transaction::Operation;
    for op in &transaction.operations {
        let (target, update) = match *op {
            Operation::Install(p) => (p, false),
            Operation::Update(_, t) => (t, true),
            Operation::Uninstall(p) => {
                registered.retain(|n| *n != arena[p].name);
                continue;
            }
            _ => continue,
        };
        let name = arena[target].name.as_str();
        if !plugin_type(&arena[target]) || !allowed(name) {
            continue;
        }
        if !update && registered.iter().any(|n| n == name) {
            continue;
        }
        if let Some(entry) = target_of(name) {
            crate::verbose_listeners::plugin_registered(name, entry);
        }
        if !registered.iter().any(|n| n == name) {
            registered.push(name.to_owned());
        }
    }
}

/// The scope analysis is pure (lock, manifest, installed.json, global
/// config): computed here, reported after the join. `None` for a dry run.
fn analyze_scope(run: &Run<'_>) -> Option<vivacity_core::scope::ScopeReport> {
    let args = run.args;
    let scope = if args.dry_run {
        None
    } else {
        let mut report = vivacity_core::scope::analyze(
            &run.project,
            &run.lock,
            &run.manifest,
            run.with_dev,
            !args.no_plugins,
        );
        // `POST_INSTALL_CMD` only: not the install that follows an update.
        if !args.after_update() {
            report
                .issues
                .extend(vivacity_core::scope::core_project_message_issue(
                    &run.project,
                    &run.lock,
                    &run.manifest,
                    run.with_dev,
                    !args.no_plugins,
                ));
        }
        // The second round of emulated plugins (docs/plans/
        // plugins-round2.md): what their listeners would do that vivacity
        // does not reproduce. The install that follows an update was
        // checked on the solved lock already, its interactivity included.
        let installed =
            plugin_order::installed_json_packages(&composer_dir_of(&run.project, &run.manifest));
        let global = crate::effect_plugins::global_packages();
        let ctx = vivacity_core::effect_plugins::Context {
            project: &run.project,
            manifest: &run.manifest,
            local: run
                .lock
                .wanted_packages(run.with_dev)
                .map(|p| &p.raw)
                .collect(),
            installed: &installed,
            dev_mode: run.with_dev,
            command: if args.after_update() {
                vivacity_core::effect_plugins::Command::Update
            } else {
                vivacity_core::effect_plugins::Command::Install
            },
            interactive: !args.after_update()
                && crate::effect_plugins::interactive(args.compat.no_interaction),
            no_autoloader: args.no_autoloader,
            plugins_enabled: !args.no_plugins,
            global: &global,
            aliases: !run.lock.aliases.is_empty(),
            lock_data: Some(&run.lock_value),
        };
        report.issues.extend(
            vivacity_core::effect_plugins::issues(&ctx)
                .into_iter()
                .map(vivacity_core::scope::ScopeIssue::Layout),
        );
        Some(report)
    };

    trace("scope analysis", run.t0);
    scope
}

/// The autoloader, planned during the network wait when the install has
/// nothing to place (every wanted package present, same identity): its
/// inputs are then all known — the local repository the install would
/// produce, the manifest, the layout — and `plan` writes nothing under
/// vendor/. Kept as a `Result` and only looked at where the dump runs
/// today, so an error surfaces at the same point with the same text.
/// Not with `--run-scripts` (pre-autoload-dump may edit sources).
fn plan_autoload_early(
    run: &Run<'_>,
    tx: &LocalTransaction,
    scope: Option<&vivacity_core::scope::ScopeReport>,
) -> Option<anyhow::Result<PlannedDump>> {
    let args = run.args;
    // liborm85/composer-vendor-cleaner and cakephp/plugin-installer change
    // the tree or the root's autoload at PRE_AUTOLOAD_DUMP: not before.
    let early_dump: Option<anyhow::Result<PlannedDump>> = if args.dry_run
        || args.no_autoloader
        || run.runner.is_some()
        || !tx.transaction.operations.is_empty()
        || crate::effect_plugins::dump_depends_on_listeners(
            &run.lock,
            &run.manifest,
            run.with_dev,
            !args.no_plugins,
        ) {
        None
    } else {
        scope
            .filter(|s| s.is_native_ok())
            .and_then(|s| s.layout.as_ref())
            .and_then(|layout| {
                vivacity_core::installer::local_repository_if_unchanged(
                    &run.lock,
                    layout,
                    run.with_dev,
                )
                .map(|local| {
                    dump_autoload_plan(
                        &run.project,
                        &local,
                        &run.manifest,
                        layout,
                        run.with_dev,
                        args.optimize_autoloader || args.classmap_authoritative,
                        args.classmap_authoritative,
                        run.ignore_platform_reqs,
                        &run.ignore_platform_req,
                        (args.apcu_autoloader, args.apcu_autoloader_prefix.as_deref()),
                        !args.no_plugins,
                        run.lock
                            .packages_dev
                            .iter()
                            .map(|p| p.name().to_owned())
                            .collect(),
                        // A no-op: nothing placed.
                        Vec::new(),
                    )
                })
            })
    };
    trace("autoload planned", run.t0);
    early_dump
}

/// The verification joined, reported as `doInstall` does: the list
/// filter's warnings (written while the pool was built), the resolution
/// line (`-v`), then the problems (`SolverProblemsException`, exit
/// `max(1, 2)`) or the operations a solved lock should not have (exit 4).
fn join_verification(run: &Run<'_>, verification: Verification) -> anyhow::Result<Flow> {
    use vivacity_resolver::session::InstallVerdict;
    let mut verification = verification;
    let Some(handle) = verification.handle.take() else {
        return Ok(Flow::Continue(()));
    };
    // Sent before the join already; dropped so that a thread still waiting
    // could never wait forever.
    drop(verification.root_version.take());
    let verified = match handle
        .join()
        .map_err(|_| anyhow::anyhow!("the lock verification thread panicked"))?
    {
        Ok(v) => v,
        // A request the list filter would make that Composer treats in a
        // way vivacity does not (`secure-http` read from auth.json): the
        // run is Composer's, nothing written yet — the headline and
        // « Verifying… » are printed already, and Composer prints them
        // again (the late hand-over of HANDOVER.md).
        Err(e) if e.kind == vivacity_resolver::session::SessionErrorKind::Unsupported => {
            let scope = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::Layout(e.message)],
                skipped_plugins: vec![],
                layout: None,
            };
            return Ok(Flow::Break(fallback_or_fail(run.args, &scope)?));
        }
        Err(e) => {
            // Written by Composer before it threw (a degraded repository).
            for line in &e.preface {
                vivacity_core::say!("{line}");
            }
            return Err(session_error(e));
        }
    };
    trace("lock verification", run.t0);
    for w in &verified.warnings {
        vivacity_core::say!("{w}");
    }
    // No reference here: Composer does not run without php.
    if verified.php_missing && !verification.ignores_all && verification.lock_platform {
        vivacity_core::say!(
            "Warning: php not found, platform requirements were not checked \
             (--ignore-platform-reqs silences this warning)"
        );
    }
    say_lock_resolution(verified.resolution);
    match verified.verdict {
        InstallVerdict::Installable => Ok(Flow::Continue(())),
        InstallVerdict::Problems(pretty) => {
            // The headline at QUIET, the problems at the default level.
            let head = "Your lock file does not contain a compatible set of packages. Please run composer update.";
            vivacity_core::say_always!("{head}");
            vivacity_core::say!("{pretty}");
            // `$ghe->emit($err."\n".$prettyProblem)` (Installer.php:829).
            vivacity_core::io::github_action_error(&format!("{head}\n{pretty}"));
            Ok(Flow::Break(2))
        }
        InstallVerdict::NeedsChanges => {
            vivacity_core::say_always!("Your lock file cannot be installed on this system without changes. Please run composer update.");
            Ok(Flow::Break(4))
        }
        // The exception leaves `doInstall` after the resolution line.
        InstallVerdict::Invalid(message) => Err(anyhow::anyhow!("{message}")),
    }
}

/// The root requirements the lock does not satisfy: printed, then exit 4
/// unless `allow-missing-requirements`.
fn report_missing(
    run: &Run<'_>,
    missing: &[String],
    verification: &mut Verification,
) -> anyhow::Result<Flow> {
    if !missing.is_empty() {
        // On a bare vendor the plugin is not active yet in Composer's run:
        // it would install itself, then run a partial `composer update` of
        // the merged requirements and rewrite the lock. vivacity does not
        // do that on a user's behalf: the lock goes to Composer, with the
        // reason. With the plugin installed, Composer refuses like this.
        if let Some(m) = &run.merged {
            let plugin_installed =
                installed_packages(&run.project, &run.manifest)
                    .iter()
                    .any(|p| {
                        p.get("name").and_then(|n| n.as_str())
                            == Some(vivacity_resolver::merge_plugin::PLUGIN_NAME)
                    });
            if !plugin_installed {
                let report = vivacity_core::scope::ScopeReport {
                    issues: vec![vivacity_core::scope::ScopeIssue::MergePlugin(format!(
                        "the lock does not satisfy the merged requirements ({}); Composer would run the plugin's implicit update and rewrite composer.lock",
                        m.merged_names.join(", ")
                    ))],
                    ..Default::default()
                };
                verification.abandon_and_wait();
                return Ok(Flow::Break(fallback_or_fail(run.args, &report)?));
            }
        }
        for line in missing {
            vivacity_core::say!("{line}");
        }
        if !require::truthy(require::config_value(
            &run.manifest,
            "allow-missing-requirements",
        )) {
            verification.abandon();
            return Ok(Flow::Break(4));
        }
    }
    Ok(Flow::Continue(()))
}

/// `Package operations: …` (the operation list itself at `-v`), or
/// `Nothing to install, update or remove`.
fn report_operations(tx: &LocalTransaction) {
    use vivacity_resolver::transaction::Operation;
    let ops = &tx.transaction.operations;
    let installs = ops
        .iter()
        .filter(|o| matches!(o, Operation::Install(_)))
        .count();
    let updates = ops
        .iter()
        .filter(|o| matches!(o, Operation::Update(..)))
        .count();
    let removals = ops
        .iter()
        .filter(|o| matches!(o, Operation::Uninstall(_)))
        .count();
    if installs + updates + removals == 0 {
        vivacity_core::say!("Nothing to install, update or remove");
    } else {
        vivacity_core::say!(
            "Package operations: {installs} install{}, {updates} update{}, {removals} removal{}",
            if installs == 1 { "" } else { "s" },
            if updates == 1 { "" } else { "s" },
            if removals == 1 { "" } else { "s" }
        );
        for line in vivacity_resolver::transaction::verbose_operation_summary(ops, &tx.arena) {
            vivacity_core::say_verbose!("{line}");
        }
    }
}

/// A dry run stops after the operations: their lines in transaction order,
/// then (an update's suggestions and) the abandoned packages, and the
/// funding count — no dump, and no `POST_*_CMD` (`runScripts` is off).
/// 0, unless the lock has no `packages-dev` ([`report_before_dump`]).
fn dry_run(run: &Run<'_>, tx: &LocalTransaction) -> anyhow::Result<i32> {
    // Plugins activated when the `Composer` was created: a dry run executes
    // no operation, so only those loaded from installed.json.
    crate::no_install::activate_yii2_composer(&run.project, &run.manifest, !run.args.no_plugins)?;
    for op in &tx.transaction.operations {
        if let Some(line) = op.show(&tx.arena, false) {
            vivacity_core::say!("  - {line}");
        }
    }
    // `Installer::run` after `doInstall`.
    report_before_dump(run)?;
    print_funding(&run.project, &run.manifest);
    Ok(0)
}

/// `Installer::run` after `doInstall`/`doUpdate`, before the dump
/// (Installer.php:343-373): an update's suggestions and the abandoned
/// packages of its new lock, precomputed by the update, which knows the
/// operations; for an install, the abandoned packages of the lock (dev
/// included).
fn report_before_dump(run: &Run<'_>) -> anyhow::Result<()> {
    let say_all = |lines: &[String]| {
        for line in lines {
            vivacity_core::say!("{line}");
        }
    };
    match &run.args.post_update {
        Some(report) => say_all(&report.lines),
        None => {
            // `$this->locker->getLockedRepository(true)` (Installer.php:356),
            // dev mode or not: a `--no-dev` install of a lock without
            // `packages-dev` fails here, its packages laid out, before the
            // autoloader.
            refuse_lock_without_dev(run)?;
            say_all(&abandoned_warnings(&run.lock_value));
        }
    }
    Ok(())
}

/// Out of scope: Composer as fallback (default) or fail explicitly. In
/// scope: the notes on what is emulated or skipped, then the layout the
/// install places packages by (`--check-scope` stops here).
fn native_layout(
    run: &Run<'_>,
    scope: Option<vivacity_core::scope::ScopeReport>,
) -> anyhow::Result<Flow<vivacity_core::layout::Layout>> {
    let Some(scope) = scope else {
        anyhow::bail!("internal: scope was not analysed");
    };
    if !scope.is_native_ok() {
        return Ok(Flow::Break(fallback_or_fail(run.args, &scope)?));
    }
    let Some(layout) = scope.layout else {
        anyhow::bail!("internal: scope is native but no layout was resolved");
    };
    if let Some(tag) = &layout.installers_tag {
        vivacity_core::say!(
            "Note: composer/installers {tag} emulated natively (custom install paths)"
        );
    }
    for plugin in &scope.skipped_plugins {
        vivacity_core::say!(
            "Note: plugin {plugin} installed as a plain library (vivacity never runs plugins)"
        );
    }
    trace("scope", run.t0);
    if run.args.check_scope {
        vivacity_core::say_always!("vivacity: this lock is installed natively");
        return Ok(Flow::Break(0));
    }
    Ok(Flow::Continue(layout))
}

/// The installer's report, and the runtime it ran on: kept until the end
/// of `run_install`, where it always was dropped (dropping a runtime waits
/// for its blocking tasks).
struct Installed {
    report: vivacity_core::installer::InstallReport,
    _runtime: tokio::runtime::Runtime,
}

/// The operations: their lines decided on the state before the
/// transaction, the transaction itself, then the lines (codeception/c3's
/// `uninstall` before its own); then, as `Installer::run` prints them
/// before the dump, an update's suggestions and the abandoned packages.
fn execute_operations(
    run: &Run<'_>,
    tx: &LocalTransaction,
    layout: &vivacity_core::layout::Layout,
) -> anyhow::Result<Flow<Installed>> {
    let args = run.args;
    // The operation lines of a real install, in transaction order, with the
    // downloader's appendix (`getInstallOperationAppendix`: `: Extracting
    // archive`, `: Symlinking from …`, `: Mirroring from …`, `: Source
    // already present`) computed on the state before the transaction, like
    // Composer does right before each operation. They are printed once the
    // transaction has succeeded: the placements run in parallel, and a
    // failure is reported alone.
    let operation_lines = operation_lines(
        &run.project,
        &tx.arena,
        &tx.transaction.operations,
        layout,
        run.lock
            .flex_packs(&run.manifest, run.with_dev, !args.no_plugins),
        !args.no_plugins,
        &run.manifest,
    )?;
    // Composer decides these before it fetches anything; computed here for the
    // same reason `operation_lines` is — our own fetch fills that cache. The
    // names are the downloads themselves (one predicate for both).
    // `startup_hand_over` handed over what `files_cache` refuses.
    let files_cache = vivacity_core::fetch::files_cache(
        run.manifest.get("config"),
        vivacity_core::fetch::with_global_json(&run.project, "auth.json", |a| a.cloned()).as_ref(),
    )
    .unwrap_or(vivacity_core::fetch::FilesCache::Enabled);
    let (downloading, downloads) = download_lines(
        &run.lock,
        &tx.arena,
        &tx.transaction.operations,
        run.with_dev,
        files_cache,
        args.offline,
    );

    // Transaction.
    let store = Arc::new(vivacity_core::store::Store::default_location());
    let auth = vivacity_core::fetch::Auth::load(&run.project);
    let mut fetcher =
        vivacity_core::fetch::Fetcher::new(vivacity_core::fetch::composer_cache_dir(), auth)?;
    if files_cache == vivacity_core::fetch::FilesCache::Disabled {
        fetcher = fetcher.without_files_cache();
    }
    let fetcher = Arc::new(fetcher);
    // The identities the dump that follows can use: none without a dump,
    // or when scripts run between the placement and the dump (which then
    // takes nothing from the placement).
    let placement_identities = if args.no_autoloader || run.runner.is_some() {
        vivacity_core::installer::PlacementIdentities::None
    } else if effective_optimize(
        &run.manifest,
        args.optimize_autoloader,
        args.classmap_authoritative,
    ) {
        vivacity_core::installer::PlacementIdentities::AllRules
    } else {
        vivacity_core::installer::PlacementIdentities::Classmap
    };
    let opts = vivacity_core::installer::InstallOptions {
        with_dev: run.with_dev,
        offline: args.offline,
        plugins_enabled: !args.no_plugins,
        placement_identities,
        downloads: Some(downloads),
        ..Default::default()
    };
    let runtime = tokio::runtime::Runtime::new().context("cannot start the async runtime")?;
    let report = match runtime.block_on(vivacity_core::installer::install(
        &run.project,
        &run.lock,
        &run.manifest,
        layout,
        store,
        fetcher,
        &opts,
    )) {
        Ok(r) => {
            // Every download is in: what was held goes out as it was.
            vivacity_core::io::release_output();
            r
        }
        // Emulation refusal detected before any write: vendor/ is intact.
        Err(vivacity_core::Error::Unsupported(msg)) => {
            let scope = vivacity_core::scope::ScopeReport {
                issues: vec![vivacity_core::scope::ScopeIssue::Layout(msg)],
                skipped_plugins: vec![],
                layout: None,
            };
            return Ok(Flow::Break(fallback_or_fail(args, &scope)?));
        }
        Err(vivacity_core::Error::Refused(msg)) => {
            vivacity_core::say_always!("{msg}");
            return Ok(Flow::Break(1));
        }
        // A download that failed: Composer printed every line of the batch
        // (the registration loop) before the error — point 12, for the
        // downloads.
        Err(
            e @ (vivacity_core::Error::Http { .. }
            | vivacity_core::Error::Transport(_)
            | vivacity_core::Error::ShasumMismatch { .. }),
        ) => {
            // The run's own end: what was held goes out first.
            vivacity_core::io::release_output();
            for line in &downloading {
                vivacity_core::say!("{line}");
            }
            return Err(e.into());
        }
        Err(e) => return Err(e.into()),
    };
    trace("install transaction", run.t0);
    for line in &downloading {
        vivacity_core::say!("{line}");
    }
    // A redirect to an insecure host (`secure-http` false): Composer warns as
    // its wait loop restarts the job, after the lines above.
    for line in vivacity_core::secure_http::take_redirect_warnings() {
        vivacity_core::say!("{line}");
    }
    // codeception/c3's `uninstall` when this transaction removes the plugin:
    // `PluginInstaller::uninstall` calls it before `LibraryInstaller`
    // removes the code and prints the operation's line.
    let c3_leaves = tx.transaction.operations.iter().any(|op| {
        matches!(*op, vivacity_resolver::transaction::Operation::Uninstall(p)
            if tx.arena[p].name == vivacity_core::c3_plugin::PLUGIN_NAME)
    });
    let c3_line = format!("  - Removing {} (", vivacity_core::c3_plugin::PLUGIN_NAME);
    let mut c3_uninstalled = false;
    for line in &operation_lines {
        if c3_leaves && !c3_uninstalled && line.starts_with(&c3_line) {
            emulate_c3_uninstall(&run.project, &run.manifest, !args.no_plugins)?;
            c3_uninstalled = true;
        }
        vivacity_core::say!("{line}");
    }
    if c3_leaves && !c3_uninstalled {
        emulate_c3_uninstall(&run.project, &run.manifest, !args.no_plugins)?;
    }
    // `BinaryInstaller` notices belong to the operations, before the dump.
    for m in &report.messages {
        vivacity_core::say!("{m}");
    }
    report_before_dump(run)?;
    Ok(Flow::Continue(Installed {
        report,
        _runtime: runtime,
    }))
}

/// `Installer::run`'s dump, after `doInstall`: the "Generating autoload
/// files" line, pre-autoload-dump, the autoloader (the plan made during the
/// network wait, or made now), the emulated post-autoload-dump plugins,
/// post-autoload-dump. Returns the closing line's autoloader note, and the
/// counts liborm85/composer-vendor-cleaner reports at post-install-cmd.
fn dump_autoloader(
    run: &Run<'_>,
    tx: &LocalTransaction,
    layout: &vivacity_core::layout::Layout,
    report: &vivacity_core::installer::InstallReport,
    early_dump: Option<anyhow::Result<PlannedDump>>,
) -> anyhow::Result<Flow<(String, Option<vivacity_core::vendor_cleaner::Counts>)>> {
    let args = run.args;
    // `Installer::run` (Installer.php:377-381), before
    // `AutoloadGenerator::dump` dispatches PRE_AUTOLOAD_DUMP: "optimized"
    // as soon as the effective optimize flag is on — the option,
    // `config.optimize-autoloader`, or class-map authoritative (which
    // implies it), the same computation `dump_autoload_plan` makes.
    vivacity_core::say!(
        "Generating{} autoload files",
        if effective_optimize(
            &run.manifest,
            args.optimize_autoloader,
            args.classmap_authoritative
        ) {
            " optimized"
        } else {
            ""
        }
    );
    // `AutoloadGenerator::dump` dispatches PRE_AUTOLOAD_DUMP: the plugins'
    // listeners (-v lines only: php-http/discovery's is silent), then the
    // scripts.
    if !args.no_plugins {
        announce_in_order(
            &tx.listeners,
            crate::verbose_listeners::PRE_AUTOLOAD_DUMP,
            &run.manifest,
        );
    }
    // `AutoloadGenerator::dump($localRepo)`: the local repository, not
    // the lock (they differ for an unchanged package whose lock entry
    // moved).
    let local = report.local_repository.as_ref().unwrap_or(&run.lock);
    // The listeners that act there (liborm85 cleans the packages, cakephp
    // extends the root's autoload), before the scripts.
    let packages: Vec<&vivacity_core::lock::LockPackage> =
        local.wanted_packages(run.with_dev).collect();
    let (root, cleaner_counts) = crate::effect_plugins::pre_autoload_dump(
        &run.manifest,
        layout,
        local,
        &packages,
        run.with_dev,
        !args.no_plugins,
        &tx.listeners,
        false,
    )?;
    if let Some(r) = &run.runner {
        let code = r.run(scripts::PRE_AUTOLOAD_DUMP)?;
        if code != 0 {
            return Ok(Flow::Break(code));
        }
    }
    let planned = match early_dump {
        // Planned during the network wait: the install placed nothing,
        // the inputs are what they were.
        Some(planned) => planned?,
        None => dump_autoload_plan(
            &run.project,
            local,
            &root,
            layout,
            run.with_dev,
            args.optimize_autoloader || args.classmap_authoritative,
            args.classmap_authoritative,
            run.ignore_platform_reqs,
            &run.ignore_platform_req,
            (args.apcu_autoloader, args.apcu_autoloader_prefix.as_deref()),
            !args.no_plugins,
            // `$localRepo->setDevPackageNames($this->locker->getDevPackageNames())`
            run.lock
                .packages_dev
                .iter()
                .map(|p| p.name().to_owned())
                .collect(),
            // What this run placed, as it was right after the placement —
            // unless scripts ran since (`pre-autoload-dump`, the package
            // events): a file they rewrote in place within the timestamp
            // granularity would keep its identity.
            if run.runner.is_some() {
                Vec::new()
            } else {
                report.placed.clone()
            },
        )?,
    };
    let dumped = planned.finish(&run.project, &run.manifest, layout)?;
    let autoload_note = format!(", autoloader with {} classes", dumped.classes);
    post_autoload_dump_plugins(run, tx, local, layout)?;
    // `AutoloadGenerator::dump`: post-autoload-dump once the files are
    // written (the emulated post-autoload-dump plugins included).
    if let Some(r) = &run.runner {
        let code = r.run(scripts::POST_AUTOLOAD_DUMP)?;
        if code != 0 {
            return Ok(Flow::Break(code));
        }
    }
    trace("autoload dump", run.t0);
    Ok(Flow::Continue((autoload_note, cleaner_counts)))
}

/// The local repository's order after the transaction (the previous
/// installed.json order minus the removed and updated packages, then the
/// operations' order), with the names the transaction removed or updated
/// and those it installed or updated.
fn local_order(tx: &LocalTransaction) -> (Vec<&str>, Vec<&str>, Vec<&str>) {
    use vivacity_resolver::transaction::Operation;
    let arena = &tx.arena;
    let previous: Vec<&str> = match &tx.unchanged_names {
        Some(names) => names.iter().map(String::as_str).collect(),
        None => tx.present.iter().map(|&i| arena[i].name.as_str()).collect(),
    };
    let mut gone: Vec<&str> = Vec::new();
    let mut fresh: Vec<&str> = Vec::new();
    for op in &tx.transaction.operations {
        match *op {
            Operation::Uninstall(p) => gone.push(arena[p].name.as_str()),
            Operation::Update(i, t) => {
                gone.push(arena[i].name.as_str());
                fresh.push(arena[t].name.as_str());
            }
            Operation::Install(p) => fresh.push(arena[p].name.as_str()),
            _ => {}
        }
    }
    let order = vivacity_core::pest_plugin::local_repository_order(&previous, &gone, &fresh);
    (order, gone, fresh)
}

/// Plugins listening to post-autoload-dump, emulated: the local
/// repository's order is the previous installed.json order minus
/// the removed and updated packages, then the operations' order.
fn post_autoload_dump_plugins(
    run: &Run<'_>,
    tx: &LocalTransaction,
    local: &vivacity_core::lock::Lock,
    layout: &vivacity_core::layout::Layout,
) -> anyhow::Result<()> {
    let args = run.args;
    let (order, gone, fresh) = local_order(tx);
    let previously_present = match &tx.unchanged_names {
        Some(names) => names
            .iter()
            .any(|n| n == vivacity_core::pest_plugin::PLUGIN_NAME),
        None => tx
            .present
            .iter()
            .any(|&i| tx.arena[i].name == vivacity_core::pest_plugin::PLUGIN_NAME),
    };
    emulate_pest_plugin(
        &run.project,
        local,
        &run.manifest,
        run.with_dev,
        &order,
        !args.no_plugins,
        previously_present,
    )?;
    // yiisoft/yii2-composer: `activate` then its installer's
    // per-operation rewrites of extensions.php — one write here,
    // when an extension was installed, updated or removed.
    let touched: Vec<&str> = gone.iter().chain(fresh.iter()).copied().collect();
    emulate_yii2_composer(
        &run.project,
        local,
        &run.manifest,
        run.with_dev,
        &order,
        &touched,
        !args.no_plugins,
    )?;
    // cakephp/plugin-installer's `cakephp-plugins.php` (silent).
    let packages: Vec<&vivacity_core::lock::LockPackage> =
        local.wanted_packages(run.with_dev).collect();
    crate::effect_plugins::post_autoload_dump(
        &run.manifest,
        layout,
        local,
        &packages,
        run.with_dev,
        !args.no_plugins,
    )?;
    // The ones that print, in their plugins' activation order.
    let drupol = crate::effect_plugins::drupol_run(
        Some(&run.lock_value),
        local,
        &run.manifest,
        run.with_dev,
        !args.no_plugins,
    );
    post_autoload_dump_printers(
        &run.project,
        local,
        &run.manifest,
        run.with_dev,
        !args.no_plugins,
        &tx.listeners,
        drupol.as_ref(),
    )
}

/// The `POST_AUTOLOAD_DUMP` listeners that write lines —
/// bamarni/composer-bin-plugin's deprecations (stderr),
/// composer/package-versions-deprecated's two lines and
/// drupol/composer-packages' two lines (stdout) — in the order their
/// plugins were activated (`plugin_order`). The silent ones (pest-plugin,
/// yii2-composer) depend on nothing the others do.
pub(crate) fn post_autoload_dump_printers(
    project: &std::path::Path,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
    plugins_enabled: bool,
    listeners: &[String],
    drupol: Option<&crate::effect_plugins::DrupolRun<'_>>,
) -> anyhow::Result<()> {
    // The printers, and under -v every listener of the event: each plugin's
    // `> post-autoload-dump: …` line precedes what it prints.
    let mut emulated = vec![
        vivacity_core::bamarni_bin::PLUGIN_NAME,
        vivacity_core::package_versions::PLUGIN_NAME,
        vivacity_core::effect_plugins::DRUPOL,
    ];
    let event = crate::verbose_listeners::POST_AUTOLOAD_DUMP;
    for name in crate::verbose_listeners::listening_to(event) {
        if !emulated.contains(&name) {
            emulated.push(name);
        }
    }
    for plugin in plugin_order::listeners_in_order(listeners, &emulated) {
        let loaded = plugins_enabled && listeners.iter().any(|n| n == plugin);
        if loaded {
            crate::verbose_listeners::announce(plugin, event, manifest);
        }
        if plugin == vivacity_core::bamarni_bin::PLUGIN_NAME {
            // Composer calls it when the plugin is loaded — installed, its
            // classes on disk, whatever the dev mode of this dump.
            if loaded {
                emulate_bamarni_bin(manifest);
            }
        } else if plugin == vivacity_core::package_versions::PLUGIN_NAME {
            emulate_package_versions(project, local, manifest, with_dev, plugins_enabled)?;
        } else if plugin == vivacity_core::effect_plugins::DRUPOL {
            if let Some(run) = drupol {
                crate::effect_plugins::composer_packages(project, manifest, run)?;
            }
        }
    }
    Ok(())
}

/// The `-v` lines of `event` for the plugins loaded (`listeners`, in
/// activation order) that listen to it and print nothing else there.
pub(crate) fn announce_in_order(listeners: &[String], event: &str, manifest: &serde_json::Value) {
    let names = crate::verbose_listeners::listening_to(event);
    for plugin in listeners {
        if names.contains(&plugin.as_str()) {
            crate::verbose_listeners::announce(plugin, event, manifest);
        }
    }
}

/// The end of `Installer::run` (Installer.php:412-442): the funding count,
/// then `POST_INSTALL_CMD` / `POST_UPDATE_CMD` — the plugins' listeners
/// first (all at priority 0, in the order their plugins were activated:
/// `listeners`, `plugin_order`), then the scripts of composer.json, which
/// `EventDispatcher::getListeners` appends after the plugins' priority-0
/// listeners. Runs without the dump too (`--no-autoloader`), as in
/// Composer.
fn post_install(
    run: &Run<'_>,
    layout: &vivacity_core::layout::Layout,
    report: &vivacity_core::installer::InstallReport,
    tx: &LocalTransaction,
    cleaner_counts: Option<&vivacity_core::vendor_cleaner::Counts>,
) -> anyhow::Result<Flow> {
    let args = run.args;
    let listeners = &tx.listeners;
    let (order, _, _) = local_order(tx);
    print_funding(&run.project, &run.manifest);
    let local = report.local_repository.as_ref().unwrap_or(&run.lock);
    if !args.no_plugins {
        // laminas/laminas-skeleton-installer listens at priority 1000
        // (`Plugin::getSubscribedEvents`): before every listener at 0.
        crate::effect_plugins::skeleton(&run.project, &run.manifest, local, run.with_dev, true)?;
        let mut emulated = vec![
            vivacity_core::phpcs_installer::PLUGIN_NAME,
            extension_installers::PHPSTAN,
            extension_installers::RECTOR,
            extension_installers::INFECTION,
            vivacity_core::c3_plugin::PLUGIN_NAME,
            "symfony/flex",
            vivacity_core::effect_plugins::DG_CLEANER,
            vivacity_core::effect_plugins::VENDOR_CLEANER,
            vivacity_core::effect_plugins::PATCHER,
        ];
        // `Installer::run` (Installer.php:440): POST_UPDATE_CMD after an
        // update, POST_INSTALL_CMD otherwise. Under -v each listener's line
        // precedes what it prints.
        let event = if args.after_update() {
            crate::verbose_listeners::POST_UPDATE_CMD
        } else {
            crate::verbose_listeners::POST_INSTALL_CMD
        };
        for name in crate::verbose_listeners::listening_to(event) {
            if !emulated.contains(&name) {
                emulated.push(name);
            }
        }
        for plugin in plugin_order::listeners_in_order(listeners, &emulated) {
            if listeners.iter().any(|n| n == plugin) {
                crate::verbose_listeners::announce(plugin, event, &run.manifest);
            }
            post_install_listener(run, layout, local, &order, plugin, cleaner_counts)?;
        }
    }
    if let Some(r) = &run.runner {
        let code = r.run(scripts::POST_INSTALL_CMD)?;
        if code != 0 {
            return Ok(Flow::Break(code));
        }
    }
    Ok(Flow::Continue(()))
}

/// One emulated `POST_INSTALL_CMD` / `POST_UPDATE_CMD` listener; each
/// checks that its plugin is installed and allowed.
fn post_install_listener(
    run: &Run<'_>,
    layout: &vivacity_core::layout::Layout,
    local: &vivacity_core::lock::Lock,
    order: &[&str],
    plugin: &str,
    cleaner_counts: Option<&vivacity_core::vendor_cleaner::Counts>,
) -> anyhow::Result<()> {
    let args = run.args;
    match plugin {
        vivacity_core::effect_plugins::DG_CLEANER => crate::effect_plugins::composer_cleaner(
            &run.manifest,
            layout,
            local,
            run.with_dev,
            !args.no_plugins,
        )?,
        vivacity_core::effect_plugins::VENDOR_CLEANER => {
            crate::effect_plugins::vendor_cleaner_finish(
                &run.manifest,
                layout,
                local,
                run.with_dev,
                !args.no_plugins,
                cleaner_counts,
            )?
        }
        vivacity_core::phpcs_installer::PLUGIN_NAME => {
            emulate_phpcs(&run.project, layout, local, &run.manifest, run.with_dev)?;
        }
        extension_installers::PHPSTAN => extension_installers::phpstan(
            layout,
            local,
            &run.lock.aliases,
            &run.manifest,
            run.with_dev,
            !args.no_plugins,
        )?,
        extension_installers::RECTOR => extension_installers::rector(
            layout,
            local,
            &run.manifest,
            run.with_dev,
            !args.no_plugins,
        )?,
        extension_installers::INFECTION => extension_installers::infection(
            layout,
            local,
            order,
            &run.manifest,
            run.with_dev,
            !args.no_plugins,
        )?,
        vivacity_core::effect_plugins::PATCHER => {
            if let Some(patched) = crate::effect_plugins::patcher_post(
                &run.project,
                &run.manifest,
                layout,
                local,
                order,
                run.with_dev,
                !args.no_plugins,
            )? {
                // `setPatchedPackageData`: installed.json written again.
                let root = vivacity_core::state::RootPackage::detect(
                    &run.manifest,
                    &run.project,
                    run.with_dev,
                );
                vivacity_core::state::write_state_files(
                    &layout.composer_dir(),
                    &patched,
                    &root,
                    &run.manifest,
                    run.with_dev,
                    layout,
                )?;
            }
        }
        vivacity_core::c3_plugin::PLUGIN_NAME => emulate_c3(
            &run.project,
            local,
            &run.manifest,
            run.with_dev,
            args.after_update(),
            !args.no_plugins,
        )?,
        // symfony/flex: `install` on `POST_INSTALL_CMD`, `update` on
        // `POST_UPDATE_CMD` (decided by the update, which saw the operations).
        "symfony/flex" => match &args.post_update {
            None => emulate_flex_install(&run.project, &run.manifest, !args.no_plugins)?,
            Some(update) if update.flex_active => {
                print_flex_post_update(
                    &update.manifest,
                    update.thanks_reminder,
                    update.flex_plan.as_deref(),
                )?;
            }
            Some(_) => {}
        },
        _ => {}
    }
    Ok(())
}

/// dealerdirect/phpcodesniffer-composer-installer's `POST_INSTALL_CMD` /
/// `POST_UPDATE_CMD` listener (`Plugin::onDependenciesChangedEvent`):
/// with the plugin among `local`'s packages and allowed, PHP_CodeSniffer's
/// `installed_paths` registered from them; `saveInstalledPaths` writes its
/// line when it saved.
pub(crate) fn emulate_phpcs(
    project: &std::path::Path,
    layout: &vivacity_core::layout::Layout,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
) -> anyhow::Result<()> {
    use vivacity_core::phpcs_installer as phpcs;
    let installed: Vec<&vivacity_core::lock::LockPackage> =
        local.wanted_packages(with_dev).collect();
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, phpcs::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if let Some(own) = installed
        .iter()
        .find(|p| p.name() == phpcs::PLUGIN_NAME)
        .filter(|_| allowed)
    {
        let change = phpcs::register_standards(
            project,
            layout,
            &installed,
            manifest,
            phpcs::variant(own.version()),
        )?;
        if let Some(line) = change.line() {
            vivacity_core::out!("{line}");
        }
    }
    Ok(())
}

/// vivacity's closing line: what the install did and where it found it.
fn say_summary(
    run: &Run<'_>,
    report: &vivacity_core::installer::InstallReport,
    autoload_note: &str,
) {
    let warmed = if report.store_warmed > 0 {
        format!(", store warmed for {} packages", report.store_warmed)
    } else {
        String::new()
    };
    let git = if report.from_git > 0 {
        format!(", {} from git", report.from_git)
    } else {
        String::new()
    };
    vivacity_core::say!(
        "vivacity: {} installed, {} unchanged, {} removed ({} from store, {} from cache, {} from network{git}){warmed}{autoload_note} in {:.2}s",
        report.installed,
        report.unchanged,
        report.removed,
        report.store_hits,
        report.from_cache,
        report.from_network,
        run.t0.elapsed().as_secs_f32()
    );
}

/// `pestphp/pest-plugin`'s post-autoload-dump listener, emulated: with
/// plugins on and the plugin wanted, `vendor/pest-plugins.json` from the
/// installed packages' `extra.pest.plugins` in local-repository order
/// (`order`, package names); the file goes when the plugin leaves.
pub(crate) fn emulate_pest_plugin(
    project: &std::path::Path,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
    order: &[&str],
    plugins_enabled: bool,
    previously_present: bool,
) -> anyhow::Result<()> {
    let vendor = vivacity_core::dirs::Dirs::resolve(manifest)
        .unwrap_or_default()
        .vendor_dir(project);
    let wanted: std::collections::BTreeMap<&str, &vivacity_core::lock::LockPackage> = local
        .wanted_packages(with_dev)
        .map(|p| (p.name(), p))
        .collect();
    // Like Composer: a plugin listed as `false` in allow-plugins is skipped.
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, vivacity_core::pest_plugin::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if !plugins_enabled || !allowed || !wanted.contains_key(vivacity_core::pest_plugin::PLUGIN_NAME)
    {
        if previously_present {
            vivacity_core::pest_plugin::remove_pest_plugins(&vendor)?;
        }
        return Ok(());
    }
    let extras: Vec<Option<&serde_json::Value>> = order
        .iter()
        .filter_map(|n| wanted.get(n))
        .map(|p| p.raw.get("extra"))
        .collect();
    vivacity_core::pest_plugin::write_pest_plugins(&vendor, &extras, manifest.get("extra"))?;
    Ok(())
}

/// `yiisoft/yii2-composer`, emulated: with plugins on and the plugin
/// installed and allowed, `vendor/yiisoft/extensions.php` exists
/// (`activate`), and when a `yii2-extension` package was among the
/// operations (`touched`) the map is rewritten from the installed
/// extensions in local-repository order (`order`).
pub(crate) fn emulate_yii2_composer(
    project: &std::path::Path,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
    order: &[&str],
    touched: &[&str],
    plugins_enabled: bool,
) -> anyhow::Result<()> {
    use vivacity_core::yii2_composer as yii;
    let wanted: std::collections::BTreeMap<&str, &vivacity_core::lock::LockPackage> = local
        .wanted_packages(with_dev)
        .map(|p| (p.name(), p))
        .collect();
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, yii::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if !plugins_enabled || !allowed || !wanted.contains_key(yii::PLUGIN_NAME) {
        return Ok(());
    }
    let vendor = vivacity_core::dirs::Dirs::resolve(manifest)
        .unwrap_or_default()
        .vendor_dir(project);
    yii::ensure_extensions_file(&vendor)?;
    let is_extension = |n: &str| {
        wanted
            .get(n)
            .is_some_and(|p| p.package_type() == yii::EXTENSION_TYPE)
    };
    let extension_touched = touched.iter().any(|n| {
        is_extension(n)
            || local
                .packages
                .iter()
                .chain(local.packages_dev.iter())
                .any(|p| p.name() == *n && p.package_type() == yii::EXTENSION_TYPE)
    });
    if !extension_touched {
        return Ok(());
    }
    let entries: Vec<(&str, serde_json::Value)> = order
        .iter()
        .filter(|n| is_extension(n))
        .map(|n| (*n, yii::extension_entry(wanted[n])))
        .collect();
    yii::write_extensions(&vendor, &entries)?;
    Ok(())
}

/// `codeception/c3`'s `uninstall`, emulated (the transaction removes the
/// plugin): with plugins on and the plugin allowed, `c3.php` deleted from
/// the project root. Message on stdout, as `$io->write` prints.
pub(crate) fn emulate_c3_uninstall(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    plugins_enabled: bool,
) -> anyhow::Result<()> {
    use vivacity_core::c3_plugin as c3;
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, c3::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if plugins_enabled && allowed && c3::delete_c3(project)? {
        vivacity_core::out!("[codeception/c3] Deleting c3.php from the root of your project...");
    }
    Ok(())
}

/// `codeception/c3`'s `POST_INSTALL_CMD` / `POST_UPDATE_CMD` listener,
/// emulated: with plugins on and the plugin installed and allowed, `c3.php`
/// copied to the project root (`copyC3V2`; `askForUpdateV2` after an
/// update: no "up-to-date" line). Messages on stdout, as `$io->write`
/// prints.
pub(crate) fn emulate_c3(
    project: &std::path::Path,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
    after_update: bool,
    plugins_enabled: bool,
) -> anyhow::Result<()> {
    use vivacity_core::c3_plugin as c3;
    if !plugins_enabled {
        return Ok(());
    }
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, c3::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    let wanted = local
        .wanted_packages(with_dev)
        .any(|p| p.name() == c3::PLUGIN_NAME);
    if !wanted || !allowed {
        return Ok(());
    }
    let vendor = vivacity_core::dirs::Dirs::resolve(manifest)
        .unwrap_or_default()
        .vendor_dir(project);
    match c3::copy_c3(&vendor, project)? {
        c3::C3Action::UpToDate if !after_update => {
            vivacity_core::out!("[codeception/c3] c3.php is already up-to-date");
        }
        c3::C3Action::Copied => {
            vivacity_core::out!("[codeception/c3] Copying c3.php to the root of your project...");
            vivacity_core::out!("[codeception/c3] Include c3.php into index.php in order to collect codecoverage from server scripts");
        }
        _ => {}
    }
    Ok(())
}

/// bamarni/composer-bin-plugin's `POST_AUTOLOAD_DUMP` listener
/// (`onPostAutoloadDump`), for a loaded plugin: its `logDebug` line at -v,
/// then the deprecation lines again — unless `allow-plugins` refuses it.
pub(crate) fn emulate_bamarni_bin(manifest: &serde_json::Value) {
    use vivacity_core::bamarni_bin as bin;
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, bin::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if !allowed {
        return;
    }
    // `onPostAutoloadDump`'s `logDebug` (BamarniBinPlugin.php:88), at -v.
    vivacity_core::say_verbose!("[bamarni-bin] Calling onPostAutoloadDump().");
    if let Ok(cfg) = bin::config(manifest.get("extra")) {
        bin::print_deprecations(&cfg);
    }
}

/// `composer/package-versions-deprecated`'s `POST_AUTOLOAD_DUMP`
/// listener, emulated: with plugins on and the plugin installed and
/// allowed, its `Versions.php` is rewritten from the lock and the root
/// package (`vivacity_core::package_versions`).
pub(crate) fn emulate_package_versions(
    project: &std::path::Path,
    local: &vivacity_core::lock::Lock,
    manifest: &serde_json::Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> anyhow::Result<()> {
    use vivacity_core::package_versions as pv;
    let allowed = matches!(
        vivacity_core::layout::plugin_allowed(manifest, pv::PLUGIN_NAME),
        vivacity_core::layout::PluginVerdict::Allowed
    );
    if !plugins_enabled
        || !allowed
        || !local
            .wanted_packages(with_dev)
            .any(|p| p.name() == pv::PLUGIN_NAME)
    {
        return Ok(());
    }
    let root = vivacity_core::state::RootPackage::detect(manifest, project, with_dev);
    let replaces: Vec<(String, String)> = manifest
        .get("replace")
        .and_then(serde_json::Value::as_object)
        .map(|m| {
            m.iter()
                .filter_map(|(k, v)| v.as_str().map(|c| (k.to_lowercase(), c.to_owned())))
                .collect()
        })
        .unwrap_or_default();
    let versions = pv::versions(
        local,
        with_dev,
        &root.name,
        &root.pretty_version,
        root.reference.as_deref().unwrap_or(""),
        &replaces,
    );
    let vendor = vivacity_core::dirs::Dirs::resolve(manifest)
        .unwrap_or_default()
        .vendor_dir(project);
    // `writeVersionClassToFile` (Installer.php:200-231): its lines on
    // stdout around the write, or the one that says why it skipped.
    if !pv::versions_dir(&vendor).exists() {
        vivacity_core::out!("composer/package-versions-deprecated: Package not found (probably scheduled for removal); generation of version class skipped.");
        return Ok(());
    }
    vivacity_core::out!("composer/package-versions-deprecated: Generating version class...");
    pv::write(&vendor, &pv::render(&root.name, &versions))?;
    vivacity_core::out!("composer/package-versions-deprecated: ...done generating version class");
    Ok(())
}

/// `secure-http` true (or read from where vivacity does not) on a dist
/// Composer would download: Composer refuses the request (`CurlDownloader`
/// → `Config::prohibitUrlByConfig`), so the run is Composer's — decided on
/// the lock in memory, a string test per URL, before anything is printed or
/// written. Only an insecure URL costs more: then installed.json is read, and
/// a package it already holds at the locked version and reference (no
/// download in Composer either) does not count. The URL is the first one
/// `FileDownloader` tries (`Package::getDistUrls`: a preferred mirror first),
/// and the one vivacity downloads (vivacity does not read mirrors). A dist
/// Composer's files cache would serve still counts: Composer then succeeds on
/// its own.
pub(crate) fn insecure_dist_reason(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    lock: &vivacity_core::lock::Lock,
    with_dev: bool,
    plugins_enabled: bool,
) -> Option<String> {
    use serde_json::Value;
    use vivacity_core::secure_http::{classify, Verdict};
    let mut installed: Option<Vec<Value>> = None;
    for p in lock.wanted_packages(with_dev) {
        if p.is_metapackage() || p.dist_kind() == vivacity_core::lock::DistKind::Missing {
            continue;
        }
        let dist = p.raw.get("dist");
        // The common path: every URL `https`, a string test each.
        let any = dist
            .and_then(|d| d.get("url"))
            .and_then(Value::as_str)
            .into_iter()
            .chain(
                dist.and_then(|d| d.get("mirrors"))
                    .and_then(Value::as_array)
                    .into_iter()
                    .flatten()
                    .filter_map(|m| m.get("url").and_then(Value::as_str)),
            )
            .any(|u| vivacity_core::secure_http::insecure(u).is_some());
        if !any {
            continue;
        }
        let first_mirror = first_preferred_mirror(dist);
        let mut why = None;
        for url in first_mirror.into_iter().chain(p.dist_url_expanded()) {
            why = match classify(&url) {
                Verdict::Refuse => Some("which secure-http refuses".to_owned()),
                Verdict::HandOver(reason) => Some(format!("with {reason}")),
                Verdict::Allowed | Verdict::Warn { .. } => continue,
            };
            break;
        }
        let Some(why) = why else { continue };
        // Present as locked (`Transaction`'s identity), install path there:
        // no operation, no download.
        let present = installed.get_or_insert_with(|| {
            let composer_dir = composer_dir_of(project, manifest);
            present_packages(
                project,
                manifest,
                lock,
                with_dev,
                plugins_enabled,
                &composer_dir,
                plugin_order::installed_json_packages(&composer_dir),
            )
        });
        if installed_as_locked(present, p) {
            continue;
        }
        return Some(format!(
            "the dist of {} is downloaded over an insecure protocol, {why}",
            p.name()
        ));
    }
    None
}

/// The mirror `FileDownloader` tries first, if any: `Package::getUrls`
/// starts from the dist URL and, mirror by mirror, skips one already listed
/// (`in_array`), puts a preferred one at the head (`array_unshift`) and the
/// others at the end (Package.php:688-704). Compared as written (the
/// placeholders `ComposerMirror::processUrl` fills in are left).
fn first_preferred_mirror(dist: Option<&serde_json::Value>) -> Option<String> {
    use serde_json::Value;
    let main = dist.and_then(|d| d.get("url")).and_then(Value::as_str)?;
    let mut urls: std::collections::VecDeque<&str> = std::collections::VecDeque::from([main]);
    for m in dist
        .and_then(|d| d.get("mirrors"))
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let Some(url) = m.get("url").and_then(Value::as_str) else {
            continue;
        };
        if urls.contains(&url) {
            continue;
        }
        if m.get("preferred").is_some_and(crate::manifest::php_truthy) {
            urls.push_front(url);
        } else {
            urls.push_back(url);
        }
    }
    let first = *urls.front()?;
    (first != main).then(|| first.to_owned())
}

/// Whether any dist URL of a lock (as JSON) has an insecure scheme: the
/// string scan that keeps [`insecure_dist_reason`] off the common path.
pub(crate) fn any_insecure_dist(lock: &serde_json::Value) -> bool {
    use serde_json::Value;
    ["packages", "packages-dev"]
        .iter()
        .filter_map(|k| lock.get(*k).and_then(Value::as_array))
        .flatten()
        .filter_map(|p| p.get("dist"))
        .any(|d| {
            let main = d.get("url").and_then(Value::as_str);
            let mirrors = d
                .get("mirrors")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(|m| m.get("url").and_then(Value::as_str));
            main.into_iter()
                .chain(mirrors)
                .any(|u| vivacity_core::secure_http::insecure(u).is_some())
        })
}

/// `HttpDownloader::$maxJobs`: 12, or `COMPOSER_MAX_PARALLEL_HTTP` when
/// `is_numeric`, `(int)` and clamped to 1..=50 (HttpDownloader.php:52,
/// :91-93).
fn max_parallel_http() -> usize {
    let Ok(raw) = std::env::var("COMPOSER_MAX_PARALLEL_HTTP") else {
        return 12;
    };
    let trimmed = raw.trim_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']);
    let numeric = !trimmed.is_empty()
        && trimmed
            .chars()
            .all(|c| c.is_ascii_digit() || matches!(c, '.' | 'e' | 'E' | '+' | '-'))
        && trimmed.parse::<f64>().is_ok_and(f64::is_finite);
    if !numeric {
        return 12;
    }
    let n = trimmed.parse::<f64>().unwrap_or(12.0).trunc();
    n.clamp(1.0, 50.0) as usize
}

/// `  - <operation><appendix>` for every operation of a real install.
/// `FileDownloader::download`'s line, for the packages this install will fetch.
///
/// Composer writes it synchronously in `downloadAndExecuteBatch`'s registration
/// loop — `return $download()` runs its `writeError` before `addCopy`, and
/// `addJob` does not tick the curl loop — so the order is the transaction's,
/// not the completion order, and the lines form one block before the operation
/// lines. A package with no dist (a metapackage) or a `path` dist gets no
/// `FileDownloader` and no line. A dry run downloads nothing and prints none
/// (measured).
///
/// The decision is Composer's (`fetch::composer_downloads`): the line appears
/// when its files cache does not serve the archive — absent, a `dist.shasum`
/// its copy does not match, or no files cache this run (`files_cache`). The
/// same answer decides the request: the names come back with the lines, and
/// the installer downloads exactly those, store or not (point 55).
///
/// Offline (`--offline`, Composer's `COMPOSER_DISABLE_NETWORK`), the curl
/// jobs are refused in `startJob` before `initDownload` runs: no
/// `secure-http` warning (measured).
///
/// `secure-http` false: the request a line announces starts right after it
/// (`addCopy` → `startJob` → `CurlDownloader::initDownload`), which writes
/// « Warning: Accessing <host> over http… » once per host — for the first
/// `maxJobs` downloads only. Past them a job waits in the queue and starts in
/// `wait()`, after the last line, in queue order (measured: the 13th
/// download's new host is warned after the 14th line).
pub(crate) fn download_lines(
    lock: &vivacity_core::lock::Lock,
    arena: &[vivacity_resolver::package::Package],
    operations: &[vivacity_resolver::transaction::Operation],
    with_dev: bool,
    files_cache: vivacity_core::fetch::FilesCache,
    offline: bool,
) -> (Vec<String>, std::collections::BTreeSet<String>) {
    use vivacity_resolver::transaction::{DisplayRef, Operation};
    let by_name: std::collections::BTreeMap<&str, &vivacity_core::lock::LockPackage> = lock
        .wanted_packages(with_dev)
        .map(|p| (p.name(), p))
        .collect();
    let cache_root = vivacity_core::fetch::composer_cache_dir();
    let mut lines = Vec::new();
    let mut downloads = std::collections::BTreeSet::new();
    let enabled = files_cache == vivacity_core::fetch::FilesCache::Enabled;
    let max_jobs = max_parallel_http();
    let mut started = 0usize;
    let mut queued: Vec<(String, String)> = Vec::new();
    for op in operations {
        let target = match *op {
            Operation::Install(p) | Operation::Update(_, p) => p,
            _ => continue,
        };
        let package = &arena[target];
        let Some(locked) = by_name.get(package.name.as_str()) else {
            continue;
        };
        // `MetapackageInstaller::download` does nothing, whatever the
        // metapackage's lock entry says (an `artifact` repository gives
        // every package a zip dist).
        if locked.is_metapackage() {
            continue;
        }
        // `GitDownloader::doDownload`: a package without dist whose git
        // repository is remote is synced into the VCS cache, in the same
        // pass as the dists are downloaded (docs/plans/git-sources.md).
        if locked.dist_kind() == vivacity_core::lock::DistKind::Missing {
            // `MetapackageInstaller::download` does nothing.
            if let Some(source) = package
                .source
                .as_ref()
                .filter(|s| s.kind == "git" && package.package_type != "metapackage")
            {
                if !vivacity_core::git_source::is_local_path(&source.url) {
                    lines.push(vivacity_core::git_source::syncing_line(
                        &package.name,
                        &vivacity_resolver::transaction::full_pretty_version(
                            package,
                            true,
                            DisplayRef::SourceRefIfDev,
                        ),
                    ));
                }
            }
            continue;
        }
        let kind = match locked
            .raw
            .get("dist")
            .and_then(|d| d.get("type"))
            .and_then(serde_json::Value::as_str)
        {
            Some(kind) if kind != "path" => kind.to_owned(),
            _ => continue,
        };
        let Some(url) = locked.dist_url_expanded() else {
            continue;
        };
        let cached =
            vivacity_core::fetch::dist_cache_path_of(&cache_root, locked.name(), &url, &kind);
        if !vivacity_core::fetch::composer_downloads(&cached, locked.dist_shasum(), enabled) {
            continue;
        }
        downloads.insert(locked.name().to_owned());
        lines.push(format!(
            "  - Downloading {} ({})",
            package.name,
            vivacity_resolver::transaction::full_pretty_version(
                package,
                true,
                DisplayRef::SourceRefIfDev
            )
        ));
        // The request goes to the URL `FileDownloader` tries first: the last
        // preferred mirror, else the dist URL (vivacity downloads the latter,
        // the line is Composer's).
        let requested =
            first_preferred_mirror(locked.raw.get("dist")).unwrap_or_else(|| url.clone());
        if offline {
            continue;
        }
        if let vivacity_core::secure_http::Verdict::Warn { scheme, host } =
            vivacity_core::secure_http::classify(&requested)
        {
            if started < max_jobs {
                lines.extend(vivacity_core::secure_http::warn_once(&scheme, &host));
            } else {
                queued.push((scheme, host));
            }
        }
        // Only an `http(s)://` download takes a curl job; anything else goes
        // through `RemoteFilesystem`, synchronously (`canUseCurl`).
        let scheme = requested.split("://").next().unwrap_or("");
        if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") {
            started += 1;
        }
    }
    for (scheme, host) in queued {
        lines.extend(vivacity_core::secure_http::warn_once(&scheme, &host));
    }
    (lines, downloads)
}

pub(crate) fn operation_lines(
    project: &std::path::Path,
    arena: &[vivacity_resolver::package::Package],
    operations: &[vivacity_resolver::transaction::Operation],
    layout: &vivacity_core::layout::Layout,
    flex_packs: bool,
    plugins_enabled: bool,
    manifest: &serde_json::Value,
) -> anyhow::Result<Vec<String>> {
    use vivacity_resolver::transaction::Operation;
    let mut lines = Vec::new();
    // composer/installers 1.x registered by this transaction (not loaded
    // with the installed plugins): `PluginInstaller::install` compiles its
    // `Installer.php` right after its line — the PHP 8.4 deprecations.
    let installers_loaded = !plugins_enabled
        || crate::plugin_allow::load_for(project, manifest)
            .loaded
            .iter()
            .any(|n| n == "composer/installers")
        || vivacity_core::layout::plugin_allowed(manifest, "composer/installers")
            != vivacity_core::layout::PluginVerdict::Allowed;
    let mut deprecation_due = !installers_loaded;
    for op in operations {
        let Some(shown) = op.show(arena, false) else {
            continue;
        };
        let appendix = match *op {
            Operation::Install(p) | Operation::Update(_, p) => {
                let pkg = &arena[p];
                match pkg.dist.as_ref() {
                    Some(d) if d.kind == "path" => {
                        let install_path = layout
                            .abs(&pkg.name)
                            .unwrap_or_else(|| layout.vendor_dir().join(&pkg.name));
                        match vivacity_core::path_install::install_appendix(
                            project,
                            &install_path,
                            &d.url,
                            pkg.raw.get("transport-options"),
                        ) {
                            Ok(a) => a,
                            Err(vivacity_core::Error::Refused(msg)) => anyhow::bail!("{msg}"),
                            Err(e) => return Err(e.into()),
                        }
                    }
                    // `GitDownloader::doInstall`: `Cloning <ref>[ from cache]`.
                    None if pkg.package_type != "metapackage"
                        && pkg.source.as_ref().is_some_and(|s| s.kind == "git") =>
                    {
                        let source = pkg.source.as_ref();
                        let url = source.map(|s| s.url.as_str()).unwrap_or("");
                        let reference = source.and_then(|s| s.reference.as_deref()).unwrap_or("");
                        vivacity_core::git_source::install_appendix(
                            reference,
                            !vivacity_core::git_source::is_local_path(url),
                            vivacity_core::io::level() == vivacity_core::io::Verbosity::Verbose,
                        )
                    }
                    // `SymfonyPackInstaller extends MetapackageInstaller`:
                    // with Flex active a `symfony-pack` is laid out like a
                    // metapackage — nothing downloaded, nothing appended.
                    Some(_)
                        if pkg.package_type != "metapackage"
                            && !(flex_packs && pkg.package_type == "symfony-pack") =>
                    {
                        ": Extracting archive".to_owned()
                    }
                    _ => String::new(),
                }
            }
            Operation::Uninstall(p) => {
                let pkg = &arena[p];
                match pkg.dist.as_ref() {
                    Some(d) if d.kind == "path" => {
                        let install_path = layout
                            .abs(&pkg.name)
                            .unwrap_or_else(|| layout.vendor_dir().join(&pkg.name));
                        if vivacity_core::path_install::is_own_source(
                            project,
                            &install_path.to_string_lossy(),
                            &d.url,
                        ) {
                            format!(", source is still present in {}", install_path.display())
                        } else {
                            String::new()
                        }
                    }
                    _ => String::new(),
                }
            }
            _ => String::new(),
        };
        lines.push(format!("  - {shown}{appendix}"));
        if let Operation::Install(p) | Operation::Update(_, p) = *op {
            let pkg = &arena[p];
            if deprecation_due && pkg.name == "composer/installers" {
                let notes =
                    crate::plugin_allow::installers_deprecation(&layout.vendor_dir(), &pkg.version);
                deprecation_due = notes.is_empty();
                lines.extend(notes);
            }
        }
        // `PluginInstaller::install|update` registers the package right
        // after laying it out, and `PluginManager::registerPackage` says so
        // when plugins are off.
        if !plugins_enabled {
            if let Operation::Install(p) | Operation::Update(_, p) = *op {
                let pkg = &arena[p];
                if matches!(
                    pkg.package_type.as_str(),
                    "composer-plugin" | "composer-installer"
                ) {
                    lines.push(format!(
                        "The \"{}\" plugin was not loaded as plugins are disabled.",
                        pkg.name
                    ));
                }
            }
        }
    }
    Ok(lines)
}

/// Does vendor/ already hold this package exactly as the new lock names it?
/// Then the install lays nothing out for it, and what Flex reads at
/// `POST_UPDATE_CMD` is what is there now.
pub(crate) fn installed_as_locked(
    installed: &[serde_json::Value],
    p: &vivacity_core::lock::LockPackage,
) -> bool {
    let wanted = serde_json::Value::Object(p.raw.clone());
    installed.iter().any(|i| {
        i.get("name").and_then(serde_json::Value::as_str) == Some(p.name())
            && package_identity(i) == package_identity(&wanted)
    })
}

/// What `Transaction::calculateOperations` compares to decide that a present
/// package and a resolved one are the same thing, and so that there is no
/// operation: the version, both references, and the abandoned mark (an
/// `abandoned` that appears or changes is an update on its own).
/// `unchanged_local_repository` asks the same question of the whole set, and
/// the two must not drift apart — a package this calls unchanged while the
/// installer updates it loses Flex's `POST_PACKAGE_UPDATE`.
pub(crate) fn package_identity(
    p: &serde_json::Value,
) -> (
    Option<serde_json::Value>,
    Option<serde_json::Value>,
    Option<serde_json::Value>,
    Option<serde_json::Value>,
) {
    let field = |a: &str, b: &str| p.get(a).and_then(|v| v.get(b)).cloned();
    (
        p.get("version").cloned(),
        field("dist", "reference"),
        field("source", "reference"),
        p.get("abandoned").cloned(),
    )
}

/// The packages of vendor/composer/installed.json (list form of old
/// Composers accepted), minus those whose install path is gone
/// (`Factory::purgePackages` through `LibraryInstaller::isInstalled`; a
/// metapackage is always installed).
/// `LocalRepoTransaction` over installed.json and the lock, when the raw
/// entries prove it empty: same names, and for each the same version,
/// dist and source references, and `abandoned` state — what
/// `Transaction::new` compares. Returns the present names in
/// installed.json order (the local repository's order, which the emulated
/// plugins read). `None` when anything differs, or when either side could
/// carry an alias (a root alias in the lock, a `branch-alias` on a dev
/// version): aliases add operations of their own, and the full
/// computation handles them.
pub(crate) fn unchanged_local_repository(
    installed: &[serde_json::Value],
    lock: &serde_json::Value,
    with_dev: bool,
) -> Option<Vec<String>> {
    use serde_json::Value;
    if lock
        .get("aliases")
        .and_then(Value::as_array)
        .is_some_and(|a| !a.is_empty())
    {
        return None;
    }
    let wanted: Vec<&Value> = ["packages", "packages-dev"]
        .iter()
        .take(if with_dev { 2 } else { 1 })
        .filter_map(|k| lock.get(*k))
        .filter_map(Value::as_array)
        .flatten()
        .collect();
    if with_dev && lock.get("packages-dev").is_none() {
        return None; // the loader errors on this: let it
    }
    if wanted.len() != installed.len() {
        return None;
    }
    // `ArrayLoader::getBranchAlias` only looks at a dev version (and at
    // `default-branch`): a stable entry never grows an alias, whatever its
    // `extra`. Anything else declines, and the full computation decides.
    let aliased = |p: &Value| {
        let dev = p
            .get("version")
            .and_then(Value::as_str)
            .is_some_and(|v| v.starts_with("dev-") || v.ends_with("-dev"));
        (dev && p
            .get("extra")
            .and_then(|e| e.get("branch-alias"))
            .is_some_and(|b| !b.is_null()))
            || p.get("default-branch") == Some(&Value::Bool(true))
    };
    let key = |p: &Value| -> Option<String> {
        p.get("name")
            .and_then(Value::as_str)
            .map(str::to_ascii_lowercase)
    };
    let identity = package_identity;
    let mut by_name: std::collections::BTreeMap<String, &Value> = Default::default();
    for p in &wanted {
        if aliased(p) {
            return None;
        }
        by_name.insert(key(p)?, p);
    }
    let mut names = Vec::with_capacity(installed.len());
    for p in installed {
        if aliased(p) {
            return None;
        }
        let name = key(p)?;
        if identity(by_name.get(&name)?) != identity(p) {
            return None;
        }
        names.push(name);
    }
    (names.len() == by_name.len()).then_some(names)
}

pub(crate) fn installed_packages(
    project: &std::path::Path,
    manifest: &serde_json::Value,
) -> Vec<serde_json::Value> {
    let composer_dir = composer_dir_of(project, manifest);
    purge_missing(
        &composer_dir,
        plugin_order::installed_json_packages(&composer_dir),
    )
}

/// installed.json's packages as `Factory::purgePackages` leaves them: those
/// whose install path is gone are dropped (`purge_missing`) — the path the
/// installer of this run computes (`LibraryInstaller::isInstalled`), and a
/// `symfony-pack` without Flex is looked for in the vendor directory. The
/// one decision both the local-repository transaction and `secure-http`'s
/// "already installed, nothing downloaded" ([`insecure_dist_reason`]) read.
pub(crate) fn present_packages(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    lock: &vivacity_core::lock::Lock,
    with_dev: bool,
    plugins_enabled: bool,
    composer_dir: &std::path::Path,
    installed_raw: Vec<serde_json::Value>,
) -> Vec<serde_json::Value> {
    let mut installed_now = purge_missing(composer_dir, installed_raw);
    // `LibraryInstaller::isInstalled` looks at the path the installer of
    // this run computes: a package an installer plugin laid out elsewhere,
    // under `--no-plugins` (or with that plugin no longer active), is looked
    // for at `<vendor-dir>/<name>` — absent, it is installed again there.
    if let Ok(layout) =
        vivacity_core::layout::Layout::resolve(project, lock, manifest, with_dev, plugins_enabled)
    {
        installed_now.retain(|p| {
            let name = p
                .get("name")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            if p.get("type").and_then(serde_json::Value::as_str) == Some("metapackage")
                || layout.install_path(name).is_none()
            {
                return true;
            }
            layout.abs(name).is_none_or(|d| d.exists())
        });
    }
    // A `symfony-pack` laid out by Flex's pack installer has no install
    // path in installed.json (`MetapackageInstaller`), which the purge above
    // reads as "always installed". `Factory::createComposer` loads the
    // installed plugins (`loadInstalledPlugins`) before `purgePackages`:
    // without Flex among them (`--no-plugins`, Flex not installed or not
    // allowed), the pack's installer is `LibraryInstaller`, whose
    // `isInstalled` asks for `<vendor-dir>/<name>` (`Filesystem::isReadable`:
    // a file would do, a dangling link would not) — absent, the pack is not
    // installed and the run installs it.
    if !vivacity_core::scope::active_plugins(project, manifest, plugins_enabled)
        .iter()
        .any(|p| p == "symfony/flex")
    {
        let vendor = vivacity_core::dirs::Dirs::resolve(manifest)
            .unwrap_or_default()
            .vendor_dir(project);
        installed_now.retain(|p| {
            let pack = p.get("type").and_then(serde_json::Value::as_str) == Some("symfony-pack");
            let no_path = p.get("install-path").is_none_or(serde_json::Value::is_null);
            let name = p
                .get("name")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            !(pack && no_path && !vendor.join(name).exists())
        });
    }
    installed_now
}

/// `Factory::purgePackages`: the packages whose install path is gone leave
/// the local repository (a metapackage, or an entry without a path, stays).
pub(crate) fn purge_missing(
    composer_dir: &std::path::Path,
    list: Vec<serde_json::Value>,
) -> Vec<serde_json::Value> {
    list.into_iter()
        .filter(|p| {
            if p.get("type").and_then(|t| t.as_str()) == Some("metapackage") {
                return true;
            }
            match p.get("install-path").and_then(|v| v.as_str()) {
                Some(rel) => composer_dir.join(rel).exists(),
                None => true,
            }
        })
        .collect()
}

/// `Installer::run`: the funding count of the local repository's packages
/// (never an alias), unless `COMPOSER_FUND` is a number whose `intval` is 0
/// ([`funding_shown`]). Printed
/// in every mode, dry run included (`$localRepo` is then the mocked
/// repository of the same packages).
pub(crate) fn print_funding(project: &std::path::Path, manifest: &serde_json::Value) {
    if !funding_shown(std::env::var("COMPOSER_FUND").ok().as_deref()) {
        return;
    }
    let funding = installed_packages(project, manifest)
        .iter()
        .filter(|p| {
            p.get("funding")
                .and_then(serde_json::Value::as_array)
                .is_some_and(|f| !f.is_empty())
        })
        .count();
    if funding > 0 {
        vivacity_core::say!(
            "{funding} package{} you are using {} looking for funding.\nUse the `composer fund` command to find out more!",
            if funding == 1 { "" } else { "s" },
            if funding == 1 { "is" } else { "are" }
        );
    }
}

/// `is_numeric($fundEnv)` then `intval($fundEnv) !== 0`: a numeric
/// `COMPOSER_FUND` that truncates to 0 (`0`, `0.5`, `-0.9`) hides the line,
/// and so does one that overflows to infinity (`intval(INF)` is 0). `inf`
/// and `nan` are not numeric to PHP, whatever Rust parses.
fn funding_shown(env: Option<&str>) -> bool {
    let Some(t) = env.map(str::trim) else {
        return true;
    };
    let lower = t.to_ascii_lowercase();
    if lower.contains("inf") || lower.contains("nan") {
        return true;
    }
    match t.parse::<f64>() {
        Ok(n) => n.is_finite() && n.trunc() != 0.0,
        Err(_) => true,
    }
}

/// `Installer::run`: one warning per abandoned package of the lock (dev
/// included), in lock order.
pub(crate) fn abandoned_warnings(lock: &serde_json::Value) -> Vec<String> {
    let mut out = Vec::new();
    for section in ["packages", "packages-dev"] {
        for p in lock
            .get(section)
            .and_then(serde_json::Value::as_array)
            .into_iter()
            .flatten()
        {
            // `CompletePackage::isAbandoned` = `(bool) $abandoned`,
            // `getReplacementPackage` = the string, else null.
            let abandoned = match p.get("abandoned") {
                None | Some(serde_json::Value::Null) | Some(serde_json::Value::Bool(false)) => {
                    continue
                }
                Some(serde_json::Value::String(s)) if s.is_empty() || s == "0" => continue,
                Some(serde_json::Value::Number(n)) if n.as_f64() == Some(0.0) => continue,
                Some(serde_json::Value::Array(a)) if a.is_empty() => continue,
                Some(serde_json::Value::Object(o)) if o.is_empty() => continue,
                Some(serde_json::Value::String(replacement)) => Some(replacement.clone()),
                Some(_) => None,
            };
            let replacement = match abandoned {
                Some(r) => format!("Use {r} instead"),
                None => "No replacement was suggested".to_owned(),
            };
            out.push(format!(
                "Package {} is abandoned, you should avoid using it. {replacement}.",
                p.get("name")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("")
            ));
        }
    }
    out
}

#[cfg(test)]
mod funding_tests {
    use super::funding_shown;

    #[test]
    fn funding_hidden_by_a_numeric_fund_that_truncates_to_zero() {
        assert!(funding_shown(None));
        assert!(funding_shown(Some("")));
        assert!(funding_shown(Some("no")));
        assert!(funding_shown(Some("1")));
        assert!(funding_shown(Some(" 2.5 ")));
        assert!(!funding_shown(Some("0")));
        assert!(!funding_shown(Some("0.5")));
        assert!(!funding_shown(Some("-0.9")));
        assert!(!funding_shown(Some("1e400")));
        assert!(funding_shown(Some("inf")));
        assert!(funding_shown(Some("NaN")));
    }
}

#[cfg(test)]
mod local_repository_tests {
    use super::unchanged_local_repository;
    use serde_json::{json, Value};

    fn pkg(name: &str, version: &str) -> Value {
        json!({"name": name, "version": version, "dist": {"reference": "abc"}})
    }

    fn lock(packages: Vec<Value>, dev: Vec<Value>) -> Value {
        json!({"packages": packages, "packages-dev": dev, "aliases": []})
    }

    #[test]
    fn accepts_only_a_truly_unchanged_repository() {
        let installed = vec![pkg("a/b", "1.0.0"), pkg("c/d", "2.0.0")];
        let l = lock(vec![pkg("a/b", "1.0.0")], vec![pkg("c/d", "2.0.0")]);
        assert_eq!(
            unchanged_local_repository(&installed, &l, true),
            Some(vec!["a/b".to_owned(), "c/d".to_owned()]),
            "same packages, same versions and references"
        );
        // --no-dev over a dev vendor: the dev package must be uninstalled.
        assert!(unchanged_local_repository(&installed, &l, false).is_none());
    }

    #[test]
    fn declines_every_difference_the_transaction_would_see() {
        let installed = vec![pkg("a/b", "1.0.0")];
        let same = || vec![pkg("a/b", "1.0.0")];
        let decline = |packages: Vec<Value>, why: &str| {
            assert!(
                unchanged_local_repository(&installed, &lock(packages, vec![]), true).is_none(),
                "{why}"
            );
        };
        decline(vec![pkg("a/b", "1.1.0")], "a new version is an update");
        decline(
            vec![json!({"name": "a/b", "version": "1.0.0", "dist": {"reference": "zzz"}})],
            "a new dist reference is an update",
        );
        decline(
            vec![
                json!({"name": "a/b", "version": "1.0.0", "dist": {"reference": "abc"}, "source": {"reference": "s"}}),
            ],
            "a new source reference is an update",
        );
        decline(
            vec![
                json!({"name": "a/b", "version": "1.0.0", "dist": {"reference": "abc"}, "abandoned": true}),
            ],
            "becoming abandoned is an update",
        );
        decline(
            vec![pkg("e/f", "1.0.0")],
            "another package is install + uninstall",
        );
        decline(vec![], "an empty lock uninstalls");
        decline(
            vec![pkg("a/b", "1.0.0"), pkg("e/f", "1.0.0")],
            "one more package is an install",
        );
        // Aliases add operations of their own: never the fast path.
        let mut aliased = lock(same(), vec![]);
        aliased["aliases"] =
            json!([{"package": "a/b", "alias": "1.0", "alias_normalized": "1.0.0.0"}]);
        assert!(unchanged_local_repository(&installed, &aliased, true).is_none());
        let dev_alias = json!({"name": "a/b", "version": "dev-main", "dist": {"reference": "abc"},
                               "extra": {"branch-alias": {"dev-main": "1.x-dev"}}});
        assert!(
            unchanged_local_repository(
                std::slice::from_ref(&dev_alias),
                &lock(vec![dev_alias.clone()], vec![]),
                true
            )
            .is_none(),
            "a dev version with a branch-alias grows an alias package"
        );
        // A stable version keeps its `extra` and grows nothing.
        let stable_extra = json!({"name": "a/b", "version": "1.0.0", "dist": {"reference": "abc"},
                                  "extra": {"branch-alias": {"dev-main": "1.x-dev"}}});
        assert!(unchanged_local_repository(
            std::slice::from_ref(&stable_extra),
            &lock(vec![stable_extra.clone()], vec![]),
            true
        )
        .is_some());
        // A lock without `packages-dev` is the loader's error, not ours.
        assert!(
            unchanged_local_repository(&installed, &json!({"packages": same()}), true).is_none()
        );
    }
}