composer-install 0.6.1

Install a resolved composer.lock into a project: download + verify + extract dists in parallel, materialize path packages, apply patches, run the declarative install plugins, dump the autoloader, and link vendor/bin — without running PHP. The pubgrub solver is out of scope; this is the install-from-lock half.
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
//! `install_from_lock` — apply a resolved `composer.lock` to a project.
//!
//! Reads `composer.json` + `composer.lock`, verifies the content-hash, diffs
//! against the existing `vendor/composer/installed.json` to skip packages that
//! are already up-to-date, runs preflight (rejecting source-only and non-zip
//! dists which can't be installed at all; surfacing plugins / post-install
//! scripts as warnings since the package zips are installed but their PHP is
//! never run), builds [`DistRequest`]s only for changed/new packages, removes
//! stale packages, downloads + extracts into `vendor/` via a [`Fetcher`],
//! materializes `type: path` packages, applies patches, runs the declarative
//! install plugins (Magento deploy, Laravel discovery), hands off to
//! [`composer_autoload::dump_autoload`] for `vendor/autoload.php` +
//! `installed.{json,php}`, and links `vendor/bin` proxies.
//!
//! Preflight failures are aggregated into a single error so the caller sees
//! every blocker in one pass rather than fix-one-hit-next. Preflight warnings
//! are returned alongside on success via [`InstallSummary::warnings`].
//!
//! The three app-specific seams are injected via [`InstallEnv`]: the network
//! ([`Fetcher`]), the dist cache location (`cache_root`), and progress
//! reporting ([`Progress`]). Root-script execution is opted in with
//! [`ScriptHooks`]; pass `None` for the deterministic scripts-off behavior.

use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use composer_autoload::{DumpRequest, dump_autoload};
use composer_manifest::lockfile::{self, Lock, LockPackage};
use composer_patches::{ApplyOptions, FailureMode, MaterializedPatch, PatchPlan, apply_patch_text};
use eyre::{Context, Result, eyre};
use serde_json::Value;

use crate::archive::ArchiveKind;
use crate::auth::{AuthCredentials, read_all_auth_with};
use crate::downloader::{DistCandidate, DistOutcome, DistRequest, fetch_and_extract_dists};
use crate::error::InstallError;
use crate::fetch::Fetcher;
use crate::progress::Progress;
use crate::source::{SourceFetcher, SourceSpec, materialize_sources};
use crate::stale::{InstallRecord, remove_stale_packages};

/// The runtime seams an install needs, injected so the crate stays free of any
/// HTTP-client / progress-bar / paths policy. Build it with
/// [`InstallEnv::new`] plus the `with_*` methods, and pass it by reference to
/// [`install_from_lock`].
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct InstallEnv<'a> {
    /// Downloads each dist URL to a verified cache file. Use
    /// [`crate::ReqwestFetcher`] for the batteries-included default.
    pub fetcher: &'a dyn Fetcher,
    /// Per-package progress callbacks. Use [`crate::NoProgress`] for silence.
    pub progress: &'a dyn Progress,
    /// Directory the dist archives are cached under (persistent across runs;
    /// created if absent). Composer keeps the equivalent in
    /// `~/.composer/cache/files/`.
    pub cache_root: &'a Path,
    /// Installs packages the lock pins to a git `source` with no dist. `None`
    /// (the default) makes such packages a preflight error.
    pub source_fetcher: Option<&'a dyn SourceFetcher>,
    /// Machine-wide credentials from the caller's own store (a CLI's login
    /// command, say), merged above the global `auth.json` and below the
    /// project's sources: composer.json `config`, project `auth.json` and
    /// `COMPOSER_AUTH` still win.
    pub machine_auth: Option<&'a HashMap<String, AuthCredentials>>,
    /// File name, under `vendor/composer/`, of the autoloader freshness
    /// marker. Defaults to `.composer-install-autoload-fresh`.
    pub autoload_marker: &'a str,
    /// How warnings and preflight blockers name the calling tool and its
    /// commands. Defaults to tool-neutral text; see [`Wording`].
    pub wording: Wording<'a>,
}

/// The words messages use for the calling tool, so a CLI built on this crate
/// can point its users at its own commands. Start from
/// [`Wording::default`] and set the fields that differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Wording<'a> {
    /// The tool, as the subject of a sentence: "… that `tool` does not
    /// relocate". Defaults to `this installer`.
    pub tool: &'a str,
    /// The command that regenerates `composer.lock`. Defaults to
    /// `composer update`.
    pub update_command: &'a str,
    /// The command that installs what this crate cannot (plugin hooks,
    /// non-git sources, other dist types). Defaults to `composer install`.
    pub install_command: &'a str,
    /// A sentence telling the user how to have root scripts run. Defaults to
    /// naming [`ScriptHooks`], the library seam.
    pub scripts_hint: &'a str,
}

impl Default for Wording<'_> {
    fn default() -> Self {
        Self {
            tool: "this installer",
            update_command: "composer update",
            install_command: "composer install",
            scripts_hint: "Supply a `ScriptHooks` implementation to run them.",
        }
    }
}

impl<'a> InstallEnv<'a> {
    /// The required seams: a dist fetcher, a progress sink, and the dist cache
    /// directory. Source installs are off until
    /// [`with_source_fetcher`](Self::with_source_fetcher).
    pub fn new(fetcher: &'a dyn Fetcher, progress: &'a dyn Progress, cache_root: &'a Path) -> Self {
        Self {
            fetcher,
            progress,
            cache_root,
            source_fetcher: None,
            machine_auth: None,
            autoload_marker: AUTOLOAD_FRESH_MARKER,
            wording: Wording::default(),
        }
    }

    /// Name the calling tool and its commands in warnings and preflight
    /// blockers; see [`Wording`].
    #[must_use]
    pub fn with_wording(mut self, wording: Wording<'a>) -> Self {
        self.wording = wording;
        self
    }

    /// Add machine-wide credentials from the caller's own store; see
    /// [`machine_auth`](Self::machine_auth) for the precedence.
    #[must_use]
    pub fn with_machine_auth(mut self, auth: &'a HashMap<String, AuthCredentials>) -> Self {
        self.machine_auth = Some(auth);
        self
    }

    /// Use another file name for the autoloader freshness marker, so a tool
    /// that already writes its own keeps its warm state.
    #[must_use]
    pub fn with_autoload_marker(mut self, name: &'a str) -> Self {
        self.autoload_marker = name;
        self
    }

    /// Install git-source packages with `source_fetcher` — typically a
    /// [`crate::GitSourceFetcher`].
    #[must_use]
    pub fn with_source_fetcher(mut self, source_fetcher: &'a dyn SourceFetcher) -> Self {
        self.source_fetcher = Some(source_fetcher);
        self
    }
}

