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
//! Handing a command to the real Composer: before any write, with the same
//! arguments, or stopping with exit 3 under `--no-fallback`.

use super::*;

/// The resolution commands' fallback (plan v0.16, decision 1), symmetric
/// to `install`'s: an installed, allowed plugin that changes what the
/// command resolves or writes, and that vivacity does not emulate for it,
/// hands the whole command to Composer with the same arguments — before
/// any write (the caller reverts its manifest edit first). `--no-fallback`
/// stops with exit 3 instead. `Some(code)` when the command was handled
/// here; `None` when vivacity goes on natively. `post_update_cmd`: the
/// command dispatches `POST_UPDATE_CMD` (not a dry run) — without an
/// install, to the plugins loaded from installed.json
/// (docs/plans/no-install-listeners.md).
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolution_fallback(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    command: vivacity_core::scope::ResolutionCommand,
    no_plugins: bool,
    no_fallback: bool,
    with_install: bool,
    post_update_cmd: bool,
    with_dev: bool,
    start: &PoolStart<'_>,
) -> anyhow::Result<Option<i32>> {
    let mut issues = vivacity_core::scope::resolution_issues(
        project,
        manifest,
        command,
        !no_plugins,
        with_install,
        post_update_cmd,
    );
    // laminas-skeleton-installer, configured, rewrites composer.json at
    // `POST_UPDATE_CMD`; `require` and `remove` read the file again for the
    // lock's hash afterwards (docs/plans/plugins-round2.md). Decided now,
    // before the command edits composer.json.
    if !no_plugins
        && matches!(
            command,
            vivacity_core::scope::ResolutionCommand::Require
                | vivacity_core::scope::ResolutionCommand::Remove
        )
        && vivacity_core::scope::active_plugins(project, manifest, true)
            .iter()
            .any(|p| p == vivacity_core::effect_plugins::LAMINAS_SKELETON)
        && vivacity_core::effect_plugins::laminas_skeleton_configured(manifest) == Ok(true)
    {
        issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
            vivacity_core::effect_plugins::LAMINAS_SKELETON.to_owned(),
            "rewrites composer.json, which the command reads again for the lock's hash (not emulated)".to_owned(),
        ));
    }
    // Without an install, `POST_UPDATE_CMD` still runs the loaded plugins'
    // listeners on the local repository: what vivacity cannot reproduce
    // there goes to Composer now, before anything is written.
    if !with_install && post_update_cmd && !no_plugins {
        issues.extend(crate::no_install::issues_before_resolution(
            project, manifest, with_dev,
        ));
    }
    // Flex emulated for this command: its file-writing behaviours are
    // still Composer's.
    let flex_active = vivacity_core::scope::active_plugins(project, manifest, !no_plugins)
        .iter()
        .any(|p| p == "symfony/flex");
    if flex_active && !issues.iter().any(|i| matches!(i, vivacity_core::scope::ScopeIssue::ResolutionPlugin(n, _) if n == "symfony/flex")) {
        if let Some(reason) = flex_write_guard(project, manifest) {
            issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                "symfony/flex".to_owned(),
                reason,
            ));
        }
    }
    // The merge plugin emulated: a merged file's `repositories`
    // (`prependRepositories`) is not. Dev mode does not matter here — the
    // files are merged whatever the mode, only their `require-dev` waits.
    let merge_active = vivacity_core::scope::active_plugins(project, manifest, !no_plugins)
        .iter()
        .any(|p| p == vivacity_resolver::merge_plugin::PLUGIN_NAME);
    if merge_active {
        if let Ok(Some(merged)) = merge_root_when(project, manifest, true, true) {
            if !merged.repositories.is_empty() {
                issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
                    vivacity_resolver::merge_plugin::PLUGIN_NAME.to_owned(),
                    format!(
                        "merges repositories from {} (not emulated at resolution)",
                        merged.repositories.join(", ")
                    ),
                ));
            }
        }
    }
    // `secure-http` on the `composer` repositories the resolution reads —
    // the project's and the global config.json's, merged as `Config::merge`
    // merges them: decided here, before `require` or `remove` edit
    // composer.json and before anything is printed.
    issues.extend(insecure_repository_issue(
        project,
        manifest,
        with_install,
        with_dev,
        !no_plugins,
        start,
    ));
    if issues.is_empty() {
        return Ok(None);
    }
    delegate_resolution(&issues, no_fallback).map(Some)
}

/// Whether the command holds its output while a `secure-http` hand-over
/// may still come late (the maintainer's narrow trigger, 2026-10-30): a
/// remote `composer` repository other than packagist.org configured, and
/// `secure-http` true — such a repository may serve metadata or dists over
/// `http`, which only its files tell. Packagist alone: never. A test on the
/// JSON in memory — composer.json's `repositories` and the global
/// config.json's (kept for the run) — broader than the merged list (a
/// repository disabled by name still counts: one hold too many at worst);
/// the setting is read only once such a repository is there.
/// `VIVACITY_HOLD_OUTPUT=force` holds whatever the configuration (the
/// harnesses: no local `https` server stands in for a remote repository).
pub(crate) fn hold_trigger(manifest: &serde_json::Value) -> bool {
    // Decided once per run: `require`/`remove` before their edit, which
    // touches no repository; the resolution and the install phase that
    // follow ask again.
    let mut memo = HOLD_TRIGGER
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(decided) = *memo {
        return decided;
    }
    let decided = evaluate_hold_trigger(manifest);
    *memo = Some(decided);
    decided
}

/// [`hold_trigger`] for the run (`None`: not decided yet).
static HOLD_TRIGGER: std::sync::Mutex<Option<bool>> = std::sync::Mutex::new(None);

/// A new run decides again.
pub(crate) fn forget_hold_trigger() {
    *HOLD_TRIGGER
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}

fn evaluate_hold_trigger(manifest: &serde_json::Value) -> bool {
    if std::env::var("VIVACITY_HOLD_OUTPUT").as_deref() == Ok("force") {
        return true;
    }
    fn remote(repos: Option<&serde_json::Value>) -> bool {
        use serde_json::Value;
        let entries: Box<dyn Iterator<Item = &Value>> = match repos {
            Some(Value::Array(a)) => Box::new(a.iter()),
            Some(Value::Object(o)) => Box::new(o.values()),
            _ => return false,
        };
        entries.into_iter().any(|r| {
            if r.get("type").and_then(Value::as_str) != Some("composer") {
                return false;
            }
            let Some(url) = r.get("url").and_then(Value::as_str) else {
                return false;
            };
            let lower = url.to_ascii_lowercase();
            let Some(rest) = ["https?://", "https://", "http://"]
                .iter()
                .find_map(|p| lower.strip_prefix(p))
            else {
                // A path, or a host without a scheme (`http://`, which
                // secure-http refuses up front anyway).
                return !lower.contains("://") && !std::path::Path::new(url).exists();
            };
            let host = rest.split(['/', ':']).next().unwrap_or("");
            host != "repo.packagist.org" && host != "packagist.org"
        })
    }
    let configured = remote(manifest.get("repositories"))
        || vivacity_core::fetch::composer_home().is_some_and(|home| {
            vivacity_core::fetch::with_global_json(&home, "config.json", |c| {
                remote(c.and_then(|c| c.get("repositories")))
            })
        });
    configured && secure_http_refuses()
}

fn secure_http_refuses() -> bool {
    use vivacity_core::secure_http::{classify, Verdict};
    matches!(
        classify("http://localhost/"),
        Verdict::Refuse | Verdict::HandOver(_)
    )
}

