vivacity 0.26.0

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
//! `update`: resolve, write the lock, install — `UpdateCommand` and the
//! resolution half of `Installer::run`; `require` and `remove` go through
//! it too.

use super::*;

/// Network transport for remote composer repositories: the vivacity-core
/// Fetcher (Composer auth, retries), made synchronous, with a parallel
/// batch (Composer: curl multi, 12 downloads at a time).
pub(crate) fn http_transport(
    project: &std::path::Path,
    offline: bool,
) -> anyhow::Result<vivacity_resolver::repository::HttpTransports> {
    let runtime =
        Arc::new(tokio::runtime::Runtime::new().context("cannot start the async runtime")?);
    let fetcher = Arc::new(vivacity_core::fetch::Fetcher::new(
        vivacity_core::fetch::composer_cache_dir(),
        vivacity_core::fetch::Auth::load(project),
    )?);
    fn to_fetched(
        r: vivacity_core::fetch::MetadataResponse,
    ) -> vivacity_resolver::repository::Fetched {
        use vivacity_core::fetch::MetadataResponse as M;
        use vivacity_resolver::repository::Fetched as F;
        match r {
            M::NotModified => F::NotModified,
            M::NotFound => F::NotFound,
            M::Body {
                bytes,
                last_modified,
            } => F::Body {
                bytes,
                last_modified,
            },
        }
    }
    let http: vivacity_resolver::repository::HttpFetch = {
        let runtime = runtime.clone();
        let fetcher = fetcher.clone();
        Arc::new(move |url: &str, ims: Option<&str>| {
            if offline {
                return network_disabled(url, ims);
            }
            let r = runtime
                .block_on(fetcher.metadata_fetch(url, ims))
                .map(to_fetched)
                .map_err(|e| e.to_string());
            say_redirect_warnings();
            r
        })
    };
    // Parallel batch (Composer: curl multi, 12 downloads at a time).
    let http_many: vivacity_resolver::repository::HttpFetchMany = {
        let runtime = runtime.clone();
        let fetcher = fetcher.clone();
        Arc::new(move |requests: &[vivacity_resolver::repository::Request]| {
            if offline {
                return requests
                    .iter()
                    .map(|(u, ims)| network_disabled(u, ims.as_deref()))
                    .collect();
            }
            let requests: Vec<(String, Option<String>)> = requests.to_vec();
            runtime.block_on(async {
                let sem = Arc::new(tokio::sync::Semaphore::new(12));
                let tasks: Vec<_> = requests
                    .into_iter()
                    .map(|(u, ims)| {
                        let sem = sem.clone();
                        let fetcher = fetcher.clone();
                        async move {
                            let _permit = sem.acquire().await;
                            fetcher
                                .metadata_fetch(&u, ims.as_deref())
                                .await
                                .map(to_fetched)
                                .map_err(|e| e.to_string())
                        }
                    })
                    .collect();
                let r = futures_join_all(tasks).await;
                say_redirect_warnings();
                r
            })
        })
    };
    // Form POST (security advisories API).
    let http_post: vivacity_resolver::repository::HttpPost = {
        let runtime = runtime.clone();
        let fetcher = fetcher.clone();
        Arc::new(move |url: &str, body: &str| {
            if offline {
                return network_disabled(url, None);
            }
            let r = runtime
                .block_on(fetcher.post_form(url, body))
                .map(to_fetched)
                .map_err(|e| e.to_string());
            say_redirect_warnings();
            r
        })
    };
    Ok((http, Some(http_many), Some(http_post)))
}

/// The `secure-http` warnings of the redirects a metadata request followed
/// to an insecure host, written as the request completes (Composer: as
/// `CurlDownloader` restarts the job).
fn say_redirect_warnings() {
    for line in vivacity_core::secure_http::take_redirect_warnings() {
        vivacity_core::say!("{line}");
    }
}

/// `--offline` answers metadata requests as Composer's `HttpDownloader`
/// does under `COMPOSER_DISABLE_NETWORK` (HttpDownloader.php:328-338), the
/// variable the fallback hands `--offline` over as: a conditional request
/// (`If-Modified-Since`, a cached file with its `last-modified`) gets a 304,
/// so the cache serves without a word; any other fails as a transport
/// error, `Network disabled, request canceled: <url>` (`Url::sanitize`d).
fn network_disabled(
    url: &str,
    if_modified_since: Option<&str>,
) -> Result<vivacity_resolver::repository::Fetched, String> {
    if if_modified_since.is_some() {
        return Ok(vivacity_resolver::repository::Fetched::NotModified);
    }
    Err(format!(
        "{}{}",
        vivacity_resolver::repository::NETWORK_DISABLED,
        vivacity_resolver::metacache::sanitize_url(url)
    ))
}

/// `{\S+[ =:]\S+}`: a `packages` entry that carries a constraint. The
/// name alone is what the allow list takes (`{^([^ =:]+)[ =:].*$}`).
pub(crate) fn package_of_requirement(entry: &str) -> &str {
    match entry.find([' ', '=', ':']) {
        Some(i)
            if entry[i + 1..]
                .trim_start_matches([' ', '=', ':'])
                .is_empty() =>
        {
            entry
        }
        Some(i) => &entry[..i],
        None => entry,
    }
}

/// `UpdateCommand`: `formatRequirements(--with)` plus the `packages`
/// entries that carry a constraint — `a/b:^1`, `a/b=^1`, `a/b ^1`
/// (`VersionParser::parseNameVersionPairs`). A pair without a version is
/// the command's own error.
pub(crate) fn temporary_requirements(
    with: &[String],
    packages: &[String],
) -> anyhow::Result<Vec<(String, String)>> {
    let mut out: Vec<(String, String)> = Vec::new();
    let carrying: Vec<String> = packages
        .iter()
        .filter(|p| package_of_requirement(p) != p.as_str())
        .cloned()
        .collect();
    for source in [with, &carrying] {
        for (name, version) in vivacity_resolver::version::parse_name_version_pairs(source) {
            let Some(version) = version else {
                anyhow::bail!(
                    "Option {name} is missing a version constraint, use e.g. {name}:^1.0"
                );
            };
            // `$requires[$name] = $version`: the last one wins.
            match out.iter_mut().find(|(n, _)| *n == name) {
                Some(slot) => slot.1 = version,
                None => out.push((name, version)),
            }
        }
    }
    Ok(out)
}