impl std::fmt::Debug for InstallEnv<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InstallEnv")
            .field("cache_root", &self.cache_root)
            .field("source_fetcher", &self.source_fetcher.is_some())
            .field("machine_auth", &self.machine_auth.map(HashMap::len))
            .field("autoload_marker", &self.autoload_marker)
            .field("wording", &self.wording)
            .finish_non_exhaustive()
    }
}

/// How a dist's files are materialized into `vendor/`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LinkMode {
    /// Decompress each cached `<key>.zip` straight into `vendor/` on every
    /// install (the portable default; independent trees, safe to mutate).
    #[default]
    Extract,
    /// Decompress each dist ONCE into a persistent extracted store next to the
    /// zip cache, then **hard-link** the store tree into `vendor/`. Skips the
    /// per-install decompression and file writes when the store is warm.
    ///
    /// Safe to mutate `vendor/` afterwards **only** because every writer in this
    /// installer (and `composer-patches`) replaces a file atomically — a temp
    /// file in the same dir plus a rename — which drops the hard link and gives
    /// the touched file a fresh inode, leaving the shared store intact. An
    /// in-place-truncating writer would corrupt the store for the next install.
    Hardlink,
}

/// Caller-supplied install options. Mirrors the subset of Composer's `install`
/// flags this installer honors.
#[derive(Debug, Clone, Copy, Default)]
pub struct InstallOptions {
    /// Skip packages in `composer.lock`'s `packages-dev` AND pass
    /// `no_dev=true` to the autoloader so dev autoload entries don't reach
    /// `vendor/autoload.php`.
    pub no_dev: bool,
    /// How dist files land in `vendor/` (see [`LinkMode`]). Defaults to
    /// [`LinkMode::Extract`].
    pub link_mode: LinkMode,
}

/// Lifecycle hooks fired during an install when root-script execution is opted
/// in. The installer stays command- and PHP-agnostic: the caller supplies an
/// implementation that maps each hook to the right Composer event
/// (`pre-install-cmd` vs `pre-update-cmd`, …) and runs it.
///
/// `Some(hooks)` is the scripts-ON gate: when present, the native Laravel
/// discovery + its drift guard are skipped (the real `post-autoload-dump`
/// entries run instead), and the "scripts not run" warning is suppressed.
/// `None` keeps the deterministic scripts-OFF behavior.
pub trait ScriptHooks {
    /// `pre-install-cmd` / `pre-update-cmd` — before package operations.
    fn pre_cmd(&self) -> Result<()>;
    /// `pre-autoload-dump` — before the autoloader is regenerated.
    fn pre_autoload_dump(&self) -> Result<()>;
    /// `post-autoload-dump` — after the autoloader is regenerated. Runs the
    /// project's real entries (e.g. Laravel's `package:discover`).
    fn post_autoload_dump(&self) -> Result<()>;
    /// `post-install-cmd` / `post-update-cmd` — at the very end.
    fn post_cmd(&self) -> Result<()>;
}

/// What happened. Returned to the caller for machine emission and a one-line
/// text summary.
#[derive(Debug, Clone)]
pub struct InstallSummary {
    pub project_root: PathBuf,
    pub packages_installed: u32,
    pub packages_already_present: u32,
    /// Packages whose dist reference matched `installed.json` and whose vendor
    /// directory already existed — skipped entirely (no download, no
    /// extraction).
    pub packages_up_to_date: u32,
    /// Composer-plugin packages installed like any other package (Composer
    /// installs them too), but whose install-time hooks are NOT run — this
    /// installer never executes plugin PHP. Their files ARE extracted, so
    /// packages that happen to be `type: composer-plugin` yet provide
    /// runtime code (e.g. `php-http/discovery`) are not left missing.
    pub plugin_hooks_skipped: u32,
    /// Packages that were in the previous `installed.json` but are no longer in
    /// the lock file (or excluded by `--no-dev`) and had their vendor directory
    /// removed.
    pub packages_removed: u32,
    pub bins_installed: u32,
    /// Files copied into the project root by the native
    /// `magento/magento-composer-installer` deploy (`extra.map`). Zero for
    /// non-Magento projects.
    pub files_deployed: u64,
    pub no_dev: bool,
    /// On-disk bytes of the dist archives fetched this run (cache hits
    /// contribute nothing).
    pub download_bytes: u64,
    /// Wall-clock of the autoload dump, in milliseconds. `0` when the freshness
    /// marker let the dump be skipped entirely.
    pub autoload_ms: u64,
    /// Soft preflight findings — one per Composer plugin, one for a non-empty
    /// `scripts` section, plus any Magento deploy warnings. Callers typically
    /// print these as `warning: …` lines.
    pub warnings: Vec<String>,
}

/// Apply `composer.lock` to `project_root`. See module docs for the flow.
///
/// # Errors
///
/// Returns `Err` when the project is not a Composer project (missing
/// `composer.json`/`composer.lock`), preflight finds a hard blocker, a download
/// or extraction fails, or the autoloader dump fails.
pub fn install_from_lock(
    env: &InstallEnv<'_>,
    project_root: &Path,
    opts: InstallOptions,
    hooks: Option<&dyn ScriptHooks>,
) -> Result<InstallSummary> {
    install_from_lock_with_patches(env, project_root, opts, hooks, None)
}