/// Starts holding the output, with a trace marker the harnesses look for.
pub(crate) fn start_holding(until: &str) {
    if vivacity_core::io::holding_output() {
        return;
    }
    vivacity_core::io::hold_output();
    if std::env::var_os("VIVACITY_TRACE").is_some() {
        eprintln!("trace: output held until {until} (secure-http)");
    }
}

/// What a resolution's pool starts from, as the command knows it before
/// anything is printed: `update <packages>` (the allow list and its
/// transitive mode), `require` (the requirements it adds, which a lock
/// makes the allow list), `remove` (the packages it drops). Empty: a full
/// update.
#[derive(Default)]
pub(crate) struct PoolStart<'a> {
    pub allow: Vec<String>,
    pub mode: Option<vivacity_resolver::pool::UpdateMode>,
    pub added: Vec<(String, String)>,
    pub removed: Vec<String>,
    /// The lock, when the command has it in memory already (`remove`).
    pub lock: Option<&'a serde_json::Value>,
    /// The command resolves nothing (`remove --no-update`, `require
    /// --no-update` with every constraint given): no repository is opened,
    /// nothing about them counts.
    pub no_resolution: bool,
}

/// `install`'s pool filters on the lock (`verify_install`) on a local
/// `composer` repository: a custom policy list it advertises, or a filter
/// `api-url` its `malware` list would need (the `install` scope never loads
/// metadata) — read now, before anything is printed. Nothing to do (no
/// merge, no read) without a local `composer` repository in composer.json
/// or the global config.json.
pub(crate) fn local_install_issue(manifest: &serde_json::Value) -> Option<String> {
    use serde_json::Value;
    let local = |repos: Option<&Value>| -> bool {
        let entries: Box<dyn Iterator<Item = &Value>> = match repos {
            Some(Value::Array(a)) => Box::new(a.iter()),
            Some(Value::Object(o)) => Box::new(o.values()),
            _ => return false,
        };
        entries.into_iter().any(|r| {
            r.get("type").and_then(Value::as_str) == Some("composer")
                && r.get("url")
                    .and_then(Value::as_str)
                    .is_some_and(|u| u.starts_with("file://") || !u.contains("://"))
        })
    };
    let home = vivacity_core::fetch::composer_home();
    let any = local(manifest.get("repositories"))
        || home.as_deref().is_some_and(|h| {
            vivacity_core::fetch::with_global_json(h, "config.json", |c| {
                local(c.and_then(|c| c.get("repositories")))
            })
        });
    if !any {
        return None;
    }
    let config = vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()).ok()?;
    let policy = vivacity_resolver::policy_config::PolicyConfig::from_raw(&config.policy).ok()?;
    let repos: Vec<(String, Option<Value>)> = config
        .repositories
        .iter()
        .filter(|r| r.definition.get("type").and_then(Value::as_str) == Some("composer"))
        .filter_map(|r| {
            let url = r.definition.get("url").and_then(Value::as_str)?;
            vivacity_resolver::repository::repo_urls(url)
                .packages_json_url
                .starts_with("file://")
                .then(|| (url.to_owned(), r.definition.get("filter").cloned()))
        })
        .collect();
    vivacity_resolver::repository::local_unsupported(
        &repos,
        &policy.custom_lists,
        false,
        policy.malware_blocks("install"),
    )
}

/// What creating the `Composer` (every command) refuses or warns about in a
/// repository definition, decided at startup on the JSON in memory —
/// composer.json's `repositories` and the global config.json's (kept for
/// the run): nothing to do without such a section. Broader than the merged
/// list (a definition disabled by name still counts: a hand-over Composer
/// would not need). `RepositoryManager::createRepository` warns about a
/// `packagist` key set to false (every time the `Composer` is created:
/// handed over rather than written); `RepositoryFactory::createRepos`, the
/// `FilterRepository` and `ComposerRepository` constructors throw on a
/// definition that is not an object, has no type, a bad `only`/`exclude`/
/// `canonical`, a `composer` URL `parse_url` refuses (no host, a bad port)
/// or a user `filter` that is not booleans by list name. A doubt hands
/// over.
pub(crate) fn repository_construction_issue(
    project: Option<&std::path::Path>,
    manifest: Option<&serde_json::Value>,
) -> Option<String> {
    use serde_json::Value;
    let check = |repos: Option<&Value>| -> Option<String> {
        let entries: Vec<(String, &Value)> = match repos {
            None | Some(Value::Null) => return None,
            Some(Value::Array(a)) => a
                .iter()
                .enumerate()
                .map(|(i, r)| (i.to_string(), r))
                .collect(),
            Some(Value::Object(o)) => o.iter().map(|(k, r)| (k.clone(), r)).collect(),
            Some(_) => return Some("\"repositories\" is not a list of definitions".to_owned()),
        };
        for (name, repo) in entries {
            let def = match repo {
                // `"name": false` disables a repository (`Config::merge`).
                Value::Bool(false) => continue,
                Value::Object(m) => m,
                _ => return Some(format!("repository {name} is not a definition")),
            };
            // `{"packagist.org": false}`: the same, in a list.
            if def.len() == 1 && def.values().next() == Some(&Value::Bool(false)) {
                continue;
            }
            let Some(kind) = def.get("type") else {
                return Some(format!("repository {name} has no type"));
            };
            if def.get("packagist") == Some(&Value::Bool(false)) {
                return Some(format!(
                    "repository {name} has a packagist key, which Composer warns about"
                ));
            }
            let set = |k: &str| def.get(k).filter(|v| !v.is_null());
            let array = |v: &Value| v.is_array() || v.is_object();
            if set("only").is_some_and(|v| !array(v))
                || set("exclude").is_some_and(|v| !array(v))
                || (set("only").is_some() && set("exclude").is_some())
                || set("canonical").is_some_and(|v| !v.is_boolean())
            {
                return Some(format!(
                    "repository {name} has an only/exclude/canonical Composer refuses"
                ));
            }
            if kind.as_str() != Some("composer") {
                continue;
            }
            let refused = match def.get("url") {
                Some(Value::String(url)) => composer_url_refused(project, url),
                _ => true,
            };
            if refused {
                return Some(format!(
                    "repository {name} has a url Composer refuses for a composer repository"
                ));
            }
            if def.get("filter").is_some_and(user_filter_refused) {
                return Some(format!("repository {name} has a filter Composer refuses"));
            }
        }
        None
    };
    if let Some(why) = check(manifest.and_then(|m| m.get("repositories"))) {
        return Some(why);
    }
    let home = vivacity_core::fetch::composer_home()?;
    vivacity_core::fetch::with_global_json(&home, "config.json", |c| {
        check(c.and_then(|c| c.get("repositories")))
    })
}

/// `ComposerRepository::__construct`'s URL: without `scheme://`, a path
/// that exists becomes `file://`, anything else `http://`; then `rtrim`
/// of `/` and `parse_url`, which must give a scheme. `true` where
/// `parse_url` fails as mirrored here — a scheme other than `file` without
/// a host, a port `parse_url` refuses ([`php_port`]) — checked against PHP
/// 8.4's `parse_url` on the forms of the unit test below.
fn composer_url_refused(project: Option<&std::path::Path>, url: &str) -> bool {
    let bytes = url.as_bytes();
    let word = bytes
        .iter()
        .take_while(|b| b.is_ascii_alphanumeric() || **b == b'_' || **b == b'.')
        .count();
    let after = if bytes.get(word) == Some(&b'?') {
        word + 1
    } else {
        word
    };
    let owned;
    let url = if word > 0 && url[after..].starts_with("://") {
        url
    } else {
        let path = std::path::Path::new(url);
        let exists = if path.is_absolute() {
            path.exists()
        } else {
            project.is_some_and(|p| p.join(path).exists())
        };
        if exists {
            return false;
        }
        owned = format!("http://{url}");
        &owned
    };
    let url = url.trim_end_matches('/').replace('\\', "/");
    let Some((scheme, rest)) = url.split_once("://") else {
        return true;
    };
    if scheme.eq_ignore_ascii_case("file") {
        return false;
    }
    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    let host_port = authority.rsplit('@').next().unwrap_or("");
    if host_port.is_empty() {
        return true;
    }
    // `php_url_parse_ex`: no port in a host that is all in brackets;
    // otherwise the last `:` starts the port (so `[::1` and `[::1]x` read
    // as host `[:`, port 1, as PHP reads them).
    let port = if host_port.starts_with('[') && host_port.ends_with(']') {
        ""
    } else {
        match host_port.rsplit_once(':') {
            Some(("", _)) => return true,
            Some((_, port)) => port,
            None => "",
        }
    };
    !(port.is_empty() || php_port(port))
}