/// `composer update`: resolution (exact port of Composer's solver), lock
/// written if its data changes, then `install`.
pub(crate) fn run_update(args: &UpdateArgs) -> anyhow::Result<i32> {
    refuse_alternate_manifest()?;
    // `BaseCommand::initialize`: the root-version warning before anything
    // `UpdateCommand` prints, then the platform options' environment —
    // before `execute` finds no composer.json.
    hold_root_version_warning(&project_dir(args.working_dir.as_deref())?);
    hold_ignored_lock_warning(&project_dir(args.working_dir.as_deref())?);
    platform_requirement_env(args.ignore_platform_reqs, &args.ignore_platform_req, true);
    if let Some(code) = refuse_missing_manifest(&project_dir(args.working_dir.as_deref())?) {
        return Ok(code);
    }
    // Partial update: `update a/b [-w|-W]` (UpdateCommand).
    let env_flag = |name: &str| std::env::var(name).is_ok_and(|v| !v.is_empty() && v != "0");
    // `update lock|nothing|mirrors`: the lock's metadata refreshed, not
    // reproduced — Composer's, before anything.
    if let Some(p) = args
        .packages
        .iter()
        .find(|p| ["lock", "nothing", "mirrors"].contains(&p.as_str()))
    {
        return delegate_resolution(
            &[vivacity_core::scope::ScopeIssue::Layout(format!(
                "`update {p}` (refreshes the lock's metadata, not reproduced)"
            ))],
            args.no_fallback,
        );
    }
    let transitive = if args.with_all_dependencies || env_flag("COMPOSER_WITH_ALL_DEPENDENCIES") {
        vivacity_resolver::pool::UpdateMode::ListedWithTransitiveDeps
    } else if args.with_dependencies || env_flag("COMPOSER_WITH_DEPENDENCIES") {
        vivacity_resolver::pool::UpdateMode::ListedWithTransitiveDepsNoRootRequire
    } else {
        vivacity_resolver::pool::UpdateMode::OnlyListed
    };
    // `UpdateCommand`: `--with a/b:^1` and the `update a/b:^1` shorthand
    // are temporary constraints; the shorthand's package keeps its name in
    // the allow list.
    let reqs = temporary_requirements(&args.with, &args.packages)?;
    let allow_list: Vec<String> = args
        .packages
        .iter()
        .map(|p| package_of_requirement(p).to_owned())
        .collect();
    let mut options = if allow_list.is_empty() {
        vivacity_resolver::session::UpdateOptions::default()
    } else {
        vivacity_resolver::session::UpdateOptions::partial(&allow_list, transitive)
    };
    options.no_blocking = args.no_blocking || args.no_security_blocking;
    options.temporary_requirements = reqs;
    // BaseCommand: COMPOSER_PREFER_STABLE / COMPOSER_PREFER_LOWEST count as
    // the options.
    let prefer_stable = args.prefer_stable || env_flag("COMPOSER_PREFER_STABLE");
    let prefer_lowest = args.prefer_lowest || env_flag("COMPOSER_PREFER_LOWEST");
    {
        let project = project_dir(args.working_dir.as_deref())?;
        if let Ok(manifest) = std::fs::read_to_string(project.join("composer.json"))
            .map_err(anyhow::Error::from)
            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).map_err(Into::into))
        {
            // The root package, then the installed plugins
            // (`Factory::createComposer`), before anything resolves.
            if let Some(code) = refuse_invalid_root(&manifest) {
                return Ok(code);
            }
            if let Some(code) = crate::plugin_allow::at_load(
                &project,
                &manifest,
                None,
                !args.no_plugins,
                args.no_fallback,
            )? {
                return Ok(code);
            }
            if let Some(code) = resolution_fallback(
                &project,
                &manifest,
                vivacity_core::scope::ResolutionCommand::Update,
                args.no_plugins,
                args.no_fallback,
                !args.no_install && !args.dry_run,
                !args.dry_run,
                !(args.no_dev || env_no_dev()),
                &PoolStart {
                    allow: allow_list.clone(),
                    mode: Some(transitive),
                    ..PoolStart::default()
                },
            )? {
                return Ok(code);
            }
        }
    }
    // `update` edits nothing before resolving: nothing to undo.
    run_update_resolved(args, options, prefer_stable, prefer_lowest, &|| Ok(()))
        .map(|ended| ended.status)
}

/// A session error the command prints itself: each part at its Composer
/// level when the session split it, else the whole message at the default
/// level (`UpdateCommand`'s temporary-constraint refusal).
fn print_session_error(e: &vivacity_resolver::session::SessionError) {
    if e.parts.is_empty() {
        vivacity_core::say!("{}", e.message);
    }
    for (level, text) in &e.parts {
        vivacity_core::say_at!(*level, "{text}");
    }
    if let Some(annotation) = &e.annotation {
        vivacity_core::io::github_action_error(annotation);
    }
}

/// How [`run_update_resolved`] ended: the exit code, and whether the whole
/// command went to Composer after the resolution — the caller (`remove`)
/// then adds nothing of its own: no revert, no local-repository check.
pub(crate) struct Ended {
    pub(crate) status: i32,
    pub(crate) by_composer: bool,
}

/// Resolution, lock write and install, once the list and the update mode
/// are decided (shared by `update` and `remove`). `undo_edit` restores the
/// caller's composer.json before a hand-over ([`hand_resolution_over`]).
pub(crate) fn run_update_resolved(
    args: &UpdateArgs,
    options: vivacity_resolver::session::UpdateOptions,
    prefer_stable: bool,
    prefer_lowest: bool,
    undo_edit: &dyn Fn() -> anyhow::Result<()>,
) -> anyhow::Result<Ended> {
    let resolved = resolve_and_lock(args, options, prefer_stable, prefer_lowest)?;
    if let Some(issue) = &resolved.hand_over {
        return Ok(Ended {
            status: hand_resolution_over(issue, args.no_fallback, undo_edit)?,
            by_composer: true,
        });
    }
    let ended = |status| Ended {
        status,
        by_composer: false,
    };
    if resolved.status != 0 {
        return Ok(ended(resolved.status));
    }
    if !args.no_install {
        let (virtual_lock, virtual_manifest) = if args.dry_run {
            (resolved.lock.clone(), Some(resolved.manifest.clone()))
        } else if resolved.virtual_lock {
            (resolved.lock.clone(), None)
        } else {
            (None, None)
        };
        // The install phase prints the end of `Installer::run` itself, at
        // Composer's points — or Composer does, when it was handed over.
        let status = install_after_update(args, resolved.report(), virtual_lock, virtual_manifest)?;
        return Ok(ended(status));
    }
    print_post_update(&resolved, &project_dir(args.working_dir.as_deref())?, args)?;
    Ok(ended(0))
}

/// The install that follows the lock write (`Installer::run` with
/// `setInstall(true)`): its status. It prints the end of `Installer::run`
/// (`report`) at Composer's points — unless it goes to Composer, whose
/// `install` then prints its own end (the abandoned packages, the funding
/// count; the suggestions, which only an update prints, are what is
/// missing).
pub(crate) fn install_after_update(
    args: &UpdateArgs,
    report: UpdateReport,
    virtual_lock: Option<serde_json::Value>,
    virtual_manifest: Option<serde_json::Value>,
) -> anyhow::Result<i32> {
    let install = InstallArgs {
        compat: GlobalCompatArgs::default(),
        prefer_source: args.prefer_source,
        prefer_dist: args.prefer_dist,
        prefer_install: args.prefer_install.clone(),
        no_progress: args.no_progress,
        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,
        run_scripts: false,
        no_plugins: args.no_plugins,
        ignore_platform_reqs: args.ignore_platform_reqs,
        ignore_platform_req: args.ignore_platform_req.clone(),
        no_fallback: args.no_fallback,
        check_scope: false,
        offline: args.offline,
        no_blocking: args.no_blocking,
        no_security_blocking: args.no_security_blocking,
        no_install: false,
        dry_run: args.dry_run,
        working_dir: args.working_dir.clone(),
        fallback_line: Some(after_update_line(args)),
        virtual_lock,
        virtual_manifest,
        post_update: Some(Box::new(UpdateReport {
            allow_plugins_at_load: args.allow_plugins_at_load.clone(),
            ..report
        })),
    };
    run_install(&install)
}