/// Like [`install_from_lock`], but also applies a resolved [`PatchPlan`]
/// (cweagans-style patches, applied natively). `patches` is `None` for the
/// patches-disabled path, which keeps install-set diffing dist-ref-only.
///
/// The plan drives **two** touch points required for re-application
/// correctness: pre-extraction it forces every package whose patch fingerprint
/// changed into the install set (so a changed patch set re-extracts pristine),
/// and post-extraction it applies the patches and rewrites `patches.lock.json`.
///
/// # Errors
///
/// As [`install_from_lock`], plus a patch that fails to apply under
/// [`FailureMode::Abort`].
///
/// # Panics
///
/// Only on an internal invariant violation: every package with a dist yields
/// at least its own dist URL.
///
#[tracing::instrument(skip_all, fields(project_root = %project_root.display()))]
pub fn install_from_lock_with_patches(
    env: &InstallEnv<'_>,
    project_root: &Path,
    opts: InstallOptions,
    hooks: Option<&dyn ScriptHooks>,
    patches: Option<&PatchPlan>,
) -> Result<InstallSummary> {
    let composer_json_path = project_root.join("composer.json");
    let composer_lock_path = project_root.join("composer.lock");
    let composer_json_bytes = match std::fs::read(&composer_json_path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(InstallError::MissingManifest {
                path: composer_json_path,
            }
            .into());
        }
        Err(e) => {
            return Err(
                eyre::Report::new(e).wrap_err(format!("reading {}", composer_json_path.display()))
            );
        }
    };
    let lock = if composer_lock_path.exists() {
        Lock::read(&composer_lock_path)?
    } else {
        return Err(InstallError::MissingLock {
            path: composer_lock_path,
        }
        .into());
    };

    // A stale lock (content-hash mismatch) warns rather than blocks — same as
    // Composer. Surface it first so it leads the warning list.
    let mut warnings = Vec::new();
    let wording = &env.wording;
    warnings.extend(content_hash_warning(&composer_json_bytes, &lock, wording)?);
    warnings.extend(preflight(
        &composer_json_bytes,
        &lock,
        opts.no_dev,
        hooks.is_some(),
        env.source_fetcher.is_some(),
        wording,
    )?);

    // Assemble per-host auth from every source Composer understands —
    // composer.json `config`, global `auth.json`, project-level `auth.json`,
    // and the `COMPOSER_AUTH` env var. Dist URLs sitting behind the same auth
    // as the metadata (Magento's `/archives/…`, private satis, GitLab CI
    // Composer ZIPs) need the header; public-CDN dists from Packagist do not.
    let composer_json_value: Value = serde_json::from_slice(&composer_json_bytes).map_err(|e| {
        InstallError::InvalidManifest {
            path: composer_json_path.clone(),
            detail: e.to_string(),
        }
    })?;
    let auth: HashMap<String, AuthCredentials> =
        read_all_auth_with(&composer_json_value, project_root, env.machine_auth)?;

    // `pre-install-cmd` / `pre-update-cmd` — before any package operation
    // (download/extract). Only when the user opted into root scripts.
    if let Some(hooks) = hooks {
        hooks.pre_cmd()?;
    }

    // Gather the packages actually installed. Filters:
    //   - `path` dists: materialized separately (symlink-or-copy).
    //   - metapackages: no `dist` and no code — pure require-graph nodes.
    // Composer-plugin packages install like any other package (Composer does
    // too — their files may provide runtime code); only their install-time
    // hooks are skipped, since this installer never runs plugin PHP. Preflight
    // warns about them.
    let candidates: Vec<&LockPackage> = if opts.no_dev {
        lock.packages.iter().collect()
    } else {
        lock.all_packages().collect()
    };
    let plugin_hooks_skipped =
        u32::try_from(candidates.iter().filter(|p| p.is_composer_plugin()).count())
            .unwrap_or(u32::MAX);

    // Drift guard for native Laravel discovery. This installer substitutes its
    // own package:discover + clearCompiled for Laravel's `post-autoload-dump`
    // script instead of running it. A custom step *after* the defaults is fine
    // (the defaults still run first). But a step *before* or *between* them — or
    // a renamed/removed discovery command — could change what the defaults see,
    // so it can't be safely reproduced: fail fast rather than leave the app
    // half-configured. Only applies when laravel/framework is installed.
    //
    // Skipped entirely when root scripts are opted in (`hooks.is_some()`): the
    // real `post-autoload-dump` entries run via the hook.
    if hooks.is_none() && candidates.iter().any(|p| p.name == "laravel/framework") {
        let scripts = composer_json_value
            .get("scripts")
            .cloned()
            .unwrap_or(Value::Null);
        let blocking = composer_installers::blocking_post_autoload_dump(&scripts);
        if !blocking.is_empty() {
            return Err(eyre!(
                "Laravel post-autoload-dump runs steps before/among the default Laravel steps \
                 that {tool} does not reproduce:\n  {}\n\n\
                 `artisan package:discover` and `ComposerScripts::postAutoloadDump` are reproduced natively, \
                 but only when they run first — a step ahead of or between them may change what \
                 they see. Steps appended *after* the defaults are fine. Reorder so custom steps \
                 come last, or run the script yourself (`composer run-script post-autoload-dump`). \
                 If Laravel changed its default post-autoload-dump, the native discovery is out of \
                 date — please report it.",
                blocking.join("\n  "),
                tool = wording.tool,
            ));
        }
    }
    let installable: Vec<&LockPackage> = candidates
        .iter()
        .copied()
        .filter(|p| !p.is_path_dist() && !p.is_metapackage())
        .collect();

    // Path packages are materialized separately (symlink-or-copy), not
    // downloaded.
    let installer_paths = composer_installers::InstallerPaths::parse(&composer_json_value);
    let path_packages: Vec<&LockPackage> = candidates
        .iter()
        .copied()
        .filter(|p| p.is_path_dist())
        .collect();
    let path_dests: Vec<PathBuf> = path_packages
        .iter()
        .map(|p| {
            let rel = composer_installers::install_path(
                &p.name,
                p.package_type.as_deref(),
                &installer_paths,
            );
            project_root.join(rel)
        })
        .collect();

    // Diff against the existing installed state to skip packages whose dist
    // reference hasn't changed and whose vendor dir is still present.
    //
    // Patch-aware step: any package whose desired patch fingerprint differs
    // from the applied one (`patches.lock.json`) is forced back into the
    // install set even when its dist reference is unchanged — a patch is only
    // ever applied to a pristine tree.
    let installed_state = read_installed_state(project_root);
    let force_patch: HashSet<&str> = patches
        .map(|plan| compute_force_set(plan, &installable, installed_state.as_ref(), project_root))
        .unwrap_or_default();
    let (install_set, packages_up_to_date) = diff_install_set_with_force(
        &installable,
        installed_state.as_ref(),
        project_root,
        &force_patch,
    );

    // Remove packages that left the lock. `new_record` is every package this
    // install puts on disk (path and dist alike), at its installer path; it is
    // written once the install succeeds so the next one knows what to remove
    // even if an autoloader dump rewrote `installed.json` in between. See
    // `crate::stale`.
    let new_record = InstallRecord::for_packages(&candidates, &installer_paths);
    let packages_removed = remove_stale_packages(project_root, &new_record);

    // Native `composer/installers`: a package's on-disk location can be
    // remapped by its `type` and the root `extra.installer-paths`. For the
    // common case (every Magento 2 module) this resolves to `vendor/<name>`.
    // The same computation runs in the autoloader so the generated autoload +
    // `installed.json` install-path point at the relocated tree.
    let vendor_dirs: Vec<PathBuf> = install_set
        .iter()
        .map(|p| {
            let rel = composer_installers::install_path(
                &p.name,
                p.package_type.as_deref(),
                &installer_paths,
            );
            // Surface composer/installers types this installer doesn't
            // relocate: the package lands in vendor/ and a framework expecting
            // it elsewhere won't find it. Only warn when it actually fell back
            // to vendor/<name>.
            if rel == format!("vendor/{}", p.name)
                && let Some(framework) =
                    composer_installers::unsupported_framework(p.package_type.as_deref())
            {
                warnings.push(format!(
                    "{}: package type '{}' is a composer/installers '{}' type that {tool} \
                     does not relocate — installing to vendor/{} (the framework may expect it \
                     elsewhere; add an extra.installer-paths entry to override)",
                    p.name,
                    p.package_type.as_deref().unwrap_or(""),
                    framework,
                    p.name,
                    tool = wording.tool,
                ));
            }
            project_root.join(rel)
        })
        .collect();
    // Expand each dist into its ordered candidate URL list —
    // `LockPackage::dist_urls()` puts a `preferred` mirror ahead of the dist's
    // own URL — and pre-render each candidate's `Authorization` header when its
    // host matches the auth map. Mirrors can sit on a different host than the
    // dist URL, so auth is resolved per candidate. String storage lives in a
    // sibling vec so `DistRequest` can carry borrowed data.
    //
    // The changed set splits into dist installs and git-source installs.
    // `vendor_dirs` is index-aligned to `install_set`; both channels fill the
    // same destinations, and everything after (patches, deploy, autoload,
    // bins) treats a source checkout exactly like an extracted dist.
    let dist_indices: Vec<usize> = (0..install_set.len())
        .filter(|&i| install_set[i].dist.is_some())
        .collect();
    let source_indices: Vec<usize> = (0..install_set.len())
        .filter(|&i| install_set[i].is_source_install())
        .collect();
    let candidate_sets: Vec<Vec<DistCandidate>> = dist_indices
        .iter()
        .map(|&i| {
            install_set[i]
                .dist_urls()
                .into_iter()
                .map(|url| {
                    let auth_entry = composer_auth::auth_key(&url)
                        .and_then(|origin| auth.get(origin))
                        .map(|creds| (creds.header_value(), creds.header_name()));
                    DistCandidate {
                        url,
                        auth_header: auth_entry.as_ref().map(|(v, _)| v.clone()),
                        auth_header_name: auth_entry.as_ref().map(|(_, n)| *n),
                    }
                })
                .collect()
        })
        .collect();
    let dists: Vec<DistRequest<'_>> = dist_indices
        .iter()
        .zip(candidate_sets.iter())
        .filter_map(|(&i, candidates)| {
            let p = install_set[i];
            let dist = p.dist.as_ref()?;
            // `dist_urls()` yields at least the dist's own URL for every package
            // with a dist.
            let (primary, fallbacks) = candidates
                .split_first()
                .expect("non-empty dist_urls for a dist package");
            Some(DistRequest {
                package_name: &p.name,
                url: &primary.url,
                sha1: dist.shasum.as_deref().unwrap_or(""),
                reference: dist.reference.as_deref().unwrap_or(""),
                strip_prefix: None,
                // Preflight rejected every other dist type.
                archive: ArchiveKind::from_dist_type(&dist.kind).unwrap_or(ArchiveKind::Zip),
                vendor_dest: &vendor_dirs[i],
                auth_header: primary.auth_header.as_deref(),
                auth_header_name: primary.auth_header_name,
                project_root,
                fallbacks,
            })
        })
        .collect();
    let source_url_sets: Vec<Vec<String>> = source_indices
        .iter()
        .map(|&i| install_set[i].source_urls())
        .collect();
    let source_specs: Vec<SourceSpec<'_>> = source_indices
        .iter()
        .zip(source_url_sets.iter())
        .map(|(&i, urls)| {
            let p = install_set[i];
            SourceSpec {
                package_name: &p.name,
                urls,
                reference: p.source.as_ref().map_or("", |s| s.reference.as_str()),
                dest: &vendor_dirs[i],
            }
        })
        .collect();

    let outcomes = fetch_and_extract_dists(
        env.fetcher,
        env.cache_root,
        &dists,
        env.progress,
        opts.link_mode,
    )?;

    // Clone + check out git-source packages. Preflight rejected them unless a
    // source fetcher is configured.
    let sources_installed = match env.source_fetcher {
        Some(fetcher) if !source_specs.is_empty() => materialize_sources(fetcher, &source_specs)?,
        _ => 0,
    };

    // Materialize `type: path` packages (symlink-or-copy) into their vendor
    // destinations. Done before the autoload dump so the generated autoloader
    // sees the linked trees.
    let path_summary = crate::path_link::materialize_path_packages(
        project_root,
        &path_packages,
        &path_dests,
        installed_state.as_ref(),
    );
    warnings.extend(path_summary.warnings);

    // Native patch application. Every `install_set` member is pristine here
    // (freshly extracted), so this is the only safe place to patch. Must run
    // *before* the Magento deploy so `extra.map`-copied files carry the patched
    // content — Composer's ordering.
    if let Some(plan) = patches {
        // Deferred (vendor-shipped) patches can be read now that their owning
        // packages are extracted: materialize and fold them into the plan
        // before applying, so they patch and earn a `patches.lock.json`
        // fingerprint like any other. The clone keeps the caller's plan intact.
        let resolved;
        let plan = if plan.deferred.is_empty() {
            plan
        } else {
            let mut p = plan.clone();
            p.resolve_deferred()
                .wrap_err("materializing vendor-shipped patches after install")?;
            resolved = p;
            &resolved
        };
        apply_patch_plan(
            plan,
            &install_set,
            &vendor_dirs,
            project_root,
            &mut warnings,
        )?;
    }

    // Native `magento/magento-composer-installer`: for every freshly-extracted
    // Magento 2 component, copy its `extra.map` files into the project root and
    // apply `extra.chmod`. Driving this off `install_set` (only changed/new
    // packages) matches Composer. A deploy failure is a warning, not an abort.
    let deploy_summary = deploy_components(&install_set, &vendor_dirs, project_root);
    warnings.extend(deploy_summary.warnings);

    // `pre-autoload-dump` — before the autoloader is regenerated.
    if let Some(hooks) = hooks {
        hooks.pre_autoload_dump()?;
    }

    // Autoloader freshness fast-path. The non-optimized autoloader is a pure
    // function of the root manifest and the lock. When nothing was installed or
    // removed this run, that fingerprint is unchanged, and the output is still
    // on disk, a regenerated tree would be byte-identical — so the dump is pure
    // waste and is skipped. Restricted to scripts-off: with root scripts on the
    // unconditional dump is kept so the pre/post-autoload-dump lifecycle is
    // observable exactly as before.
    let autoload_marker = project_root
        .join("vendor/composer")
        .join(env.autoload_marker);
    let lock_bytes = std::fs::read(&composer_lock_path).unwrap_or_default();
    let fingerprint =
        autoload_fingerprint(&composer_json_bytes, &lock_bytes, opts.no_dev).to_string();
    let autoload_fresh = hooks.is_none()
        && install_set.is_empty()
        && packages_removed == 0
        && path_summary.linked == 0
        && project_root.join("vendor/autoload.php").is_file()
        && std::fs::read_to_string(&autoload_marker)
            .ok()
            .as_deref()
            .map(str::trim)
            == Some(fingerprint.as_str());

    let autoload_started = std::time::Instant::now();
    if !autoload_fresh {
        dump_autoload(&DumpRequest {
            project_root,
            optimize: false,
            classmap_authoritative: false,
            no_dev: opts.no_dev,
            apcu_autoloader: false,
            apcu_prefix: None,
            autoloader_suffix: None,
        })
        .map_err(|e| eyre!("autoload dump failed: {e}"))?;
        // Record the fingerprint so the next unchanged sync can skip the dump.
        // Best-effort: a write failure just means we regenerate next time.
        if let Err(e) = std::fs::write(&autoload_marker, &fingerprint) {
            warnings.push(format!(
                "could not write autoload freshness marker {}: {e}",
                autoload_marker.display()
            ));
        }
    }
    let autoload_ms = u64::try_from(autoload_started.elapsed().as_millis()).unwrap_or(u64::MAX);

    match hooks {
        // Scripts ON: run the project's real `post-autoload-dump` entries.
        Some(hooks) => hooks.post_autoload_dump()?,
        // Scripts OFF: native Laravel package discovery — the effect of
        // Laravel's `post-autoload-dump` script, which this installer won't
        // run. Gated on `laravel/framework` being installed. Runs after the
        // autoload dump because it reads the freshly-written `installed.json`.
        None => {
            if candidates.iter().any(|p| p.name == "laravel/framework")
                && let Err(e) = run_laravel_discovery(project_root, &composer_json_value)
            {
                warnings.push(format!("laravel package discovery failed: {e}"));
            }
        }
    }

    let bin_summary = crate::bin_proxy::install_bin_proxies(project_root, &candidates);
    warnings.extend(bin_summary.warnings);

    // `post-install-cmd` / `post-update-cmd` — at the very end, after bins.
    if let Some(hooks) = hooks {
        hooks.post_cmd()?;
    }

    let packages_installed = u32::try_from(
        outcomes
            .iter()
            .filter(|o| matches!(o, DistOutcome::Downloaded { .. }))
            .count(),
    )
    .unwrap_or(u32::MAX);
    let download_bytes: u64 = outcomes
        .iter()
        .map(|o| match o {
            DistOutcome::Downloaded { bytes } => *bytes,
            DistOutcome::CacheHit => 0,
        })
        .sum();
    let packages_already_present = u32::try_from(
        outcomes
            .iter()
            .filter(|o| **o == DistOutcome::CacheHit)
            .count(),
    )
    .unwrap_or(u32::MAX);
    // Fold path-package materialization into the totals: a freshly linked/copied
    // path package counts as installed; an unchanged one counts as up-to-date.
    // Git-source installs (always freshly checked out when in the install
    // set) count as installed too.
    let packages_installed = packages_installed
        .saturating_add(path_summary.linked)
        .saturating_add(u32::try_from(sources_installed).unwrap_or(u32::MAX));
    let packages_up_to_date = packages_up_to_date.saturating_add(path_summary.up_to_date);
    if let Err(e) = new_record.write(project_root) {
        warnings.push(format!(
            "could not record the installed packages ({e}); the next install may not \
             remove packages that leave the lock"
        ));
    }
    Ok(InstallSummary {
        project_root: project_root.to_path_buf(),
        packages_installed,
        packages_already_present,
        packages_up_to_date,
        plugin_hooks_skipped,
        packages_removed,
        bins_installed: bin_summary.bins_installed,
        files_deployed: deploy_summary.files_deployed,
        no_dev: opts.no_dev,
        download_bytes,
        autoload_ms,
        warnings,
    })
}