/// A port `parse_url` accepts: at most five characters, read by `strtol`
/// (leading blanks, a sign, at least one digit, what follows ignored), in
/// 0..=65535.
fn php_port(port: &str) -> bool {
    if port.len() > 5 {
        return false;
    }
    let s = port.trim_start_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']);
    let (negative, s) = match s.as_bytes().first() {
        Some(b'-') => (true, &s[1..]),
        Some(b'+') => (false, &s[1..]),
        _ => (false, s),
    };
    let digits: String = s.chars().take_while(char::is_ascii_digit).collect();
    if digits.is_empty() {
        return false;
    }
    let value: i64 = digits.parse().unwrap_or(i64::MAX);
    !negative && value <= 65535 || (negative && value == 0)
}

/// `parseUserFilterConfig`: `false`, `null`, `true`, or list names (PHP
/// array keys: a numeric string is an integer there) mapped to booleans.
fn user_filter_refused(filter: &serde_json::Value) -> bool {
    use serde_json::Value;
    let integer_key = |k: &str| {
        let digits = k.strip_prefix('-').unwrap_or(k);
        k == "0"
            || (!digits.is_empty()
                && !digits.starts_with('0')
                && digits.bytes().all(|b| b.is_ascii_digit())
                && k.parse::<i64>().is_ok())
    };
    match filter {
        Value::Null | Value::Bool(_) => false,
        Value::Array(a) => !a.is_empty(),
        Value::Object(m) => m
            .iter()
            .any(|(k, v)| k.is_empty() || integer_key(k) || !v.is_boolean()),
        _ => true,
    }
}

/// `require --no-update` with every constraint given resolves nothing, but
/// `requireComposer()` (RequireCommand.php:193) still instantiates every
/// repository of the merged configuration: one its `RepositoryManager`
/// refuses — a type it does not register (`pear` included: removed in 2.x),
/// no type, no `url` where the class needs one, a `package` entry that is
/// not a package definition — stops Composer before the edit. The run is Composer's then. A test on the configuration in memory.
pub(crate) fn unregistered_repository_issue(
    manifest: &serde_json::Value,
) -> Option<vivacity_core::scope::ScopeIssue> {
    use serde_json::Value;
    let home = vivacity_core::fetch::composer_home();
    let issue = |why: String| Some(vivacity_core::scope::ScopeIssue::Layout(why));
    let config = match vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()) {
        Ok(c) => c,
        Err(e) => return issue(e.message),
    };
    for repo in &config.repositories {
        let def = &repo.definition;
        let named = match &repo.key {
            vivacity_resolver::session::RepoKey::Named(n) => n.clone(),
            vivacity_resolver::session::RepoKey::Indexed(i) => i.to_string(),
        };
        let Some(kind) = def.get("type").and_then(Value::as_str) else {
            return issue(format!("repository {named} has no type"));
        };
        match kind {
            // `package`: an object or a list of objects, each with a string
            // `name` and `version` (what the loader needs). Anything else
            // fails Composer's schema check or its loader: Composer's run
            // — a doubt hands over, the schema is not rewritten here.
            "package" => {
                let well_formed = |p: &Value| {
                    p.get("name").is_some_and(Value::is_string)
                        && p.get("version").is_some_and(Value::is_string)
                };
                let ok = match def.get("package") {
                    Some(p @ Value::Object(_)) => well_formed(p),
                    Some(Value::Array(list)) => {
                        !list.is_empty() && list.iter().all(|p| p.is_object() && well_formed(p))
                    }
                    _ => false,
                };
                if !ok {
                    return issue(format!(
                        "repository {named} of type \"package\" without a package definition vivacity can vouch for"
                    ));
                }
            }
            "composer" | "vcs" | "git" | "bitbucket" | "git-bitbucket" | "github" | "gitlab"
            | "svn" | "fossil" | "perforce" | "hg" | "artifact" | "path" => {
                if !def
                    .get("url")
                    .and_then(Value::as_str)
                    .is_some_and(|u| !u.is_empty())
                {
                    return issue(format!("repository {named} has no url"));
                }
            }
            other => {
                return issue(format!(
                    "repository {named} of type \"{other}\", which Composer does not register"
                ))
            }
        }
    }
    None
}