/// Resolution and lock write: 0, or 2 on an unsolvable set.
/// The outcome of the resolution: the status (0, or 2 on an unsolvable
/// set) and the lock data, written or not (`config.lock: false` resolves
/// without writing; Composer then keeps a "virtual" lock).
pub(crate) struct Resolved {
    pub(crate) status: i32,
    /// The lock was not written (`config.lock: false`): the install phase
    /// installs it from memory (`Locker::setLockData(..., false)` keeps it,
    /// `doInstall` reads it), never from the composer.lock on disk.
    pub(crate) virtual_lock: bool,
    pub(crate) lock: Option<serde_json::Value>,
    /// What `Installer::run` prints after `doUpdate` and before the dump
    /// (suggestions, abandoned packages), ready to print; the funding count
    /// is read from installed.json after the dump, by the install phase or
    /// by [`print_post_update`].
    pub(crate) post: Vec<String>,
    /// The manifest as the (possibly patched) root package sees it.
    pub(crate) manifest: serde_json::Value,
    /// symfony/flex was active for this resolution: its `POST_UPDATE_CMD`
    /// output follows the funding count ([`UpdateReport`]).
    pub(crate) flex_active: bool,
    /// The install would perform at least one update operation, which arms
    /// Flex's `symfony/thanks` reminder (`enableThanksReminder` on
    /// `POST_PACKAGE_UPDATE`); computed before the install, since it needs
    /// the state the install replaces.
    pub(crate) thanks_reminder: bool,
    /// The recipes Flex applies at `POST_UPDATE_CMD`, reproduced
    /// (`flex_recipes`): printed and written by the install phase.
    pub(crate) flex_plan: Option<std::sync::Arc<crate::flex_recipes::FlexPlan>>,
    /// The solved lock shows a Flex behaviour vivacity does not emulate:
    /// nothing is written, and the whole command goes to Composer — run by
    /// the caller ([`hand_resolution_over`]), which first undoes its own
    /// edit of composer.json (`require`/`remove`): Composer must start from
    /// the manifest the user had, or `remove` finds its package gone.
    pub(crate) hand_over: Option<vivacity_core::scope::ScopeIssue>,
}

/// What `Installer::run` prints around an update's install phase, handed
/// to that phase ([`install_after_update`]): the suggestions and the
/// abandoned packages before the dump (`Installer.php:343-373`), Flex's
/// `POST_UPDATE_CMD` output after the funding (l. 412-442).
#[derive(Debug)]
pub(crate) struct UpdateReport {
    pub(crate) lines: Vec<String>,
    /// The manifest Flex reads (the patched root package).
    pub(crate) manifest: serde_json::Value,
    pub(crate) flex_active: bool,
    pub(crate) thanks_reminder: bool,
    pub(crate) flex_plan: Option<std::sync::Arc<crate::flex_recipes::FlexPlan>>,
    /// `UpdateArgs::allow_plugins_at_load`: the rules the run's plugins were
    /// loaded with, when the manifest the install phase reads has lost some.
    pub(crate) allow_plugins_at_load: Option<serde_json::Value>,
}

impl Resolved {
    pub(crate) fn report(&self) -> UpdateReport {
        UpdateReport {
            lines: self.post.clone(),
            manifest: self.manifest.clone(),
            flex_active: self.flex_active,
            thanks_reminder: self.thanks_reminder,
            flex_plan: self.flex_plan.clone(),
            allow_plugins_at_load: None,
        }
    }

    /// The command stops with `status` before anything is written.
    fn stopped(status: i32) -> Resolved {
        Resolved {
            status,
            virtual_lock: false,
            lock: None,
            post: Vec::new(),
            manifest: serde_json::Value::Null,
            flex_active: false,
            thanks_reminder: false,
            flex_plan: None,
            hand_over: None,
        }
    }
}

/// The resolution handed to Composer once solved ([`Resolved::hand_over`]):
/// `undo_edit` restores composer.json as it was, silently — Composer prints
/// its own `has been updated` and reverts on its own failure — then
/// [`delegate_resolution`] (exit 3 under `--no-fallback`, the edit undone
/// all the same). The command adds nothing after it: no revert, no report.
pub(crate) fn hand_resolution_over(
    issue: &vivacity_core::scope::ScopeIssue,
    no_fallback: bool,
    undo_edit: &dyn Fn() -> anyhow::Result<()>,
) -> anyhow::Result<i32> {
    undo_edit()?;
    delegate_resolution(std::slice::from_ref(issue), no_fallback)
}

/// Prints the post-update report of `Installer::run` when the update has
/// no install phase (`--no-install`): the precomputed lines, the funding
/// count, then `POST_UPDATE_CMD` (Installer.php:438-441) — dispatched
/// without an install too, not under `--dry-run`, which dispatches no
/// script event (Installer.php:292-294): the loaded plugins' listeners in
/// their activation order, each one's -v line right before what its
/// emulation does, Flex's output at its rank (`no_install`,
/// docs/plans/no-install-listeners.md, docs/plans/verbose-plugins.md).
/// With an install phase, that phase prints it (`run_install`).
pub(crate) fn print_post_update(
    resolved: &Resolved,
    project: &std::path::Path,
    args: &UpdateArgs,
) -> anyhow::Result<()> {
    let manifest = listeners_manifest(&resolved.manifest, args.allow_plugins_at_load.as_ref());
    for line in &resolved.post {
        vivacity_core::say!("{line}");
    }
    print_funding(project, &resolved.manifest);
    if args.dry_run {
        return Ok(());
    }
    let flex = || print_flex_post_update(&resolved.manifest, resolved.thanks_reminder, None);
    crate::no_install::post_update_listeners(
        project,
        &manifest,
        !args.no_plugins,
        resolved
            .flex_active
            .then_some(&flex as &dyn Fn() -> anyhow::Result<()>),
    )
}

/// The root package the plugins' listeners see: `remove` takes the removed
/// plugins out of `allow-plugins` after its `Composer` loaded them
/// (RemoveCommand.php:221-222, then :242-252), and the `PluginManager`
/// keeps the rules it read — as they were, order included.
pub(crate) fn listeners_manifest(
    manifest: &serde_json::Value,
    allow_plugins_at_load: Option<&serde_json::Value>,
) -> serde_json::Value {
    let mut manifest = manifest.clone();
    if let (Some(allow), Some(root)) = (allow_plugins_at_load, 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.clone());
        }
    }
    manifest
}