/// The set of packages to force back into the install set for patching: those
/// whose patch fingerprint changed, plus — for project-root patches — every
/// package coupled to one already being re-extracted.
///
/// A root ("top-level") patch is applied atomically at the project root, so its
/// packages must stay in lockstep: if any one is re-extracted this run, all of
/// them must be re-extracted together and the patch re-applied. The coupling is
/// expanded to a fixpoint because root patches can chain through a shared
/// package.
fn compute_force_set<'a>(
    plan: &'a PatchPlan,
    installable: &[&'a LockPackage],
    installed_state: Option<&InstalledState>,
    project_root: &Path,
) -> HashSet<&'a str> {
    // Seed: packages whose patch fingerprint changed since the applied state.
    let mut force: HashSet<&str> = plan
        .tracked_packages()
        .filter(|name| plan.fingerprint_changed(name))
        .collect();

    // Deferred (vendor-shipped) patches have no fingerprint yet: their source
    // isn't readable until the owning package is on disk. Force their targets
    // so they're re-extracted pristine before the patch is applied after the
    // install. On a clean vendor/ the target is extracted anyway; this also
    // covers a present target whose patch-owning package alone was missing.
    for target in plan.deferred_targets() {
        if let Some(p) = installable.iter().find(|p| p.name == target) {
            force.insert(p.name.as_str());
        }
    }

    if plan.root_patches.is_empty() {
        return force;
    }

    let by_name: HashMap<&str, &LockPackage> =
        installable.iter().map(|p| (p.name.as_str(), *p)).collect();
    // Whether a package needs a fresh extract for a non-patch reason (its dist
    // reference changed, its vendor dir is gone, or there is no prior state).
    let needs_reextract = |name: &str| -> bool {
        by_name.get(name).is_some_and(|p| {
            installed_state.is_none_or(|state| !dist_up_to_date(p, state, project_root))
        })
    };

    loop {
        let mut added = false;
        for rp in &plan.root_patches {
            let any_reextract = rp
                .packages
                .iter()
                .any(|pkg| force.contains(pkg.as_str()) || needs_reextract(pkg));
            if any_reextract {
                for pkg in &rp.packages {
                    // Only force packages actually installable this run.
                    if let Some(p) = by_name.get(pkg.as_str())
                        && force.insert(p.name.as_str())
                    {
                        added = true;
                    }
                }
            }
        }
        if !added {
            break;
        }
    }
    force
}