/// The first `composer` repository of the merged configuration (the global
/// config.json, then composer.json, `MergedConfig::load`) that `secure-http`
/// does not let through as is — refused, or judged on a setting vivacity
/// hands over — as a hand-over reason: its packages.json URL for a remote
/// one; for the local ones (`file://`), what their files name, read as the
/// pool would read them ([`vivacity_resolver::repository::local_insecure_url`]),
/// without a request. Over the common path (every repository `https`): a
/// string test each, on files the run has read already.
fn insecure_repository_issue(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    with_install: bool,
    with_dev: bool,
    plugins_enabled: bool,
    start: &PoolStart<'_>,
) -> Option<vivacity_core::scope::ScopeIssue> {
    use serde_json::Value;
    use vivacity_core::secure_http::{classify, insecure, Verdict};
    if start.no_resolution {
        return None;
    }
    let home = vivacity_core::fetch::composer_home();
    // An unreadable global config.json is the session's to report.
    let config = vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()).ok()?;
    let why = |v: Verdict| match v {
        Verdict::Refuse => Some("which secure-http refuses".to_owned()),
        Verdict::HandOver(reason) => Some(format!("with {reason}")),
        Verdict::Allowed | Verdict::Warn { .. } => None,
    };
    let mut local: Vec<String> = Vec::new();
    let mut local_filters: Vec<(String, Option<Value>)> = Vec::new();
    // What a resolution cannot open (`open_repository`), decided on the
    // merged configuration before anything is printed or edited: the run is
    // Composer's (the session would hand it over too, later).
    for repo in &config.repositories {
        let def = &repo.definition;
        let kind = def.get("type").and_then(Value::as_str);
        let named = match &repo.key {
            vivacity_resolver::session::RepoKey::Named(n) => n.clone(),
            vivacity_resolver::session::RepoKey::Indexed(i) => i.to_string(),
        };
        if !matches!(kind, Some("composer" | "path") | None) {
            return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                "repository {named} of type \"{}\" (not supported by vivacity at resolution)",
                kind.unwrap_or("")
            )));
        }
        if kind.is_some()
            && ["only", "exclude", "canonical"]
                .iter()
                .any(|k| def.get(*k).is_some())
        {
            return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                "repository {named} sets only/exclude/canonical (not supported by vivacity at resolution)"
            )));
        }
        if kind != Some("composer") {
            continue;
        }
        match def.get("url").and_then(Value::as_str) {
            None => {
                return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                    "repository {named} has no url"
                )))
            }
            // The common path first: an `https` URL needs nothing more.
            Some(url) if url.starts_with("https://") => {}
            Some(url) => {
                let canonical = vivacity_resolver::repository::repo_urls(url).url;
                if !["file://", "http://", "https://"]
                    .iter()
                    .any(|p| canonical.starts_with(p))
                {
                    return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                        "repository {named} has a url scheme vivacity does not read ({url})"
                    )));
                }
            }
        }
        // `allow_ssl_downgrade` (=== true): without a `metadata-url`,
        // Composer reads the rest of the repository over `http` once its
        // packages.json is in (ComposerRepository.php:190, :1552-1555) —
        // refused, or warned about; not reproduced.
        if def.get("allow_ssl_downgrade") == Some(&Value::Bool(true)) {
            return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                "repository {} sets allow_ssl_downgrade (not reproduced)",
                def.get("url").and_then(Value::as_str).unwrap_or("?")
            )));
        }
        let Some(url) = def.get("url").and_then(Value::as_str) else {
            continue;
        };
        // The common path: an `https` URL is not a path either.
        if url.starts_with("https://") {
            continue;
        }
        let urls = vivacity_resolver::repository::repo_urls(url);
        if insecure(&urls.packages_json_url).is_some() {
            if let Some(why) = why(classify(&urls.packages_json_url)) {
                return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
                    "repository {} is read over an insecure protocol, {why}",
                    vivacity_resolver::metacache::sanitize_url(&urls.url)
                )));
            }
            continue;
        }
        if urls.packages_json_url.starts_with("file://") {
            local.push(url.to_owned());
            local_filters.push((url.to_owned(), def.get("filter").cloned()));
        }
    }
    // A partial update fixes the locked packages outside its allow list:
    // one not installed as locked is downloaded from its locked dist,
    // which the lock holds — judged now (the lock in memory, or read for a
    // local repository's check anyway).
    let partial = !start.allow.is_empty() || !start.added.is_empty();
    let read_lock;
    let lock = match start.lock {
        Some(l) => Some(l),
        None if partial && with_install && !local.is_empty() => {
            read_lock = vivacity_core::jsonfile::read(&project.join("composer.lock"));
            read_lock.as_deref()
        }
        None => None,
    };
    if let (true, true, Some(lock)) = (with_install, partial, lock) {
        if let Some(reason) =
            fixed_insecure_reason(project, manifest, with_dev, plugins_enabled, start, lock)
        {
            return Some(vivacity_core::scope::ScopeIssue::Layout(reason));
        }
    }
    let fixed = lock
        .filter(|_| partial)
        .map(|l| fixed_packages(manifest, with_dev, start, l));
    if local.is_empty() {
        return None;
    }
    let policy = vivacity_resolver::policy_config::PolicyConfig::from_raw(&config.policy).ok();
    // What a local repository's packages.json declares that the session
    // would refuse once loading (the v1 protocol, a custom policy list it
    // advertises): read now, whatever `secure-http` says.
    let custom_lists = policy
        .as_ref()
        .map(|p| p.custom_lists.clone())
        .unwrap_or_default();
    if let Some(why) =
        vivacity_resolver::repository::local_unsupported(&local_filters, &custom_lists, true, false)
    {
        return Some(vivacity_core::scope::ScopeIssue::Layout(why));
    }
    // `policy.ignore-unreachable` off for the resolution's filters: their
    // refusal stops Composer (a policy vivacity cannot read: counted).
    let filters_fatal = policy
        .as_ref()
        .is_none_or(|p| !(p.ignore_unreachable.update && p.ignore_unreachable.install));
    let scope = pool_scope(
        manifest,
        with_install,
        with_dev,
        start,
        fixed,
        filters_fatal,
    );
    let (found, verdict) = vivacity_resolver::repository::local_insecure_url(&local, &scope)?;
    why(verdict).map(|why| {
        vivacity_core::scope::ScopeIssue::Layout(format!(
            "a local repository names {} (an insecure protocol), {why}",
            vivacity_resolver::metacache::sanitize_url(&found)
        ))
    })
}

/// The root's requirements as `PoolBuilder` starts from them (`require`,
/// `require-dev` in dev mode, `require`'s additions, not `remove`'s drops),
/// name and constraint.
fn root_requirements(
    manifest: &serde_json::Value,
    with_dev: bool,
    start: &PoolStart<'_>,
) -> Vec<(String, String)> {
    use serde_json::Value;
    let removed: Vec<String> = start.removed.iter().map(|n| n.to_lowercase()).collect();
    let sections: &[&str] = if with_dev {
        &["require", "require-dev"]
    } else {
        &["require"]
    };
    let mut root: Vec<(String, String)> = sections
        .iter()
        .filter_map(|k| manifest.get(*k).and_then(Value::as_object))
        .flatten()
        .filter_map(|(n, c)| Some((n.to_lowercase(), c.as_str()?.to_owned())))
        .filter(|(n, _)| !removed.contains(n))
        .collect();
    for (name, constraint) in &start.added {
        let name = name.to_lowercase();
        root.retain(|(n, _)| *n != name);
        root.push((name, constraint.clone()));
    }
    root
}

/// A partial update's fixed packages (in `lock`) not installed as locked
/// whose dist `secure-http` does not let through: the reason to hand over,
/// before anything — they are downloaded from the lock. A string test per
/// locked dist first (`any_insecure_dist`): nothing more is done without an
/// insecure URL.
pub(crate) fn fixed_insecure_reason(
    project: &std::path::Path,
    manifest: &serde_json::Value,
    with_dev: bool,
    plugins_enabled: bool,
    start: &PoolStart<'_>,
    lock: &serde_json::Value,
) -> Option<String> {
    use serde_json::Value;
    if !crate::install::any_insecure_dist(lock) {
        return None;
    }
    let fixed = fixed_packages(manifest, with_dev, start, lock);
    let sections = if with_dev {
        &["packages", "packages-dev"][..]
    } else {
        &["packages"][..]
    };
    let entries: Vec<Value> = sections
        .iter()
        .filter_map(|k| lock.get(*k).and_then(Value::as_array))
        .flatten()
        .filter(|p| {
            p.get("name")
                .and_then(Value::as_str)
                .is_some_and(|n| fixed.names.contains(&n.to_lowercase()))
        })
        .cloned()
        .collect();
    let subset = serde_json::json!({"packages": entries, "packages-dev": []});
    let parsed = vivacity_core::lock::Lock::from_value(&subset);
    crate::install::insecure_dist_reason(project, manifest, &parsed, true, plugins_enabled)
}

/// The locked packages a partial update fixes (PoolBuilder.php:215-245):
/// those outside the allow list — widened along the lock's `require`
/// links for the transitive modes, root requirements left out for `-w`
/// (Composer widens further as it loads new versions: the local check
/// unlocks those too) — and the names they replace; and the requirements
/// the fixed packages mark for loading.
struct Fixed {
    names: std::collections::BTreeSet<String>,
    requires: Vec<(String, String)>,
}