pub(crate) fn resolve_and_lock(
    args: &UpdateArgs,
    options: vivacity_resolver::session::UpdateOptions,
    prefer_stable: bool,
    prefer_lowest: bool,
) -> anyhow::Result<Resolved> {
    use vivacity_resolver::platform_filter::PlatformRequirementFilter;
    use vivacity_resolver::session::UpdateSession;
    let t0 = std::time::Instant::now();
    let project = project_dir(args.working_dir.as_deref())?;
    refuse_alternate_manifest()?;
    let manifest_path = project.join("composer.json");
    // `require`/`remove`'s edit, held back while the run holds its output
    // (`io::write_held`), is the manifest.
    let manifest_text = vivacity_core::io::read_held(&manifest_path)
        .with_context(|| format!("cannot read {}", manifest_path.display()))?;
    let installer_dev_mode = !(args.no_dev || env_no_dev());
    let mut options = options;
    // `config.lock: false`: the update runs without the lock's packages.
    options.ignore_lock |= !config_lock_enabled(&manifest_text);
    if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
        // `RootPackage::load` refuses these too, but through the error path,
        // which prefixes the message; here it is worded as Composer words it.
        if let Some(code) = refuse_invalid_root(&m) {
            return Ok(Resolved::stopped(code));
        }
        refuse_merge_plugin_resolution(&project, &m, !args.no_plugins)?;
        // composer-merge-plugin installed and allowed: the root Composer
        // resolves is the merged one (INIT, then `PRE_UPDATE_CMD` with the
        // installer's dev mode for the `require-dev` sections). A merged
        // `repositories` section was handed to Composer before getting
        // here (`resolution_fallback`).
        let active = vivacity_core::scope::active_plugins(&project, &m, !args.no_plugins)
            .iter()
            .any(|p| p == vivacity_resolver::merge_plugin::PLUGIN_NAME);
        options.merged = merge_root_when(&project, &m, installer_dev_mode, active)
            .map_err(|e| anyhow::anyhow!("{e}"))?;
        if let Some(merged) = &options.merged {
            if !merged.repositories.is_empty() {
                anyhow::bail!(
                    "wikimedia/composer-merge-plugin: {} declares repositories (not emulated at resolution)",
                    merged.repositories.join(", ")
                );
            }
        }
    }
    // The manifest the run's plugins were loaded with (`remove`: the
    // `allow-plugins` rules as read before its edit).
    let loaded_manifest = serde_json::from_str::<serde_json::Value>(&manifest_text)
        .ok()
        .map(|m| listeners_manifest(&m, args.allow_plugins_at_load.as_ref()));
    // `secure-http` under its trigger (a remote repository other than
    // packagist.org): everything the command writes from here — the
    // `COMMAND` event's lines, the install-without-lock line, « Loading… »
    // and what loading writes — is held until the pool, so that a hand-over
    // decided then prints nothing (`require` and `remove` started holding
    // before their edit already).
    let hold = loaded_manifest
        .as_ref()
        .is_some_and(crate::fallback::hold_trigger);
    if hold {
        crate::fallback::start_holding("the pool is built");
    }
    // Without an install, php-http/discovery's `POST_UPDATE_CMD` listener
    // reads the old installed state (`no_install::discovery_issue`):
    // decided on the manifest this command resolves (`require`'s edit
    // included), before anything is printed or written.
    if args.no_install && !args.dry_run && !args.no_plugins {
        if let Some(issue) = loaded_manifest
            .as_ref()
            .and_then(|m| crate::no_install::discovery_issue(&project, m))
        {
            return Ok(Resolved {
                hand_over: Some(issue),
                ..Resolved::stopped(0)
            });
        }
    }
    // `Factory::createComposer` activates the installed plugins before
    // anything is resolved: yiisoft/yii2-composer's `activate` writes its
    // file whatever the run then does — done where the run stays
    // vivacity's (not before a hand-over to Composer, which does it).
    let activate = || -> anyhow::Result<()> {
        match &loaded_manifest {
            Some(m) => crate::no_install::activate_yii2_composer(&project, m, !args.no_plugins),
            None => Ok(()),
        }
    };
    // Flex reads its index as it activates, while the `Composer` is created
    // (`BaseCommand::initialize`), if the package arguments make it: its
    // warnings come after `Factory`'s lines and before the command's own
    // (the platform variables, `--no-suggest`) and anything `prepare_update`
    // may refuse; a refused endpoint is Composer's run. `require` and
    // `remove` do it themselves.
    if !args.command_dispatched {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
            match flex::activation_lines(&project, &m, !args.no_plugins, &args.packages) {
                Ok(lines) => vivacity_core::io::hold_after_factory(
                    vivacity_core::io::Verbosity::Normal,
                    &lines,
                ),
                Err(reason) => {
                    return Ok(Resolved {
                        hand_over: Some(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                            "symfony/flex".to_owned(),
                            reason,
                        )),
                        ..Resolved::stopped(0)
                    })
                }
            }
        }
    }
    let home = vivacity_core::fetch::composer_home();
    let http = http_transport(&project, args.offline)?;
    let cache_repo_dir = vivacity_core::fetch::composer_cache_dir().join("repo");
    let mut session = match UpdateSession::prepare_update(
        &project,
        home.as_deref(),
        true,
        Some(http),
        Some(&cache_repo_dir),
        &options,
    ) {
        Ok(s) => s,
        // The command prints and returns the code itself: the message
        // alone on stderr, nothing written.
        Err(e)
            if matches!(
                e.kind,
                vivacity_resolver::session::SessionErrorKind::Printed(_)
            ) =>
        {
            // Exit 3 (`ERROR_NO_LOCK_FILE_FOR_PARTIAL_UPDATE`) is the partial
            // update without a lock, which `Installer::doUpdate` refuses
            // after `COMMAND` (Installer.php:508-510); the temporary
            // constraints (exit 1) are refused before it
            // (UpdateCommand.php:183-193).
            if e.kind == vivacity_resolver::session::SessionErrorKind::Printed(3)
                && !args.command_dispatched
            {
                if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
                    bamarni_command_event(&project, &m, !args.no_plugins);
                }
            }
            activate()?;
            print_session_error(&e);
            if let Some(line) = &e.stdout {
                vivacity_core::out!("{line}");
            }
            let vivacity_resolver::session::SessionErrorKind::Printed(code) = e.kind else {
                unreachable!()
            };
            return Ok(Resolved::stopped(code));
        }
        // A repository vivacity cannot read as Composer does (a `path`
        // package versioned by hg, fossil or svn): the command goes to
        // Composer, before anything is written.
        Err(e) if e.kind == vivacity_resolver::session::SessionErrorKind::Unsupported => {
            return Ok(Resolved {
                hand_over: Some(vivacity_core::scope::ScopeIssue::Layout(e.message)),
                ..Resolved::stopped(0)
            });
        }
        Err(e) => {
            // `Locker::getLockedRepository(true)` throws in `doUpdate`, after
            // `UpdateCommand` dispatched `COMMAND` (bamarni's lines first).
            if e.message == vivacity_resolver::repository::LOCK_WITHOUT_DEV
                && !args.command_dispatched
            {
                if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
                    bamarni_command_event(&project, &m, !args.no_plugins);
                }
            }
            return Err(session_error(e));
        }
    };
    trace("prepare", t0);
    // A partial update's fixed packages are installed from their locked
    // dists: one `secure-http` does not let through, not installed as
    // locked, is Composer's run, now — on the lock the session read (a
    // string test per locked dist, nothing more without an insecure URL).
    // `require` and `remove` judged theirs before their edit.
    if !args.command_dispatched && !args.no_install && !args.dry_run {
        if let (Some(lock), Some(m), false) = (
            session.lock_data.as_ref(),
            loaded_manifest.as_ref(),
            options.allow_list.is_empty(),
        ) {
            let start = crate::PoolStart {
                allow: options.allow_list.clone(),
                mode: options.transitive,
                ..crate::PoolStart::default()
            };
            if let Some(reason) = crate::fallback::fixed_insecure_reason(
                &project,
                m,
                installer_dev_mode,
                !args.no_plugins,
                &start,
                lock,
            ) {
                return Ok(Resolved {
                    hand_over: Some(vivacity_core::scope::ScopeIssue::Layout(reason)),
                    ..Resolved::stopped(0)
                });
            }
        }
    }
    // symfony/flex active (installed, allowed, `extra.symfony.require` or
    // `SYMFONY_REQUIRE` set): its `PRE_POOL_CREATE` filter runs on the
    // pool, from the index fetched like Flex's Downloader does. The
    // with-install and `require` cases were handed to Composer before
    // getting here (`resolution_fallback`).
    let mut flex_active = false;
    if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
        flex_active = vivacity_core::scope::active_plugins(&project, &m, !args.no_plugins)
            .iter()
            .any(|p| p == "symfony/flex");
        if flex_active {
            // `secure-http` on Flex's endpoints, read at `PRE_POOL_CREATE`
            // (with `extra.symfony.require`) or `POST_UPDATE_CMD` (not
            // dispatched under --dry-run): refused, the run is Composer's now.
            let reads_index =
                vivacity_resolver::flex_filter::symfony_require(&m).is_some() || !args.dry_run;
            let index_hosts = match flex::endpoint_hosts(&m) {
                Ok(hosts) => hosts,
                Err(_) if !reads_index => Vec::new(),
                Err(reason) => {
                    return Ok(Resolved {
                        hand_over: Some(vivacity_core::scope::ScopeIssue::Layout(reason)),
                        ..Resolved::stopped(0)
                    })
                }
            };
            if let Some(symfony_require) = vivacity_resolver::flex_filter::symfony_require(&m) {
                let parsed = vivacity_resolver::constraint::parse_constraints(&symfony_require)
                    .map_err(|e| {
                        anyhow::anyhow!("extra.symfony.require {symfony_require:?}: {e}")
                    })?;
                let versions = flex::versions(&project, &m, args.offline)?;
                session.flex = Some(vivacity_resolver::session::FlexSession {
                    symfony_require,
                    symfony: parsed.constraint,
                    versions,
                    index_hosts,
                });
            }
        }
    }
    session.prefer_stable = prefer_stable;
    session.prefer_lowest = prefer_lowest;
    session.installer_dev_mode = installer_dev_mode;
    // `BaseCommand::initialize`: the environment fills the options left
    // empty. Its warnings were held by the command (`update`, `require`,
    // `remove`, or the `install` that resolves without a lock), at the
    // point Composer writes them.
    let (ignore_all, ignore_list) =
        platform_requirement_env(args.ignore_platform_reqs, &args.ignore_platform_req, false);
    let filter = if ignore_all {
        PlatformRequirementFilter::IgnoreAll
    } else if !ignore_list.is_empty() {
        PlatformRequirementFilter::from_list(&ignore_list)
    } else {
        PlatformRequirementFilter::IgnoreNothing
    };
    // `UpdateCommand::execute` dispatches `PluginEvents::COMMAND` after its
    // own refusals (the temporary constraints, here in `prepare_update`) and
    // before `Installer::run` (UpdateCommand.php:250); `require` and
    // `remove` have dispatched theirs already.
    if !args.command_dispatched {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
            bamarni_command_event(&project, &m, !args.no_plugins);
        }
    }
    // `Installer::run` (Installer.php:277-285): an install without a lock
    // says it updates instead, before `PRE_UPDATE_CMD` and `doUpdate`.
    if let Some(line) = &args.lockless_install {
        vivacity_core::say!("{line}");
    }
    // Under the trigger, the pool's dists are judged once it is built —
    // when the command installs (`--no-install` and `--dry-run` download
    // nothing) — and the held output goes out there.
    if hold {
        session.release_at_pool = true;
        session.scan_pool_dists = !args.no_install && !args.dry_run;
    }
    vivacity_core::say!("Loading composer repositories with package information");
    // (`Updating dependencies` is printed by the session once the pool is
    // built — Flex's notice comes before it.)
    // `Installer::run`: an unsolvable set means exit code 2
    // (`SolverProblemsException`), any other error is an exception.
    let updated = session.update(&manifest_text, &filter);
    // `require`/`remove`'s edit, held back until the pool (`io::write_held`),
    // could not be written then: Composer fails at that write, before
    // anything of the resolution — first, whatever the resolution gave.
    if let Some(why) = vivacity_core::io::take_held_write_error() {
        anyhow::bail!("{why}");
    }
    let (lock, report) = match updated {
        Ok(r) => r,
        Err(e) if e.kind == vivacity_resolver::session::SessionErrorKind::Unsolvable => {
            activate()?;
            print_session_error(&e);
            return Ok(Resolved::stopped(2));
        }
        // A request found while loading that Composer would treat in a way
        // vivacity does not (`secure-http` read from auth.json): Composer's,
        // before anything is written — after « Loading composer
        // repositories » and what loading printed, which Composer prints
        // again (the late hand-over of HANDOVER.md).
        Err(e) if e.kind == vivacity_resolver::session::SessionErrorKind::Unsupported => {
            return Ok(Resolved {
                hand_over: Some(vivacity_core::scope::ScopeIssue::Layout(e.message)),
                ..Resolved::stopped(0)
            });
        }
        Err(e) => return Err(session_error(e)),
    };
    trace("resolve", t0);

    // Under -v, a plugin the install phase would activate and whose lines
    // vivacity does not print (docs/plans/verbose-plugins.md): the command
    // goes to Composer now, before the lock is written — handed over after
    // it, the install phase would run `composer install -v`, which prints
    // `post-install-cmd` and no `_composer_tmpN`.
    if vivacity_core::io::level() == vivacity_core::io::Verbosity::Verbose
        && !args.dry_run
        && !args.no_install
        && !args.no_plugins
    {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
            if let Some((plugin, reason)) =
                crate::verbose_listeners::resolved_issue(&lock, &m, installer_dev_mode)
            {
                return Ok(Resolved {
                    hand_over: Some(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                        plugin, reason,
                    )),
                    ..Resolved::stopped(0)
                });
            }
        }
    }
    // The run is vivacity's from here on as far as -v is concerned: what
    // it kept since the start (`run_once`) is written now.
    vivacity_core::io::release_deferred();

    // symfony/flex with install: its `POST_UPDATE_CMD` applies recipes to
    // what the install lays out. vivacity emulates that only where Flex
    // would apply none — and the question is answerable exactly here, on
    // the solved lock, before anything is written.
    // The package.json / importmap.php synchronisation comes with it, and
    // it does not need the install: measured on Composer 2.10.3, `update
    // --no-install` still dispatches `POST_UPDATE_CMD` — so Flex still
    // synchronises — while `--dry-run` does not dispatch it at all.
    if !args.dry_run && !args.no_install {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
            if let Some(reason) =
                flex_reinstall_reason(&project, &m, &lock, installer_dev_mode, !args.no_plugins)
            {
                return Ok(Resolved {
                    hand_over: Some(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                        "symfony/flex".to_owned(),
                        reason,
                    )),
                    ..Resolved::stopped(0)
                });
            }
        }
    }
    // The install phase, decided on the solved lock before it is written:
    // a plugin it would install that `allow-plugins` does not cover stops
    // Composer in the middle of the installation; php-http/discovery's
    // `POST_UPDATE_CMD` may edit composer.json and update again.
    if !args.dry_run && !args.no_install && !args.no_plugins {
        if let Some(m) = &loaded_manifest {
            let parsed = vivacity_core::lock::Lock::from_value(&lock);
            let issue = crate::plugin_allow::install_issue(
                &project,
                m,
                crate::plugin_allow::installed_by(&project, m, &parsed, installer_dev_mode)
                    .iter()
                    .map(|(n, o)| (n.as_str(), *o)),
            )
            .or_else(|| crate::discovery::resolved_issue(m, &lock, installer_dev_mode))
            .or_else(|| {
                // dealerdirect's configurations not reproduced, on the
                // packages the install will leave.
                vivacity_core::scope::phpcs_lock_issue(&project, &parsed, m, installer_dev_mode)
            })
            .or_else(|| {
                // The second round of emulated plugins
                // (docs/plans/plugins-round2.md), on the packages the
                // install will leave.
                let installed = vivacity_core::layout::installed_packages_of(&project, m);
                let global = crate::effect_plugins::global_packages();
                let command = match args.resolution_command {
                    Some(vivacity_core::scope::ResolutionCommand::Require) => {
                        vivacity_core::effect_plugins::Command::Require
                    }
                    Some(vivacity_core::scope::ResolutionCommand::Remove) => {
                        vivacity_core::effect_plugins::Command::Remove
                    }
                    _ => vivacity_core::effect_plugins::Command::Update,
                };
                let ctx = vivacity_core::effect_plugins::Context {
                    project: &project,
                    manifest: m,
                    local: parsed
                        .wanted_packages(installer_dev_mode)
                        .map(|p| &p.raw)
                        .collect(),
                    installed: &installed,
                    dev_mode: installer_dev_mode,
                    command,
                    interactive: crate::effect_plugins::interactive(args.compat.no_interaction),
                    no_autoloader: args.no_autoloader,
                    plugins_enabled: true,
                    global: &global,
                    aliases: !parsed.aliases.is_empty(),
                    // The lock this update writes (or keeps virtual):
                    // what `Locker::getLockData` returns to the install.
                    lock_data: Some(&lock),
                };
                vivacity_core::effect_plugins::issues(&ctx)
                    .into_iter()
                    .next()
                    .map(vivacity_core::scope::ScopeIssue::Layout)
            });
            if let Some(issue) = issue {
                return Ok(Resolved {
                    hand_over: Some(issue),
                    ..Resolved::stopped(0)
                });
            }
        }
    }
    // `secure-http` on the dists the install phase would download, known
    // only now (a repository may serve `http://` archives): Composer would
    // write this lock, then stop at the first of them — its run, before
    // the lock is written.
    if !args.dry_run && !args.no_install && crate::install::any_insecure_dist(&lock) {
        let parsed = vivacity_core::lock::Lock::from_value(&lock);
        let null = serde_json::Value::Null;
        let m = loaded_manifest.as_ref().unwrap_or(&null);
        if let Some(reason) = crate::install::insecure_dist_reason(
            &project,
            m,
            &parsed,
            installer_dev_mode,
            !args.no_plugins,
        ) {
            return Ok(Resolved {
                hand_over: Some(vivacity_core::scope::ScopeIssue::Layout(reason)),
                ..Resolved::stopped(0)
            });
        }
    }
    let lock_path = project.join("composer.lock");
    let mut text = vivacity_core::phpjson::php_json_encode_with(
        &lock,
        vivacity_core::phpjson::FLAGS_JSONFILE,
    )?;
    // `JsonFile::read` remembers the existing lock's indentation, `write`
    // reuses it.
    let old_text = std::fs::read_to_string(&lock_path).ok();
    if let Some(old) = &old_text {
        let indent = vivacity_resolver::json_manipulator::detect_indenting(old)
            .map_err(|e| anyhow::anyhow!("{e}"))?;
        if indent != "    " {
            text = vivacity_resolver::config_source::reindent(&text, &indent);
        }
    }
    text.push('\n');
    // `JsonFile::write` goes through `filePutContentsIfModified`: the file
    // is only rewritten if its bytes change. (`Locker::setLockData` also
    // compares the decoded data, but `{}` versus `[]` makes that comparison
    // always false for an ordinary lock; the bytes are the observable
    // criterion.)
    let unchanged = old_text.as_deref() == Some(text.as_str());
    // `config.lock: false`: Composer resolves without writing a lock.
    let write_lock = config_lock_enabled(&manifest_text);
    // With recipes, Flex's plan: computed now, applied at
    // `POST_UPDATE_CMD` by the install phase.
    let mut flex_plan: Option<std::sync::Arc<crate::flex_recipes::FlexPlan>> = None;
    if flex_active && !args.dry_run {
        if let Ok(m) = serde_json::from_str::<serde_json::Value>(&manifest_text) {
            let reason = if args.no_install {
                None
            } else {
                match flex_install_decision(
                    &project,
                    &m,
                    &manifest_text,
                    &lock,
                    write_lock.then_some(text.as_str()),
                    installer_dev_mode,
                    args.offline,
                    !args.no_plugins,
                )? {
                    FlexDecision::HandOver(reason) => Some(reason),
                    FlexDecision::Native(plan) => {
                        flex_plan = plan.map(std::sync::Arc::new);
                        None
                    }
                }
            };
            // With a plan, the synchronisation was decided on the files the
            // recipes leave.
            let reason = reason.or_else(|| {
                if flex_plan.is_some() {
                    None
                } else {
                    flex_sync_reason(&project, &m, &lock)
                }
            });
            if let Some(reason) = reason {
                return Ok(Resolved {
                    hand_over: Some(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                        "symfony/flex".to_owned(),
                        reason,
                    )),
                    ..Resolved::stopped(0)
                });
            }
        }
    }

    // `Flex::enableThanksReminder` on `POST_PACKAGE_UPDATE`: the reminder
    // needs one update operation, so it is decided here, on the state the
    // install is about to replace. `class_exists(Thanks::class, false)` is
    // true exactly when Composer activated the symfony/thanks plugin — from
    // the project or from COMPOSER_HOME — since nothing autoloads it.
    // Flex arms it for the `update` command only (`Flex::activate`): not for
    // the `install` that updates without a lock.
    let thanks_reminder =
        flex_active && !args.dry_run && !args.no_install && args.lockless_install.is_none() && {
            let m: serde_json::Value =
                serde_json::from_str(&manifest_text).unwrap_or(serde_json::Value::Null);
            let loaded = vivacity_core::scope::active_plugins(&project, &m, !args.no_plugins)
                .iter()
                .any(|p| p == "symfony/thanks");
            let installed = installed_packages(&project, &m);
            !loaded
                && vivacity_core::lock::Lock::from_value(&lock)
                    .wanted_packages(installer_dev_mode)
                    .any(|p| {
                        installed.iter().any(|i| {
                            i.get("name").and_then(serde_json::Value::as_str) == Some(p.name())
                        }) && !installed_as_locked(&installed, p)
                    })
        };

    let ops = &report.transaction.transaction.operations;
    // What `Installer::doUpdate` writes between the resolution and the lock
    // operations (the resolution lines, `Nothing to modify in lock file`),
    // held by the session until the checks above have decided the run is
    // vivacity's: a delegation lets Composer write its own.
    for (level, line) in &report.events {
        vivacity_core::say_at!(*level, "{line}");
    }
    if !ops.is_empty() && write_lock {
        let count = |f: &dyn Fn(&vivacity_resolver::transaction::Operation) -> bool| {
            ops.iter().filter(|o| f(o)).count()
        };
        use vivacity_resolver::transaction::Operation;
        let installs = count(&|o| matches!(o, Operation::Install(_)));
        let updates = count(&|o| matches!(o, Operation::Update(..)));
        let removals = count(&|o| matches!(o, Operation::Uninstall(_)));
        vivacity_core::say!(
            "Lock file operations: {installs} install{}, {updates} update{}, {removals} removal{}",
            if installs == 1 { "" } else { "s" },
            if updates == 1 { "" } else { "s" },
            if removals == 1 { "" } else { "s" }
        );
        // At VERBOSE, the names in the transaction's own order.
        for line in vivacity_resolver::transaction::verbose_operation_summary(ops, &session.arena) {
            vivacity_core::say_verbose!("{line}");
        }
        // `  - Locking …` / `Upgrading` / `Removing`, removals first, by name.
        for line in vivacity_resolver::transaction::lock_operation_lines(&session.arena, ops) {
            vivacity_core::say!("{line}");
        }
    }
    // `$updatedLock && $this->writeLock && $this->executeOperations`: a dry
    // run neither writes nor says so.
    if write_lock && !args.dry_run {
        vivacity_core::say!("Writing lock file");
        if !unchanged {
            let _gate = vivacity_core::signals::write_gate();
            std::fs::write(&lock_path, &text)
                .with_context(|| format!("cannot write {}", lock_path.display()))?;
        }
    }
    trace("write lock", t0);
    // `Installer::run` after `doUpdate` (and its install), before the dump:
    // the suggestions of the newly installed packages (and of the root on a
    // fresh install), the abandoned packages of the new lock.
    let manifest = patched_manifest(&session, &manifest_text);
    let fresh_install = !composer_dir_of(&project, &manifest)
        .join("installed.json")
        .is_file();
    let post = post_update_report(&session, ops, &lock, &manifest_text, fresh_install);
    activate()?;
    Ok(Resolved {
        status: 0,
        virtual_lock: !write_lock,
        lock: Some(lock),
        post,
        manifest,
        // Measured on Composer 2.10.3: `--dry-run` does not dispatch
        // `POST_UPDATE_CMD` at all, so Flex prints nothing — not even the
        // recipes hint. `--no-install` does dispatch it.
        flex_active: flex_active && !args.dry_run,
        thanks_reminder,
        flex_plan,
        hand_over: None,
    })
}