/// Apply a resolved [`PatchPlan`] to the freshly-extracted `install_set`, then
/// rewrite `patches.lock.json` (always — it is load-bearing for the next run's
/// diff). Package-scoped patches apply into each target's install dir;
/// project-root patches apply once at the project root. Every re-extracted
/// tracked package then earns the desired fingerprint (fully applied) or loses
/// it (partial apply, or no longer patched). Returns `Err` only in `Abort`
/// failure mode; otherwise apply failures surface as `warnings`.
fn apply_patch_plan(
    plan: &PatchPlan,
    install_set: &[&LockPackage],
    vendor_dirs: &[PathBuf],
    project_root: &Path,
    warnings: &mut Vec<String>,
) -> Result<()> {
    let mut new_fingerprints = plan.applied.clone();
    let install_names: HashSet<&str> = install_set.iter().map(|p| p.name.as_str()).collect();

    // Packages whose patch set did not fully apply this run. They must not earn
    // a fingerprint, so the next run re-extracts pristine and retries.
    let mut failed: HashSet<String> = HashSet::new();

    // 1. Package-scoped patches: apply into each package's install dir.
    for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
        let Some(pkg_patches) = plan.patches.get(&pkg.name) else {
            continue;
        };
        let res = composer_patches::apply_package_patches(
            vendor_dir,
            &pkg.name,
            pkg_patches,
            plan.failure_mode,
            plan.skip_report,
        )?;
        warnings.extend(res.warnings);
        if res.fingerprint.is_none() {
            failed.insert(pkg.name.clone());
        }
    }

    // 2. Project-root patches: apply once each, at the project root. Coupling
    // guarantees a root patch's packages are all-in or all-out of the install
    // set, so `all_pristine` distinguishes "re-extracted this run, (re)apply
    // now" from "untouched, already applied before".
    let vendor_by_name: HashMap<&str, &PathBuf> = install_set
        .iter()
        .zip(vendor_dirs.iter())
        .map(|(p, dir)| (p.name.as_str(), dir))
        .collect();
    for rp in &plan.root_patches {
        let all_pristine = rp
            .packages
            .iter()
            .all(|p| install_names.contains(p.as_str()));
        if !all_pristine {
            continue;
        }
        if apply_root_patch(project_root, &rp.patch, plan.failure_mode, warnings)? {
            // Record the patch in each touched package's `PATCHES.txt`.
            if !plan.skip_report {
                for pkg in &rp.packages {
                    if let Some(dir) = vendor_by_name.get(pkg.as_str())
                        && let Err(e) = composer_patches::append_patches_txt(dir, &[&rp.patch])
                    {
                        warnings.push(format!(
                            "could not update PATCHES.txt in `{}`: {e}",
                            dir.display()
                        ));
                    }
                }
            }
        } else {
            failed.extend(rp.packages.iter().cloned());
        }
    }

    // 3. Recompute fingerprints for every tracked package re-extracted this run.
    // Untouched packages keep their prior fingerprint.
    for name in plan.tracked_packages() {
        if !install_names.contains(name) {
            continue;
        }
        match (failed.contains(name), plan.desired_fingerprint(name)) {
            // Fully applied → record the combined (package + root) fingerprint.
            (false, Some(fp)) => {
                new_fingerprints.insert(name.to_string(), fp);
            }
            // Partial apply, or no longer patched → drop, so the next run
            // re-extracts pristine (and retries any failed patch).
            _ => {
                new_fingerprints.remove(name);
            }
        }
    }

    let human = plan.write_lock.then(|| plan.human_view());
    if let Err(e) = composer_patches::lock::write_with_human(project_root, &new_fingerprints, human)
    {
        warnings.push(format!("could not write patches.lock.json: {e}"));
    }
    Ok(())
}