fn fixed_packages(
    manifest: &serde_json::Value,
    with_dev: bool,
    start: &PoolStart<'_>,
    lock: &serde_json::Value,
) -> Fixed {
    use serde_json::Value;
    use vivacity_resolver::pool::UpdateMode;
    let root = root_requirements(manifest, with_dev, start);
    let mut allow: Vec<String> = start.allow.iter().map(|n| n.to_lowercase()).collect();
    allow.extend(start.added.iter().map(|(n, _)| n.to_lowercase()));
    let locked: Vec<&Value> = ["packages", "packages-dev"]
        .iter()
        .filter_map(|k| lock.get(*k).and_then(Value::as_array))
        .flatten()
        .collect();
    let name_of = |p: &Value| {
        p.get("name")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_lowercase()
    };
    let patterns: Vec<_> = allow
        .iter()
        .map(|a| vivacity_resolver::pool::package_name_regexp(a))
        .collect();
    let mut allowed: std::collections::BTreeSet<String> = locked
        .iter()
        .map(|p| name_of(p))
        .filter(|n| {
            patterns
                .iter()
                .any(|re| re.is_match(n.as_bytes()).unwrap_or(false))
        })
        .collect();
    if let Some(mode) = start.mode.filter(|m| *m != UpdateMode::OnlyListed) {
        let root_names: Vec<&String> = root.iter().map(|(n, _)| n).collect();
        let mut pending: Vec<String> = allowed.iter().cloned().collect();
        while let Some(name) = pending.pop() {
            let Some(p) = locked.iter().find(|p| name_of(p) == name) else {
                continue;
            };
            for dep in p
                .get("require")
                .and_then(Value::as_object)
                .into_iter()
                .flatten()
                .map(|(d, _)| d.to_lowercase())
            {
                if mode == UpdateMode::ListedWithTransitiveDepsNoRootRequire
                    && root_names.contains(&&dep)
                {
                    continue;
                }
                if allowed.insert(dep.clone()) {
                    pending.push(dep);
                }
            }
        }
    }
    let mut names = std::collections::BTreeSet::new();
    let mut requires = Vec::new();
    for p in &locked {
        let name = name_of(p);
        if allowed.contains(&name) {
            continue;
        }
        names.insert(name);
        for (target, _) in p
            .get("replace")
            .and_then(Value::as_object)
            .into_iter()
            .flatten()
        {
            names.insert(target.to_lowercase());
        }
        for (dep, c) in p
            .get("require")
            .and_then(Value::as_object)
            .into_iter()
            .flatten()
        {
            if let Some(c) = c.as_str() {
                requires.push((dep.to_lowercase(), c.to_owned()));
            }
        }
    }
    Fixed { names, requires }
}

/// `PoolBuilder::buildPool`'s start (PoolBuilder.php:215-290) for the local
/// check: the root's requirements and the fixed packages' requirements,
/// minus what is fixed; the stabilities and aliases the root sets.
fn pool_scope(
    manifest: &serde_json::Value,
    with_install: bool,
    with_dev: bool,
    start: &PoolStart<'_>,
    fixed: Option<Fixed>,
    filters_fatal: bool,
) -> vivacity_resolver::repository::LocalScope {
    use serde_json::Value;
    use vivacity_resolver::pool::UpdateMode;
    let root = root_requirements(manifest, with_dev, start);
    // `extractStabilityFlags`: an explicit `@stability`, or a constraint
    // that names an unstable version (`dev-main`, `1.0.x-dev`, the left
    // side of an alias).
    let flagged = root
        .iter()
        .filter(|(_, c)| {
            c.contains('@')
                || c.split("||").flat_map(|a| a.split('|')).any(|alt| {
                    let left = alt.split(" as ").next().unwrap_or(alt).trim();
                    vivacity_resolver::version::parse_stability(left) != "stable"
                })
        })
        .map(|(n, _)| n.clone())
        .collect();
    // `extractAliases`: `<version> as <alias>`.
    let root_aliases = root
        .iter()
        .filter_map(|(n, c)| {
            let (from, to) = c.split_once(" as ")?;
            let norm = |v: &str| {
                vivacity_resolver::version::normalize(v.trim().trim_start_matches(['=', ' ']), None)
                    .ok()
            };
            Some((n.clone(), norm(from)?, norm(to)?))
        })
        .collect();
    let minimum_stability = match manifest
        .get("minimum-stability")
        .and_then(Value::as_str)
        .map(str::to_lowercase)
        .as_deref()
    {
        Some("rc") => "RC".to_owned(),
        Some(s @ ("dev" | "alpha" | "beta")) => s.to_owned(),
        _ => "stable".to_owned(),
    };
    let root_names = root.iter().map(|(n, _)| n.clone()).collect();
    let (skipped, mut requires) = match fixed {
        Some(f) => (f.names, f.requires),
        None => (std::collections::BTreeSet::new(), Vec::new()),
    };
    requires.extend(root);
    requires.retain(|(n, _)| !skipped.contains(n));
    let unlock = match start.mode {
        Some(UpdateMode::ListedWithTransitiveDeps) => Some(false),
        Some(UpdateMode::ListedWithTransitiveDepsNoRootRequire) => Some(true),
        _ => None,
    };
    vivacity_resolver::repository::LocalScope {
        requires,
        skipped,
        minimum_stability,
        flagged,
        root_aliases,
        unlock,
        root_names,
        with_dists: with_install,
        filters_fatal,
    }
}

/// composer.json written by `require`/`remove` and put back before a
/// hand-over ([`manifest_restored`]): the `--no-fallback` reason says so.
/// 0: nothing; 1: put back; 2: created by `require`, then removed.
static MANIFEST_RESTORED: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);

/// `require`/`remove` put composer.json back (it had been written), or
/// removed the one `require` created: the reason of a run that stops says
/// so rather than « nothing was written ».
pub(crate) fn manifest_restored(created: bool) {
    MANIFEST_RESTORED.store(
        if created { 2 } else { 1 },
        std::sync::atomic::Ordering::Relaxed,
    );
}

/// A new run starts with nothing put back.
pub(crate) fn forget_manifest_restored() {
    MANIFEST_RESTORED.store(0, std::sync::atomic::Ordering::Relaxed);
}

/// Prints the reasons, then re-runs the command under Composer (or stops
/// with exit 3 under `--no-fallback`): the command line as it was given,
/// through [`forwarded_arguments`] — `--no-scripts` added, vivacity never
/// runs scripts, so Composer does not either — and [`hand_over`]. The
/// command is the one the line names: the hand-over that follows a
/// resolution (`hand_resolution_over`) runs inside `update`, `require` or
/// `remove` alike.
pub(crate) fn delegate_resolution(
    issues: &[vivacity_core::scope::ScopeIssue],
    no_fallback: bool,
) -> anyhow::Result<i32> {
    let tokens = command_line();
    let command = command_of(&tokens);
    // The reasons are vivacity's own narrative: at the default level when
    // Composer takes over (it prints its own run; under `-q` nothing), at
    // QUIET when the run stops here, so that an exit 3 is never mute.
    let composer = which_composer();
    let stops = no_fallback || composer.is_none();
    // Output held for a hand-over that might come: it came, nothing of it
    // is written (Composer writes its own, or the run stops on the reason).
    vivacity_core::io::drop_output();
    if stops {
        // The run ends here: what it kept under -v is its output.
        vivacity_core::io::release_deferred();
    } else {
        // Composer writes what vivacity held (the root-version warning), and
        // what it kept under -v.
        vivacity_core::io::drop_held();
        vivacity_core::io::drop_deferred();
    }
    let reason_line = |line: &str| {
        if stops {
            vivacity_core::say_always!("{line}");
        } else {
            vivacity_core::say!("{line}");
        }
    };
    reason_line(&format!(
        "vivacity: `{}` on this project is outside what vivacity handles natively:",
        canonical_command(&command)
    ));
    for issue in issues {
        reason_line(&format!("  - {issue}"));
    }
    if no_fallback {
        // What the run wrote to the project: nothing, or composer.json when
        // `require`/`remove` edited it on disk (no hold) and put it back for
        // this hand-over. Outside it, a hand-over decided once repositories
        // were loaded leaves their cache (Composer's own) and vivacity's
        // store probe.
        let restored = MANIFEST_RESTORED.swap(0, std::sync::atomic::Ordering::Relaxed);
        if restored == 1 {
            vivacity_core::say_always!("--no-fallback given: stopping here (composer.json was edited, then put back as it was; nothing else was written to the project).");
        } else if restored == 2 {
            vivacity_core::say_always!("--no-fallback given: stopping here (composer.json was created, then removed; nothing else was written to the project).");
        } else {
            vivacity_core::say_always!(
                "--no-fallback given: stopping here (nothing was written to the project)."
            );
        }
        return Ok(3);
    }
    let Some(composer) = composer else {
        vivacity_core::say_always!(
            "composer not found for the fallback — install Composer or run with --no-plugins."
        );
        return Ok(3);
    };
    let forwarded = forwarded_arguments(&tokens, &command);
    hand_over(
        &composer,
        &forwarded,
        has_option(&tokens, "--offline"),
        None,
    )
    .context("cannot run composer")
}