/// composer.json with the session root's `require`/`require-dev` (the
/// in-memory patch of a dry run applied; identical otherwise).
pub(crate) fn patched_manifest(
    session: &vivacity_resolver::session::UpdateSession,
    manifest_text: &str,
) -> serde_json::Value {
    let mut manifest: serde_json::Value = serde_json::from_str(manifest_text).unwrap_or_default();
    let links_to_object = |links: &vivacity_resolver::package::Links| -> serde_json::Value {
        let mut map = serde_json::Map::new();
        for l in links.iter() {
            map.insert(
                l.target.clone(),
                serde_json::Value::String(l.pretty_constraint.clone()),
            );
        }
        serde_json::Value::Object(map)
    };
    if let Some(obj) = manifest.as_object_mut() {
        for (key, links) in [
            ("require", &session.root.package.requires),
            ("require-dev", &session.root.package.dev_requires),
        ] {
            if links.is_empty() {
                obj.remove(key);
            } else {
                obj.insert(key.to_owned(), links_to_object(links));
            }
        }
    }
    manifest
}

/// The lines of `Installer::run` after a successful update:
/// `SuggestedPackagesReporter::outputMinimalistic` (suggestions of the
/// packages installed by this update, plus the root's own on a fresh
/// install, minus the targets some other package provides), one warning
/// per abandoned package of the new lock. The install phase prints them
/// before its dump; [`print_post_update`] without one.
pub(crate) fn post_update_report(
    session: &vivacity_resolver::session::UpdateSession,
    ops: &[vivacity_resolver::transaction::Operation],
    lock: &serde_json::Value,
    manifest_text: &str,
    fresh_install: bool,
) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    use vivacity_resolver::transaction::Operation;
    let manifest: serde_json::Value = serde_json::from_str(manifest_text).unwrap_or_default();
    // (source pretty name, target)
    let mut suggestions: Vec<(String, String)> = Vec::new();
    let add_from =
        |suggestions: &mut Vec<(String, String)>, source: &str, raw: &serde_json::Value| {
            if let Some(map) = raw.get("suggest").and_then(serde_json::Value::as_object) {
                for target in map.keys() {
                    suggestions.push((source.to_owned(), target.clone()));
                }
            }
        };
    for op in ops {
        if let Operation::Install(idx) = op {
            let p = &session.arena[*idx];
            add_from(&mut suggestions, &p.pretty_name, &p.raw);
        }
    }
    if fresh_install {
        let root_name = manifest
            .get("name")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("__root__");
        add_from(&mut suggestions, root_name, &manifest);
    }
    if !suggestions.is_empty() {
        // `InstalledRepository([locked repo (dev mode), platform repo, root])`:
        // `getNames()` of each package -> the packages providing that name.
        let mut installed_names: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        let mut add_names = |name: &str, names: Vec<String>| {
            for n in names {
                installed_names.entry(n).or_default().push(name.to_owned());
            }
        };
        let mut lock_sections = vec!["packages"];
        if session.installer_dev_mode {
            lock_sections.push("packages-dev");
        }
        for section in lock_sections {
            for p in lock
                .get(section)
                .and_then(serde_json::Value::as_array)
                .into_iter()
                .flatten()
            {
                let Some(name) = p.get("name").and_then(serde_json::Value::as_str) else {
                    continue;
                };
                let name = name.to_lowercase();
                let mut names = vec![name.clone()];
                for key in ["provide", "replace"] {
                    for target in p
                        .get(key)
                        .and_then(serde_json::Value::as_object)
                        .into_iter()
                        .flat_map(|m| m.keys())
                    {
                        if !names.contains(target) {
                            names.push(target.clone());
                        }
                    }
                }
                add_names(&name, names);
            }
        }
        for &idx in &session.platform {
            let p = &session.arena[idx];
            add_names(&p.name, p.names(true));
        }
        let root = &session.root.package;
        add_names(&root.name, root.names(true));
        let count = suggestions
            .iter()
            .filter(|(source, target)| {
                let source_lower = source.to_lowercase();
                !installed_names
                    .get(target)
                    .is_some_and(|providers| providers.iter().any(|p| *p != source_lower))
            })
            .count();
        if count > 0 {
            out.push(format!(
                "{count} package suggestions were added by new dependencies, use `composer suggest` to see details."
            ));
        }
    }
    out.extend(abandoned_warnings(lock));
    out
}