/// Apply a single project-root ("top-level") patch at the project root (the
/// caller records it in each touched package's `PATCHES.txt`). Returns whether
/// it applied cleanly: in `Abort` mode a failure is an `Err`; in `SkipAndWarn`
/// it pushes a warning and returns `Ok(false)`.
fn apply_root_patch(
    project_root: &Path,
    patch: &MaterializedPatch,
    failure_mode: FailureMode,
    warnings: &mut Vec<String>,
) -> Result<bool> {
    let text = std::fs::read_to_string(&patch.local_path)
        .with_context(|| format!("reading patch `{}`", patch.local_path.display()))?;
    let opts = ApplyOptions {
        depth: patch.depth,
        ..ApplyOptions::default()
    };
    match apply_patch_text(project_root, &text, &opts) {
        Ok(_) => Ok(true),
        Err(e) => match failure_mode {
            FailureMode::Abort => Err(eyre!(
                "patch `{}` failed to apply at the project root: {e:#}",
                patch.description
            )),
            FailureMode::SkipAndWarn => {
                warnings.push(format!(
                    "patch `{}` failed to apply at the project root: {e:#}",
                    patch.description
                ));
                Ok(false)
            }
        },
    }
}

/// Outcome of the native Magento deploy pass.
struct DeploySummary {
    files_deployed: u64,
    warnings: Vec<String>,
}

/// Run the native `magento/magento-composer-installer` deploy over the
/// freshly-extracted packages. `install_set[i]` was extracted to
/// `vendor_dirs[i]`, so the two slices are zipped. For each Magento 2 component
/// we copy its `extra.map` into `project_root` and apply `extra.chmod`; if any
/// `magento2-component` was deployed we emit `app/etc/vendor_path.php`. Deploy
/// failures become warnings.
fn deploy_components(
    install_set: &[&LockPackage],
    vendor_dirs: &[PathBuf],
    project_root: &Path,
) -> DeploySummary {
    let mut files_deployed = 0u64;
    let mut warnings = Vec::new();
    let mut deployed_component = false;

    for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
        let Some(plan) = composer_installers::plan_deploy(pkg.package_type.as_deref(), &pkg.extra)
        else {
            continue;
        };
        if plan.map.is_empty() && plan.chmod.is_empty() {
            continue;
        }
        match composer_installers::apply_deploy(&plan, vendor_dir, project_root) {
            Ok(stats) => {
                files_deployed += stats.files_copied;
                deployed_component |= plan.is_component;
                warnings.extend(
                    stats
                        .warnings
                        .into_iter()
                        .map(|w| format!("deploy of {}: {w}", pkg.name)),
                );
            }
            Err(e) => {
                warnings.push(format!("deploy of {} failed: {e}", pkg.name));
            }
        }
    }

    // `app/etc/vendor_path.php` is generated by the installer (it is not one of
    // magento2-base's mapped files); Magento's bootstrap reads it to locate
    // `vendor/`. Emit it once whenever a component laid down the root skeleton.
    if deployed_component && let Err(e) = write_vendor_path_php(project_root) {
        warnings.push(format!("writing app/etc/vendor_path.php failed: {e}"));
    }

    DeploySummary {
        files_deployed,
        warnings,
    }
}