/// The command line `run` was given, after the program name.
pub(crate) fn command_line() -> Vec<std::ffi::OsString> {
    let argv = ARGV.lock().map(|a| a.clone()).unwrap_or_default();
    argv.into_iter().skip(1).collect()
}

/// The command a line names: its first word that is not an option (clap
/// takes the subcommand first). An alias stays an alias.
fn command_of(tokens: &[std::ffi::OsString]) -> String {
    tokens
        .iter()
        .map(|t| t.to_string_lossy())
        .find(|t| !t.starts_with('-'))
        .unwrap_or_default()
        .into_owned()
}

/// The command's own name for an alias (clap's `r`, `rm`, `upgrade`).
fn canonical_command(command: &str) -> &str {
    match command {
        "r" => "require",
        "rm" => "remove",
        "upgrade" => "update",
        other => other,
    }
}

/// `flag` among the options, before any `--` (after it, a word is an
/// argument, whatever it looks like).
fn has_option(tokens: &[std::ffi::OsString], flag: &str) -> bool {
    tokens.iter().take_while(|t| *t != "--").any(|t| t == flag)
}

/// Runs Composer with `args`, as a child process in vivacity's own
/// directory — never `exec`, which would replace the process of a program
/// that embeds `vivacity::run` (ePHPm) — and returns its exit code. While
/// it runs, SIGINT/SIGTERM/SIGHUP sent to vivacity are passed on to it; a
/// signal that ended it ends the binary by the same signal (`128 + n` for
/// the library) — as Composer run directly ends. The directory does not change so that a relative
/// `--working-dir` on the line means for Composer what it meant for
/// vivacity: Composer applies it itself (`Application::doRun`, `chdir`).
/// The child gets the run's verbosity ([`with_verbosity`]), and
/// `COMPOSER_DISABLE_NETWORK=1` for `--offline`, which Composer does not
/// have. The `delegating to` line shows the whole line handed over.
pub(crate) fn hand_over(
    composer: &std::path::Path,
    args: &[std::ffi::OsString],
    offline: bool,
    reason: Option<&str>,
) -> std::io::Result<i32> {
    // The Composer started here handles its own signals (`require`'s revert
    // included): vivacity's handlers go first.
    vivacity_core::signals::release();
    // The Composer started here writes its own root-version warning: what
    // vivacity still holds is dropped, not written twice.
    vivacity_core::io::drop_held();
    vivacity_core::io::drop_output();
    // The archives this run put in Composer's files cache (an install, Flex
    // reading dists) would spare Composer their `  - Downloading` lines:
    // taken back first; one that cannot be stops the run here.
    if let Err(why) = vivacity_core::fetch::take_back_cached_dists() {
        vivacity_core::say_always!("Error: {why}");
        return Ok(1);
    }
    let line = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect::<Vec<_>>()
        .join(" ");
    match reason {
        Some(reason) => {
            vivacity_core::say!("vivacity: delegating to `composer {line}` ({reason})…")
        }
        None => vivacity_core::say!("vivacity: delegating to `composer {line}`…"),
    }
    let mut cmd = std::process::Command::new(composer);
    cmd.args(args);
    with_verbosity(&mut cmd);
    if offline {
        cmd.env("COMPOSER_DISABLE_NETWORK", "1");
    }
    // Signals sent to vivacity alone reach the Composer that runs the
    // command; a signal that ended it ends vivacity the same way
    // (`signals::exit_code_of`).
    let status = vivacity_core::signals::spawn_forwarding(&mut cmd)?;
    Ok(vivacity_core::signals::exit_code_of(status))
}

/// The arguments a command hands to Composer: the command line after the
/// program name, without vivacity's own options — `--no-fallback`,
/// `--check-scope`, `--offline` (the caller sets `COMPOSER_DISABLE_NETWORK`),
/// `--run-scripts`, and `--no-autoloader` on `require`/`remove`, where
/// Composer has no such option — and with `--no-scripts` unless
/// `--run-scripts` asked Composer to run them: vivacity's contract holds
/// through the fallback. Everything after `--` is left as it is, and
/// `--no-scripts` goes before it. `command` is the word of the line, alias
/// included (`r`, `rm`).
pub(crate) fn forwarded_arguments(
    tokens: &[std::ffi::OsString],
    command: &str,
) -> Vec<std::ffi::OsString> {
    let has = |flag: &str| has_option(tokens, flag);
    let mut dropped = vec![
        "--no-fallback",
        "--check-scope",
        "--offline",
        "--run-scripts",
    ];
    if matches!(canonical_command(command), "require" | "remove") {
        dropped.push("--no-autoloader");
    }
    let mut before_dashes = true;
    let mut forwarded: Vec<std::ffi::OsString> = Vec::new();
    for t in tokens {
        if t == "--" {
            before_dashes = false;
        }
        if before_dashes && dropped.iter().any(|f| t == f) {
            continue;
        }
        forwarded.push(t.clone());
    }
    if !has("--run-scripts") && !has("--no-scripts") {
        let at = forwarded
            .iter()
            .position(|t| t == "--")
            .unwrap_or(forwarded.len());
        forwarded.insert(at, "--no-scripts".into());
    }
    forwarded
}

/// The run's verbosity for a Composer child process, the way Symfony
/// Console carries it (`Application::configureIO` exports
/// `SHELL_VERBOSITY`): `-1` quiet, `0` normal, `1` verbose. An explicit
/// `-q`/`-v` on the forwarded line still wins, as in Composer.
pub(crate) fn with_verbosity(cmd: &mut std::process::Command) {
    let level = match vivacity_core::io::level() {
        vivacity_core::io::Verbosity::Quiet => "-1",
        vivacity_core::io::Verbosity::Normal => "0",
        vivacity_core::io::Verbosity::Verbose => "1",
    };
    cmd.env("SHELL_VERBOSITY", level);
}

/// The `install` fallback: the reasons, then the command handed to Composer
/// before anything is written under vendor/ (or exit 3 under `--no-fallback`
/// / `--check-scope`). An `install` hands over its own command line through
/// [`forwarded_arguments`] — every option it was given, `--dry-run`
/// included; the install phase of `update`/`require`/`remove`, whose line is
/// not an install's, hands over the line [`after_update_line`] built
/// (`args.fallback_line`). Either way a child process ([`hand_over`]).
pub(crate) fn fallback_or_fail(
    args: &InstallArgs,
    scope: &vivacity_core::scope::ScopeReport,
) -> anyhow::Result<i32> {
    let composer = which_composer();
    let stops = args.no_fallback || args.check_scope || composer.is_none();
    vivacity_core::io::drop_output();
    if !stops {
        // Composer writes what vivacity held (the root-version warning).
        vivacity_core::io::drop_held();
    }
    let reason_line = |line: &str| {
        if stops {
            vivacity_core::say_always!("{line}");
        } else {
            vivacity_core::say!("{line}");
        }
    };
    reason_line("vivacity: this lock is outside what vivacity handles natively:");
    for issue in &scope.issues {
        reason_line(&format!("  - {issue}"));
    }
    if args.no_fallback || args.check_scope {
        vivacity_core::say_always!(
            "--no-fallback given: stopping here (no partial vendor/ was written)."
        );
        return Ok(3);
    }
    let Some(composer) = composer else {
        vivacity_core::say_always!(
            "composer not found for the fallback — install Composer or remove the unsupported items."
        );
        return Ok(3);
    };
    let forwarded = match &args.fallback_line {
        Some(line) => line.clone(),
        None => forwarded_arguments(&command_line(), "install"),
    };
    let code =
        hand_over(&composer, &forwarded, args.offline, None).context("cannot run composer")?;
    // The install phase of an `update` whose Flex recipes vivacity had
    // decided to apply: Composer's `install` runs Flex at
    // `POST_INSTALL_CMD`, which applies no recipe (`fetchRecipes` is
    // `POST_UPDATE_CMD` only). The lock is written already, so the
    // recipes are applied here, after it, as the update would have.
    if code == 0 {
        if let Some(plan) = args
            .post_update
            .as_ref()
            .and_then(|u| u.flex_plan.as_deref())
        {
            plan.print_and_apply()?;
        }
    }
    Ok(code)
}