/// Minimal `join_all` (no futures dependency): the tasks run concurrently
/// on the runtime, results in order.
pub(crate) async fn futures_join_all<F: std::future::Future + Send + 'static>(
    tasks: Vec<F>,
) -> Vec<F::Output>
where
    F::Output: Send + 'static,
{
    let handles: Vec<_> = tasks.into_iter().map(tokio::spawn).collect();
    let mut out = Vec::with_capacity(handles.len());
    for h in handles {
        out.push(h.await.expect("metadata task panicked"));
    }
    out
}

/// `Locker::getMissingRequirementInfo`: the root requirements the lock
/// does not satisfy — `require` against the non-dev lock, `require-dev`
/// against the whole lock — with replacers and providers counting, and
/// the three fixed lines when anything is missing.
pub(crate) fn missing_requirement_info(
    manifest: &serde_json::Value,
    lock: &serde_json::Value,
    include_dev: bool,
    root_version: &str,
    root_pretty_version: &str,
    merged_links: Option<(
        &[vivacity_resolver::merge_plugin::MergedLink],
        &[vivacity_resolver::merge_plugin::MergedLink],
    )>,
) -> anyhow::Result<Vec<String>> {
    use vivacity_resolver::constraint::{parse_constraints, Constraint, Op};
    use vivacity_resolver::package::{Origin, Package};
    let mut out = Vec::new();
    let mut missing = false;
    let root_name = manifest
        .get("name")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("__root__")
        .to_lowercase();
    // `RootPackageRepository`: the root itself, with its `replace` and
    // `provide` links (`self.version` = its version), is a candidate too.
    // (target, constraint, pretty constraint, "replaced"/"provided")
    let root_links: Vec<(String, Constraint, String, &str)> =
        [("replace", "replaced"), ("provide", "provided")]
            .iter()
            .flat_map(|(key, word)| {
                manifest
                    .get(*key)
                    .and_then(serde_json::Value::as_object)
                    .into_iter()
                    .flat_map(|m| m.iter())
                    .filter_map(move |(t, c)| {
                        let text = c.as_str()?;
                        let source = if text == "self.version" {
                            root_version
                        } else {
                            text
                        };
                        Some((
                            t.to_lowercase(),
                            parse_constraints(source).ok()?.constraint,
                            text.to_owned(),
                            *word,
                        ))
                    })
            })
            .collect();
    let root_eq = Constraint::new(Op::Eq, root_version);
    let mut sets: Vec<(bool, &str, &str)> = vec![(false, "require", "Required")];
    if include_dev {
        sets.push((true, "require-dev", "Required (in require-dev)"));
    }
    for (with_dev, key, description) in sets {
        let mut arena: Vec<Package> = Vec::new();
        let repo =
            vivacity_resolver::repository::locked_repository_with(lock, &mut arena, with_dev)
                .map_err(|e| anyhow::anyhow!("composer.lock: {}", e.0))?;
        // The root's links: the merged, structured ones when the merge
        // plugin is active (a duplicate key is a conjunction the text of
        // the manifest cannot carry faithfully), else the manifest's.
        let links: Vec<(String, String, Constraint)> = match merged_links {
            Some((req, dev)) => (if with_dev { dev } else { req })
                .iter()
                .map(|l| (l.target.clone(), l.pretty.clone(), l.constraint.clone()))
                .collect(),
            None => {
                let Some(map) = manifest.get(key).and_then(serde_json::Value::as_object) else {
                    continue;
                };
                map.iter()
                    .filter_map(|(target, pretty)| {
                        let pretty = pretty.as_str()?;
                        let parsed = parse_constraints(pretty).ok()?;
                        Some((target.to_lowercase(), pretty.to_owned(), parsed.constraint))
                    })
                    .collect()
            }
        };
        for (target, pretty, constraint) in links {
            let pretty = pretty.as_str();
            if vivacity_resolver::platform::is_platform_package(&target) || pretty == "self.version"
            {
                continue;
            }
            let parsed = vivacity_resolver::constraint::ParsedConstraint {
                constraint,
                pretty: pretty.to_owned(),
            };
            // `findPackagesWithReplacersAndProviders($target, $constraint)`
            // over [lock repo, root repo]: a package of that name, or a
            // replacer/provider whose link matches the constraint.
            let matches = |idx: usize, constraint: Option<&Constraint>| -> bool {
                let p = &arena[idx];
                if p.name == target {
                    return constraint
                        .is_none_or(|c| c.matches(&Constraint::new(Op::Eq, p.version.clone())));
                }
                p.replaces.iter().chain(p.provides.iter()).any(|l| {
                    l.target == target && constraint.is_none_or(|c| c.matches(&l.constraint))
                })
            };
            let root_matches = |constraint: Option<&Constraint>| -> bool {
                if root_name == target {
                    return constraint.is_none_or(|c| c.matches(&root_eq));
                }
                root_links
                    .iter()
                    .any(|(t, lc, _, _)| *t == target && constraint.is_none_or(|c| c.matches(lc)))
            };
            if repo.iter().any(|&i| matches(i, Some(&parsed.constraint)))
                || root_matches(Some(&parsed.constraint))
            {
                continue;
            }
            let any: Option<usize> = repo.iter().copied().find(|&i| matches(i, None));
            let line = match any {
                Some(idx) => {
                    let p = &arena[idx];
                    let mut description_text = p.pretty_version.clone();
                    if p.name != target {
                        for (links, text) in [
                            (&p.replaces, "replaced as {} by {}"),
                            (&p.provides, "provided as {} by {}"),
                        ] {
                            if let Some(l) = links.iter().find(|l| l.target == target) {
                                description_text =
                                    text.replacen("{}", &l.pretty_constraint, 1).replacen(
                                        "{}",
                                        &format!("{} {}", p.pretty_name, p.pretty_version),
                                        1,
                                    );
                                break;
                            }
                        }
                    }
                    format!("- {description} package \"{target}\" is in the lock file as \"{description_text}\" but that does not satisfy your constraint \"{pretty}\".")
                }
                // The root repository comes after the lock's: the root by
                // name, or through one of its replace/provide links.
                None if root_matches(None) => {
                    let root_name_pretty = manifest
                        .get("name")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("__root__");
                    let description_text = if root_name == target {
                        root_pretty_version.to_owned()
                    } else {
                        match root_links.iter().find(|(t, _, _, _)| *t == target) {
                            Some((_, _, pc, word)) => {
                                format!(
                                    "{word} as {pc} by {root_name_pretty} {root_pretty_version}"
                                )
                            }
                            None => root_pretty_version.to_owned(),
                        }
                    };
                    format!("- {description} package \"{target}\" is in the lock file as \"{description_text}\" but that does not satisfy your constraint \"{pretty}\".")
                }
                None => {
                    format!("- {description} package \"{target}\" is not present in the lock file.")
                }
            };
            out.push(line);
            missing = true;
        }
        let _ = Origin::Locked;
    }
    if missing {
        out.push("This usually happens when composer files are incorrectly merged or the composer.json file is manually edited.".to_owned());
        out.push("Read more about correctly resolving merge conflicts https://getcomposer.org/doc/articles/resolving-merge-conflicts.md".to_owned());
        out.push("and prefer using the \"require\" command over editing the composer.json file directly https://getcomposer.org/doc/03-cli.md#require-r".to_owned());
    }
    Ok(out)
}