/// Reproduce Laravel's package discovery: rebuild `bootstrap/cache/packages.php`
/// from `installed.json` + the root `extra.laravel`, then clear the stale
/// compiled caches Laravel's `clearCompiled()` removes. Mirrors what
/// `artisan package:discover` (run via `post-autoload-dump`) would do.
fn run_laravel_discovery(project_root: &Path, composer_json_value: &Value) -> Result<()> {
    let installed_path = project_root.join("vendor/composer/installed.json");
    let bytes = std::fs::read(&installed_path)
        .wrap_err_with(|| format!("reading {}", installed_path.display()))?;
    let installed: Value = serde_json::from_slice(&bytes).wrap_err("parsing installed.json")?;
    let root_extra = composer_json_value
        .get("extra")
        .cloned()
        .unwrap_or(Value::Null);

    let manifest = composer_installers::build_package_manifest(&installed, &root_extra);
    let php = composer_installers::render_packages_php(&manifest);

    let cache_path = project_root.join(composer_installers::PACKAGES_CACHE);
    if let Some(parent) = cache_path.parent() {
        std::fs::create_dir_all(parent)
            .wrap_err_with(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(&cache_path, php)
        .wrap_err_with(|| format!("writing {}", cache_path.display()))?;

    // clearCompiled(): drop the config/services caches so they can't reference
    // a package set that just changed.
    for rel in composer_installers::STALE_CACHES {
        let path = project_root.join(rel);
        if path.exists() {
            let _ = std::fs::remove_file(path);
        }
    }
    Ok(())
}

/// Write `app/etc/vendor_path.php` (creating `app/etc/` if needed).
fn write_vendor_path_php(project_root: &Path) -> Result<()> {
    let dir = project_root.join("app/etc");
    std::fs::create_dir_all(&dir).wrap_err_with(|| format!("creating {}", dir.display()))?;
    std::fs::write(
        dir.join("vendor_path.php"),
        composer_installers::VENDOR_PATH_PHP,
    )
    .wrap_err("writing vendor_path.php")?;
    Ok(())
}

/// Snapshot of `vendor/composer/installed.json` — the packages and dist
/// references that were installed on the previous run.
pub(crate) struct InstalledState {
    /// Package name → dist reference from the previous install.
    pub(crate) packages: HashMap<String, String>,
}

/// Read `vendor/composer/installed.json` and extract the package name → dist
/// reference mapping. Returns `None` if the file doesn't exist or can't be
/// parsed (first install, corrupted state, etc.).
fn read_installed_state(project_root: &Path) -> Option<InstalledState> {
    let path = project_root.join("vendor/composer/installed.json");
    let bytes = std::fs::read(&path).ok()?;
    let value: Value = serde_json::from_slice(&bytes).ok()?;
    let obj = value.as_object()?;

    let packages_arr = obj.get("packages")?.as_array()?;
    let mut packages = HashMap::with_capacity(packages_arr.len());
    for pkg in packages_arr {
        let name = pkg.get("name").and_then(|v| v.as_str()).unwrap_or("");
        if name.is_empty() {
            continue;
        }
        // The dist reference, or the source reference for a git-source
        // install, so source packages diff on their checked-out commit.
        let reference = pkg
            .get("dist")
            .and_then(|d| d.get("reference"))
            .and_then(|r| r.as_str())
            .or_else(|| {
                pkg.get("source")
                    .and_then(|s| s.get("reference"))
                    .and_then(|r| r.as_str())
            })
            .unwrap_or("");
        packages.insert(name.to_string(), reference.to_string());
    }

    Some(InstalledState { packages })
}

/// Diff the lock file's installable set against the existing `installed.json`
/// state. Returns the subset of packages that need downloading/extracting and
/// the count already up-to-date. Removing packages that left the lock is
/// separate; see [`crate::stale::remove_stale_packages`].
#[cfg(test)]
pub(crate) fn diff_install_set<'a>(
    installable: &[&'a LockPackage],
    installed_state: Option<&InstalledState>,
    project_root: &Path,
) -> (Vec<&'a LockPackage>, u32) {
    diff_install_set_with_force(installable, installed_state, project_root, &HashSet::new())
}

/// Like [`diff_install_set`], but `force` names packages that must be
/// (re-)installed even when their dist reference matches and the vendor dir is
/// present — the patch-aware path.
pub(crate) fn diff_install_set_with_force<'a>(
    installable: &[&'a LockPackage],
    installed_state: Option<&InstalledState>,
    project_root: &Path,
    force: &HashSet<&str>,
) -> (Vec<&'a LockPackage>, u32) {
    let Some(state) = installed_state else {
        return (installable.to_vec(), 0);
    };

    let mut need_install: Vec<&'a LockPackage> = Vec::new();
    let mut up_to_date: u32 = 0;
    for p in installable {
        if !force.contains(p.name.as_str()) && dist_up_to_date(p, state, project_root) {
            up_to_date = up_to_date.saturating_add(1);
            continue;
        }
        need_install.push(p);
    }
    (need_install, up_to_date)
}

/// Whether `p` is already installed at the locked revision: its recorded dist
/// reference matches the lock and its `vendor/<name>` directory is present. The
/// single source of truth for "no fresh extract needed", shared by the
/// install-set diff and the patch-coupling force computation.
fn dist_up_to_date(p: &LockPackage, state: &InstalledState, project_root: &Path) -> bool {
    // The dist reference, or the source reference for a git-source install:
    // a source package re-clones only when its locked commit changes.
    let lock_ref = p.install_reference();
    state.packages.get(&p.name).is_some_and(|installed_ref| {
        installed_ref == lock_ref && project_root.join("vendor").join(&p.name).is_dir()
    })
}

/// Marker file (under `vendor/composer/`) holding the autoloader freshness
/// fingerprint from the last dump. Its presence + match lets a subsequent
/// unchanged sync skip the autoloader regeneration.
pub(crate) const AUTOLOAD_FRESH_MARKER: &str = ".composer-install-autoload-fresh";

/// Fingerprint of everything the non-optimized autoloader output depends on:
/// the root manifest bytes (autoload / config / installer-paths in `extra`) and
/// the lock bytes (the full package set and each package's own `autoload`
/// block), plus the dev flag.
///
/// Non-cryptographic on purpose — this is a local freshness cache, not a trust
/// boundary. A hash collision would only cost a skipped regeneration,
/// recoverable with an explicit re-dump.
fn autoload_fingerprint(composer_json_bytes: &[u8], lock_bytes: &[u8], no_dev: bool) -> u64 {
    let mut h = std::hash::DefaultHasher::new();
    composer_json_bytes.hash(&mut h);
    lock_bytes.hash(&mut h);
    no_dev.hash(&mut h);
    h.finish()
}

/// Check the lock's `content-hash` field against the current `composer.json`
/// bytes, using the same algorithm Composer runs (delegated to
/// [`composer_manifest::lockfile::content_hash`]).
///
/// A mismatch is *not* a hard failure: Composer only warns and installs the
/// lock's package set anyway, so the user gets a reproducible (if slightly
/// stale) environment rather than a refusal. We mirror that — return the
/// warning string on mismatch, `None` otherwise.
fn content_hash_warning(
    composer_json_bytes: &[u8],
    lock: &Lock,
    wording: &Wording<'_>,
) -> Result<Option<String>> {
    let Some(expected) = &lock.content_hash else {
        // Pre-1.10 lockfiles don't carry a content-hash. Composer tolerates
        // them; we do too rather than refuse to install a working historical
        // project.
        return Ok(None);
    };
    let actual = lockfile::content_hash(composer_json_bytes)?;
    if actual.eq_ignore_ascii_case(expected) {
        return Ok(None);
    }
    Ok(Some(format!(
        "composer.lock is out of sync with composer.json (content-hash {expected} → {actual}); \
         installing the locked package set anyway — you may be getting outdated dependencies. \
         Run `{}` to regenerate the lock.",
        wording.update_command,
    )))
}

/// Split lockfile contents into hard blockers (returned as `Err`) and soft
/// warnings (returned as `Ok`).
///
/// Hard blockers are things this installer genuinely cannot install:
/// source-only packages (no `dist`) and non-zip dists. The downstream loop
/// relies on preflight having rejected these and unwraps accordingly.
///
/// Warnings are things deliberately not executed but installed around: Composer
/// plugins (the package zip is skipped) and a non-empty `scripts` section when
/// script execution isn't opted in.
///
/// Every hard reason is aggregated into a single error.
fn preflight(
    composer_json_bytes: &[u8],
    lock: &Lock,
    no_dev: bool,
    scripts_on: bool,
    sources_on: bool,
    wording: &Wording<'_>,
) -> Result<Vec<String>> {
    let Wording {
        tool,
        install_command,
        scripts_hint,
        ..
    } = *wording;
    let mut reasons: Vec<String> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();
    let mut plugin_packages: Vec<String> = Vec::new();

    // composer.json scripts → not run unless opted in. When scripts are off,
    // warn — but only about scripts not already reproduced natively (Laravel's
    // discovery `post-autoload-dump` runs either way). When scripts are on, the
    // hooks run them: no warning.
    if !scripts_on
        && let Ok(value) = serde_json::from_slice::<Value>(composer_json_bytes)
        && value
            .get("scripts")
            .and_then(Value::as_object)
            .is_some_and(|s| !s.is_empty())
        && !composer_installers::only_reproduced_scripts(
            value.get("scripts").unwrap_or(&Value::Null),
        )
    {
        warnings.push(format!(
            "composer.json declares `scripts`; they are not run by default. {scripts_hint}"
        ));
    }

    let packages: Vec<&LockPackage> = if no_dev {
        lock.packages.iter().collect()
    } else {
        lock.all_packages().collect()
    };

    for p in packages {
        // path dists materialize via symlink-or-copy — outside the dist-archive
        // flow. A project that has *only* path dists works fine; no rejection.
        if p.is_path_dist() {
            continue;
        }
        if p.is_metapackage() {
            // Metapackages legitimately have no `dist` — pure require-graph
            // aggregators. Nothing to install.
            continue;
        }
        if p.is_composer_plugin() {
            // Plugin install-time hooks are arbitrary PHP we won't run, but the
            // package's FILES install like any other (plugins can double as
            // runtime libraries: php-http/discovery's classes are called by
            // opensearch-php at runtime). Collect the name for one aggregated
            // hooks-not-run warning after the loop, then fall through to the
            // dist checks below: since we extract it, its dist must be
            // installable.
            plugin_packages.push(p.name.clone());
        }
        let Some(dist) = &p.dist else {
            // No dist: install from a git `source` when a source fetcher is
            // configured. Composer normalizes github/gitlab/bitbucket sources
            // to `git` in the lock; hg/svn sources are not supported.
            match &p.source {
                Some(src) if src.kind == "git" && sources_on => {}
                Some(src) if src.kind == "git" => reasons.push(format!(
                    "package `{}` has no `dist` block, only a git source, and git source \
                     installs are not enabled — configure a source fetcher, or install it \
                     with `{install_command}`.",
                    p.name,
                )),
                Some(src) => reasons.push(format!(
                    "package `{}` has a `{}` source; {tool} can only install git \
                     sources — install it with `{install_command}`.",
                    p.name, src.kind,
                )),
                None => reasons.push(format!(
                    "package `{}` has no `dist` block and no git `source` to clone — install \
                     it with `{install_command}`.",
                    p.name,
                )),
            }
            continue;
        };
        if ArchiveKind::from_dist_type(&dist.kind).is_none() {
            reasons.push(format!(
                "package `{}` uses dist type `{}`; {tool} handles only `zip` and \
                 `tar` dists — install it with `{install_command}`.",
                p.name, dist.kind,
            ));
        }
        // Missing/empty `dist.shasum` is normal: every VCS-driver dist
        // (GitHub/GitLab/Bitbucket zipballs) emits an empty shasum. Composer
        // treats empty/null as skip-verify; the downloader does the same and
        // keys the cache off `dist.reference`.
    }

    if !plugin_packages.is_empty() {
        let names = plugin_packages.join(", ");
        let noun = if plugin_packages.len() == 1 {
            "package"
        } else {
            "packages"
        };
        warnings.push(format!(
            "{noun} {names} {verb} Composer plugins (type `composer-plugin`); \
             {pronoun} files install like any other package's, but {tool} \
             does not run plugin install-time hooks. Run `{install_command}` \
             if the hook behavior is required.",
            verb = if plugin_packages.len() == 1 {
                "is a"
            } else {
                "are"
            },
            pronoun = if plugin_packages.len() == 1 {
                "its"
            } else {
                "their"
            },
        ));
    }

    if reasons.is_empty() {
        Ok(warnings)
    } else {
        Err(InstallError::Unsupported { reasons }.into())
    }
}

#[cfg(test)]
mod tests;