/// The `composer install` line of the install phase that follows a
/// resolution (`Installer::run` with `setInstall(true)` after `doUpdate`),
/// should that phase go to Composer. Not the command line itself: by then
/// composer.lock is written and, for `require`/`remove`, composer.json is
/// edited — re-running `update` would resolve a second time, `remove` would
/// find its package already gone. Composer goes on with `doInstall` on the
/// lock it just solved; `composer install` reads that same lock. Every
/// option of the update that the install phase reads is carried, under
/// `install`'s own name (`--update-no-dev` arrives here as `no_dev`;
/// `require`'s `--prefer-*` in the internal fields of the same name).
/// Not carried: the audit — `install --audit` also sets `setErrorOnAudit`
/// (exit 5 on an advisory) where `update` audits without failing, and
/// vivacity does not audit natively either. `--no-scripts` always: none of
/// the three runs scripts in vivacity. `--dry-run` reaches a fallback only
/// through composer-merge-plugin when it is locked but not installed (the
/// install merges, the resolution did not); Composer then lists from the
/// lock on disk, not the dry run's unwritten one — but writes nothing.
pub(crate) fn after_update_line(args: &UpdateArgs) -> Vec<std::ffi::OsString> {
    let mut line: Vec<std::ffi::OsString> = vec!["install".into()];
    for (on, flag) in [
        (args.dry_run, "--dry-run"),
        (args.prefer_source, "--prefer-source"),
        (args.prefer_dist, "--prefer-dist"),
        (args.no_dev, "--no-dev"),
        (args.no_progress, "--no-progress"),
        (args.no_autoloader, "--no-autoloader"),
        (args.optimize_autoloader, "--optimize-autoloader"),
        (args.classmap_authoritative, "--classmap-authoritative"),
        (args.apcu_autoloader, "--apcu-autoloader"),
        (args.ignore_platform_reqs, "--ignore-platform-reqs"),
        (args.no_plugins, "--no-plugins"),
        (args.no_blocking, "--no-blocking"),
        (args.no_security_blocking, "--no-security-blocking"),
        (args.compat.no_interaction, "--no-interaction"),
        (args.compat.no_ansi, "--no-ansi"),
    ] {
        if on {
            line.push(flag.into());
        }
    }
    // `--name=value`, one word: Symfony would not take a separate value
    // that starts with `-` for the option's.
    let valued = |name: &str, value: &std::ffi::OsStr| {
        let mut word = std::ffi::OsString::from(format!("--{name}="));
        word.push(value);
        word
    };
    if let Some(how) = &args.prefer_install {
        line.push(valued("prefer-install", how.as_ref()));
    }
    if let Some(prefix) = &args.apcu_autoloader_prefix {
        line.push(valued("apcu-autoloader-prefix", prefix.as_ref()));
    }
    for req in &args.ignore_platform_req {
        line.push(valued("ignore-platform-req", req.as_ref()));
    }
    if let Some(dir) = &args.working_dir {
        line.push(valued("working-dir", dir.as_os_str()));
    }
    line.push("--no-scripts".into());
    line
}

/// Why `-v` on this project goes to Composer, if it does. Under `-v`,
/// Composer writes a line per plugin listener it dispatches
/// (`EventDispatcher.php:230`: `> post-autoload-dump: Class->method`), and
/// some plugins log on top of it (dealerdirect's `Plugin.php`, Flex's
/// configurators, composer-merge-plugin's `Logger.php:68`). vivacity prints
/// those lines for the plugins of `verbose_listeners::VERBOSE_PLUGINS`, in
/// the versions read; any other plugin Composer would load — installed
/// (project or `COMPOSER_HOME`) or locked, and allowed — hands the run
/// over, named (docs/plans/verbose-plugins.md). `None` under
/// `--no-plugins`, or without a readable composer.json (the command
/// reports that itself).
pub(crate) fn active_plugin(
    project: &std::path::Path,
    plugins_enabled: bool,
    run_scripts: bool,
) -> Option<String> {
    crate::verbose_listeners::issue(
        project,
        crate::plugin_order::global_composer_dir().as_deref(),
        plugins_enabled,
        run_scripts,
    )
}

/// The whole command handed to Composer before anything is read or written
/// — its verbosity, or a root version only Composer can guess: `tokens` is
/// the command line after the program name, forwarded through
/// [`forwarded_arguments`] and [`hand_over`]. `--no-fallback` stops with
/// exit 3 instead (and `--check-scope`, for the reasons it reports).
/// `remedy` completes "install Composer or …" when there is none.
pub(crate) fn delegate_for_verbosity(
    tokens: &[std::ffi::OsString],
    reason: &str,
    remedy: &str,
) -> i32 {
    let command = command_of(tokens);
    let stop = if has_option(tokens, "--no-fallback") {
        Some("--no-fallback")
    } else if has_option(tokens, "--check-scope") {
        Some("--check-scope")
    } else {
        None
    };
    if let Some(option) = stop {
        vivacity_core::say_always!(
            "vivacity: `{command}` with {reason} is outside what vivacity reproduces."
        );
        vivacity_core::say_always!("{option} given: stopping here (nothing was written).");
        return 3;
    }
    let Some(composer) = which_composer() else {
        vivacity_core::say_always!(
            "composer not found for the fallback — install Composer or {remedy}."
        );
        return 3;
    };
    let forwarded = forwarded_arguments(tokens, &command);
    match hand_over(
        &composer,
        &forwarded,
        has_option(tokens, "--offline"),
        Some(reason),
    ) {
        Ok(code) => code,
        Err(e) => {
            vivacity_core::say_always!("Error: cannot run composer: {e}");
            1
        }
    }
}

pub(crate) fn which_composer() -> Option<PathBuf> {
    let path = std::env::var_os("PATH")?;
    // On Windows, composer installs itself as composer.bat/.cmd (a wrapper
    // around the .phar); `Command` can launch a .bat (via cmd.exe).
    let names: &[&str] = if cfg!(windows) {
        &["composer.bat", "composer.cmd", "composer.exe", "composer"]
    } else {
        &["composer"]
    };
    std::env::split_paths(&path)
        .flat_map(|d| names.iter().map(move |n| d.join(n)))
        .find(|c| c.is_file())
}