/// `remove --unused`: the lock's packages (non-dev) required neither by
/// the root nor by any package reachable from it, in lock order.
pub(crate) fn unused_locked_packages(
    manifest: &serde_json::Value,
    lock: &serde_json::Value,
) -> Vec<String> {
    use std::collections::BTreeSet;
    let mut required: BTreeSet<String> = BTreeSet::new();
    for section in ["require", "require-dev"] {
        if let Some(m) = manifest.get(section).and_then(|v| v.as_object()) {
            required.extend(m.keys().map(|k| k.to_lowercase()));
        }
    }
    let mut locked: Vec<&serde_json::Value> = lock
        .get("packages")
        .and_then(|p| p.as_array())
        .map(|a| a.iter().collect())
        .unwrap_or_default();
    let names = |p: &serde_json::Value| -> Vec<String> {
        let mut out = vec![p
            .get("name")
            .and_then(|n| n.as_str())
            .unwrap_or("")
            .to_lowercase()];
        for key in ["replace", "provide"] {
            if let Some(m) = p.get(key).and_then(|v| v.as_object()) {
                out.extend(m.keys().map(|k| k.to_lowercase()));
            }
        }
        out
    };
    loop {
        let mut found = false;
        let mut i = 0;
        while i < locked.len() {
            let p = locked[i];
            if names(p).iter().any(|n| required.contains(n)) {
                if let Some(m) = p.get("require").and_then(|v| v.as_object()) {
                    required.extend(m.keys().map(|k| k.to_lowercase()));
                }
                found = true;
                locked.remove(i);
            } else {
                i += 1;
            }
        }
        if !found {
            break;
        }
    }
    locked
        .iter()
        .map(|p| {
            p.get("name")
                .and_then(|n| n.as_str())
                .unwrap_or("")
                .to_lowercase()
        })
        .collect()
}

#[cfg(test)]
mod temporary_requirement_tests {
    use super::{package_of_requirement, temporary_requirements};

    fn v(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| (*s).to_owned()).collect()
    }

    #[test]
    fn parses_the_three_forms_and_the_shorthand() {
        // `--with` takes `a/b:^1`, `a/b=^1` and `a/b ^1`.
        let reqs =
            temporary_requirements(&v(&["a/b:^1", "c/d=^2", "e/f ^3"]), &[]).expect("parsed");
        assert_eq!(
            reqs,
            vec![
                ("a/b".to_owned(), "^1".to_owned()),
                ("c/d".to_owned(), "^2".to_owned()),
                ("e/f".to_owned(), "^3".to_owned())
            ]
        );
        // A `packages` entry carrying a constraint joins them; a bare name
        // does not.
        let reqs = temporary_requirements(&[], &v(&["a/b:^1", "c/d"])).expect("parsed");
        assert_eq!(reqs, vec![("a/b".to_owned(), "^1".to_owned())]);
        // `$reqs[$package] = $constraint`: the argument wins over `--with`.
        let reqs = temporary_requirements(&v(&["a/b:^1"]), &v(&["a/b:^2"])).expect("parsed");
        assert_eq!(reqs, vec![("a/b".to_owned(), "^2".to_owned())]);
        // The allow list takes the name alone.
        assert_eq!(package_of_requirement("a/b:^1"), "a/b");
        assert_eq!(package_of_requirement("a/b=^1"), "a/b");
        assert_eq!(package_of_requirement("a/b ^1"), "a/b");
        assert_eq!(package_of_requirement("a/b"), "a/b");
        assert_eq!(package_of_requirement("a/*"), "a/*");
    }

    #[test]
    fn a_pair_without_a_version_is_an_error() {
        let e = temporary_requirements(&v(&["a/b"]), &[])
            .unwrap_err()
            .to_string();
        assert_eq!(
            e,
            "Option a/b is missing a version constraint, use e.g. a/b:^1.0"
        );
    }
}