#[cfg(test)]
mod tests {
    #[test]
    fn composer_urls_the_constructor_refuses() {
        let refused = |u: &str| composer_url_refused(None, u);
        // `php -r 'var_dump(parse_url(...))'` gives `false` for these.
        assert!(refused("https:///x"));
        assert!(refused("https://repo.test:99999"));
        assert!(refused("https://repo.test:65536"));
        assert!(refused("https://repo.test:000443"));
        assert!(refused("https://repo.test:123456"));
        assert!(refused("https://repo.test:-1"));
        assert!(refused("https://repo.test:+"));
        assert!(refused("https://user@/x"));
        assert!(refused("http://:80/x"));
        assert!(refused("http://[::1]:x"));
        // … and an array for these.
        assert!(!refused("https://repo.test:80a"));
        assert!(!refused("https://repo.test:+80"));
        assert!(!refused("https://repo.test: 80"));
        assert!(!refused("https://repo.test:  8"));
        assert!(!refused("https://repo.test:8a/x"));
        assert!(!refused("https://repo.test:0"));
        assert!(!refused("https://repo.test:"));
        assert!(!refused("http://[::1"));
        assert!(!refused("http://[::1]x"));
        assert!(!refused("http://[::1]:80"));
        assert!(!refused("http://[::1]"));
        assert!(!refused("http://[::1]:x:80"));
        assert!(refused("http://[::1]:80:x"));
        assert!(!refused("https://repo.test:8443/"));
        assert!(!refused("https://repo.test"));
        assert!(!refused("https://[::1]:8080/x"));
        assert!(!refused("file:///tmp/x"));
        assert!(!refused("repo.test/x"));
        assert!(!refused("https?://repo.test"));
    }

    #[test]
    fn user_filters_the_constructor_refuses() {
        use serde_json::json;
        assert!(!user_filter_refused(&json!(false)));
        assert!(!user_filter_refused(&json!(null)));
        assert!(!user_filter_refused(&json!([])));
        assert!(!user_filter_refused(&json!({"malware": false, "-0": true})));
        assert!(user_filter_refused(&json!({"0": false})));
        assert!(user_filter_refused(&json!({"12": true})));
        assert!(user_filter_refused(&json!({"x": "no"})));
        assert!(user_filter_refused(&json!(["x"])));
        assert!(user_filter_refused(&json!("x")));
    }

    use super::*;

    fn forward(tokens: &[&str], command: &str) -> Vec<String> {
        let tokens: Vec<std::ffi::OsString> = tokens.iter().map(Into::into).collect();
        forwarded_arguments(&tokens, command)
            .iter()
            .map(|t| t.to_string_lossy().into_owned())
            .collect()
    }

    #[test]
    fn vivacity_options_are_dropped_and_no_scripts_added_last() {
        for flag in ["--no-fallback", "--check-scope", "--offline"] {
            assert_eq!(
                forward(&["install", flag, "-o", "--working-dir", "p"], "install"),
                ["install", "-o", "--working-dir", "p", "--no-scripts"],
                "{flag}"
            );
        }
        // Composer's own options go through as they were written.
        assert_eq!(
            forward(
                &[
                    "install",
                    "--dry-run",
                    "--prefer-install=source",
                    "-q",
                    "--working-dir=p"
                ],
                "install"
            ),
            [
                "install",
                "--dry-run",
                "--prefer-install=source",
                "-q",
                "--working-dir=p",
                "--no-scripts"
            ]
        );
    }

    #[test]
    fn run_scripts_hands_the_scripts_to_composer() {
        assert_eq!(
            forward(&["install", "--run-scripts"], "install"),
            ["install"]
        );
        // Both asked: vivacity reads `--no-scripts` as winning, so does Composer.
        assert_eq!(
            forward(&["install", "--run-scripts", "--no-scripts"], "install"),
            ["install", "--no-scripts"]
        );
        // Already there: not doubled.
        assert_eq!(
            forward(&["update", "--no-scripts", "-n"], "update"),
            ["update", "--no-scripts", "-n"]
        );
    }

    #[test]
    fn nothing_after_double_dash_is_touched() {
        assert_eq!(
            forward(
                &["require", "--offline", "--", "--no-fallback", "--offline"],
                "require"
            ),
            [
                "require",
                "--no-scripts",
                "--",
                "--no-fallback",
                "--offline"
            ]
        );
        // After `--` these are arguments, not options: scripts stay off.
        assert_eq!(
            forward(
                &["require", "--", "--run-scripts", "--no-scripts"],
                "require"
            ),
            [
                "require",
                "--no-scripts",
                "--",
                "--run-scripts",
                "--no-scripts"
            ]
        );
    }

    #[test]
    fn no_autoloader_is_dropped_only_where_composer_lacks_it() {
        for command in ["require", "r", "remove", "rm"] {
            assert_eq!(
                forward(&[command, "a/b", "--no-autoloader"], command),
                [command, "a/b", "--no-scripts"],
                "{command}"
            );
        }
        for command in ["install", "update"] {
            assert_eq!(
                forward(&[command, "--no-autoloader"], command),
                [command, "--no-autoloader", "--no-scripts"],
                "{command}"
            );
        }
    }

    #[test]
    fn the_command_is_the_first_word_and_options_stop_at_double_dash() {
        let tokens: Vec<std::ffi::OsString> = ["rm", "a/b", "--", "--offline"]
            .iter()
            .map(Into::into)
            .collect();
        assert_eq!(command_of(&tokens), "rm");
        assert!(!has_option(&tokens, "--offline"));
        assert!(has_option(&tokens[..2], "a/b"));
    }

    fn update_args(argv: &[&str]) -> UpdateArgs {
        let argv = std::iter::once("vivacity").chain(argv.iter().copied());
        match Cli::try_parse_from(argv).expect("parses") {
            Cli::Update(args) => args,
            other => panic!("not an update: {other:?}"),
        }
    }

    fn line(args: &UpdateArgs) -> Vec<String> {
        after_update_line(args)
            .iter()
            .map(|t| t.to_string_lossy().into_owned())
            .collect()
    }

    #[test]
    fn the_install_phase_line_carries_what_the_install_reads() {
        assert_eq!(line(&update_args(&["update"])), ["install", "--no-scripts"]);
        // `require`'s preference, carried in the internal fields.
        let mut args = update_args(&["update"]);
        args.prefer_source = true;
        args.prefer_install = Some("auto".to_owned());
        assert_eq!(
            line(&args),
            [
                "install",
                "--prefer-source",
                "--prefer-install=auto",
                "--no-scripts"
            ]
        );
        let args = update_args(&[
            "update",
            "a/b",
            "--with",
            "c/d:1.0",
            "-W",
            "--prefer-stable",
            "--no-audit",
            "--offline",
            "--no-fallback",
            "-v",
            "--working-dir",
            "proj",
            "--no-dev",
            "-oa",
            "--apcu-autoloader",
            "--apcu-autoloader-prefix=pfx",
            "--no-progress",
            "--no-autoloader",
            "--ignore-platform-reqs",
            "--ignore-platform-req=ext-a",
            "--ignore-platform-req",
            "ext-b",
            "--no-plugins",
            "-n",
            "--no-ansi",
            "--no-blocking",
            "--no-security-blocking",
            "--dry-run",
        ]);
        // The resolution's own options (packages, `--with`, `-W`,
        // `--prefer-stable`), the audit and vivacity's options stay behind;
        // the verbosity travels as `SHELL_VERBOSITY`, `--offline` as
        // `COMPOSER_DISABLE_NETWORK`.
        assert_eq!(
            line(&args),
            [
                "install",
                "--dry-run",
                "--no-dev",
                "--no-progress",
                "--no-autoloader",
                "--optimize-autoloader",
                "--classmap-authoritative",
                "--apcu-autoloader",
                "--ignore-platform-reqs",
                "--no-plugins",
                "--no-blocking",
                "--no-security-blocking",
                "--no-interaction",
                "--no-ansi",
                "--apcu-autoloader-prefix=pfx",
                "--ignore-platform-req=ext-a",
                "--ignore-platform-req=ext-b",
                "--working-dir=proj",
                "--no-scripts",
            ]
        );
    }
}