Skip to main content

aube_resolver/
peer_context.rs

1//! Peer-dependency post-processing over an already-resolved graph.
2//!
3//! Two user-visible passes live here:
4//!
5//! * [`hoist_auto_installed_peers`] — promotes peers declared by direct
6//!   dependencies up to importer direct deps, matching pnpm's
7//!   `auto-install-peers=true` behavior. Idempotent on graphs that already
8//!   ship with those hoists (npm v7+ output, lockfile-driven installs).
9//! * [`apply_peer_contexts`] — computes pnpm-style `(peer@ver)` suffixes
10//!   on contextualized `dep_path`s. Drives the sibling-symlink wiring in
11//!   `aube-linker` so each subtree that pins different peer versions gets
12//!   its own virtual-store entry.
13//!
14//! [`detect_unmet_peers`] reports what the two passes above couldn't wire
15//! up, so the CLI can surface warnings.
16//!
17//! Call order from `Resolver::resolve`: `hoist_auto_installed_peers`
18//! (fresh resolves only) → `apply_peer_contexts` → `detect_unmet_peers`.
19
20use crate::version_satisfies;
21use crate::{FxHashMap, FxHashSet};
22use aube_lockfile::{DepType, DirectDep, LockedPackage, LockfileGraph};
23use std::collections::{BTreeMap, BTreeSet};
24
25/// A peer dependency whose declared range doesn't match the version the
26/// tree actually ends up providing. Emitted as a warning by `aube install`.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct UnmetPeer {
29    /// dep_path of the package that declared the peer.
30    pub from_dep_path: String,
31    /// Human-friendly package name (pre-context) for display.
32    pub from_name: String,
33    /// Name of the peer being declared (e.g. `"react"`).
34    pub peer_name: String,
35    /// The declared peer range from the package's packument
36    /// (e.g. `"^16.8.0 || ^17.0.0 || ^18.0.0"`).
37    pub declared: String,
38    /// What the tree actually provides, if anything. `None` means the
39    /// peer is completely missing — rare in practice because the BFS
40    /// auto-install path usually drags *some* version in, but it can
41    /// happen for corner cases.
42    pub found: Option<String>,
43}
44
45/// Scan the resolved graph and return every declared required peer whose
46/// resolved version doesn't satisfy its declared range. Optional peers
47/// (`peerDependenciesMeta.optional = true`) are skipped — pnpm treats
48/// those as "warn suppressed" with `auto-install-peers=true`. The result
49/// is purely informational; aube never fails an install on unmet peers,
50/// matching pnpm.
51///
52/// The "found" version for each package comes from its own
53/// `dependencies` map — the peer-context pass writes the resolved peer
54/// tail there, so we don't have to re-walk ancestors. Any peer suffix on
55/// the stored tail is stripped before the semver check so `18.2.0(foo@1)`
56/// is treated as `18.2.0`.
57pub fn detect_unmet_peers(graph: &LockfileGraph) -> Vec<UnmetPeer> {
58    let mut unmet = Vec::new();
59    for pkg in graph.packages.values() {
60        for (peer_name, declared_range) in &pkg.peer_dependencies {
61            let optional = pkg
62                .peer_dependencies_meta
63                .get(peer_name)
64                .map(|m| m.optional)
65                .unwrap_or(false);
66            if optional {
67                continue;
68            }
69
70            let found_tail = pkg.dependencies.get(peer_name);
71            let found_version = found_tail.map(|t| canonical_tail(t).to_string());
72
73            let satisfied = match &found_version {
74                Some(v) => version_satisfies(v, declared_range),
75                None => false,
76            };
77            if satisfied {
78                continue;
79            }
80
81            unmet.push(UnmetPeer {
82                from_dep_path: pkg.dep_path.clone(),
83                from_name: pkg.name.clone(),
84                peer_name: peer_name.clone(),
85                declared: declared_range.clone(),
86                found: found_version,
87            });
88        }
89    }
90    // Stable order for deterministic test output and readable warnings.
91    unmet.sort_by(|a, b| {
92        (a.from_dep_path.as_str(), a.peer_name.as_str())
93            .cmp(&(b.from_dep_path.as_str(), b.peer_name.as_str()))
94    });
95    unmet
96}
97
98/// Promote direct dependencies' unmet peers to importer direct deps.
99///
100/// Walks each importer's direct dependencies and hoists any peer they
101/// declare that isn't already a direct dep of the importer up to the
102/// importer's `dependencies` list — what pnpm's
103/// `auto-install-peers=true` produces in its v9 lockfile. Peers declared by
104/// transitive dependencies stay in the resolved graph for peer-context
105/// sibling wiring, but they are not surfaced as top-level
106/// `node_modules/<peer>` entries.
107///
108/// Public so lockfile-driven installs that need to re-derive peer
109/// wiring (npm/yarn/bun formats, which don't record peer contexts)
110/// can run this before [`apply_peer_contexts`] to match fresh-resolve
111/// behavior. Idempotent in the npm case: npm v7+ already hoists
112/// auto-installed peers into root's `dependencies`, so they arrive
113/// pre-`satisfied` and no additions are emitted.
114///
115/// Algorithm:
116///   1. For each importer, collect the set of names already in its
117///      direct deps. Those are "satisfied" and need no hoist.
118///   2. Visit only those direct dependency packages and examine their
119///      `peer_dependencies` declarations. For each declared peer not
120///      already satisfied by the importer, find a resolved version somewhere
121///      in the graph and synthesize a `DirectDep` entry. Mark it as
122///      satisfied so a second direct dep doesn't add a duplicate.
123///   3. Stable: we walk in-order and take the first declared peer range
124///      encountered per name as the specifier. Conflicting ranges across
125///      the tree are not reconciled — first one wins. This matches pnpm
126///      for the simple case; the complex case is deferred.
127///
128/// Leaves everything else about the graph untouched — no packages are
129/// added or removed, only importer entries grow.
130pub fn hoist_auto_installed_peers(mut graph: LockfileGraph) -> LockfileGraph {
131    let importer_paths: Vec<String> = graph.importers.keys().cloned().collect();
132    for importer_path in importer_paths {
133        let Some(direct_deps) = graph.importers.get(&importer_path) else {
134            continue;
135        };
136        let mut satisfied: FxHashSet<String> = direct_deps.iter().map(|d| d.name.clone()).collect();
137
138        // Additions are gathered into a separate vec so we don't mutate
139        // the importer's direct-dep list while still borrowing from it.
140        let mut additions: Vec<DirectDep> = Vec::new();
141
142        for dep_path in direct_deps.iter().map(|d| &d.dep_path) {
143            let Some(pkg) = graph.packages.get(dep_path) else {
144                continue;
145            };
146
147            // Collect unmet peer declarations from this package.
148            for (peer_name, peer_range) in &pkg.peer_dependencies {
149                if satisfied.contains(peer_name) {
150                    continue;
151                }
152                // Find any resolved version in the graph for this peer.
153                // Prefer the one the package already wired via its own
154                // dependencies map (the BFS auto-install result), and
155                // fall back to scanning `graph.packages` for a name
156                // match. If nothing matches, we quietly drop the peer —
157                // that's the only path where aube stays stricter than
158                // pnpm today; a future PR will emit an unmet warning.
159                //
160                // Fallback takes the semver-max version rather than
161                // whatever `BTreeMap` iteration order surfaces first —
162                // otherwise two resolved `react` entries like `18.0.0`
163                // and `18.3.1` would pick the lexicographically-earlier
164                // (older) one.
165                let resolved_version = pkg.dependencies.get(peer_name).cloned().or_else(|| {
166                    // Filter to parseable semver versions *before* the
167                    // max_by — returning `Equal` on parse failure makes
168                    // the comparator non-transitive, so an unparseable
169                    // entry sitting between two valid ones would cause
170                    // `max_by` to pick an iteration-order-dependent
171                    // result instead of the true maximum.
172                    graph
173                        .packages
174                        .values()
175                        .filter(|p| p.name == *peer_name)
176                        .filter_map(|p| {
177                            node_semver::Version::parse(&p.version)
178                                .ok()
179                                .map(|v| (v, p.version.clone()))
180                        })
181                        .max_by(|a, b| a.0.cmp(&b.0))
182                        .map(|(_, s)| s)
183                });
184                let Some(version) = resolved_version else {
185                    continue;
186                };
187                let canonical_version = canonical_tail(&version).to_string();
188                let synth_dep_path = format!("{peer_name}@{canonical_version}");
189                if !graph.packages.contains_key(&synth_dep_path) {
190                    // The peer version the package wired didn't match an
191                    // actual package entry — bail out for this peer
192                    // rather than writing a dangling DirectDep.
193                    continue;
194                }
195                satisfied.insert(peer_name.clone());
196                additions.push(DirectDep {
197                    name: peer_name.clone(),
198                    dep_path: synth_dep_path,
199                    // Peers auto-hoisted to the root are in the prod
200                    // graph by convention — matches what pnpm writes.
201                    dep_type: DepType::Production,
202                    specifier: Some(peer_range.clone()),
203                });
204            }
205        }
206
207        if !additions.is_empty() {
208            tracing::debug!(
209                "hoisted {} auto-installed peer(s) into importer {}",
210                additions.len(),
211                importer_path
212            );
213            if let Some(deps) = graph.importers.get_mut(&importer_path) {
214                deps.extend(additions);
215                deps.sort_by(|a, b| a.name.cmp(&b.name));
216            }
217        }
218    }
219    graph
220}
221
222/// Walk the resolved graph top-down from each importer and compute a
223/// peer-dependency context for every package, producing a new graph whose
224/// dep_paths carry pnpm-style `(peer@ver)` suffixes.
225///
226/// The goal is parity with pnpm's v9 lockfile output: the same
227/// `name@version` can appear multiple times — once per distinct set of peer
228/// resolutions — so different subtrees that pin incompatible peers get
229/// isolated virtual-store entries and truly different sibling-symlink
230/// neighborhoods.
231///
232/// Algorithm per visited package P, reached at some point in a DFS from an
233/// importer with `ancestor_scope: name -> dep_path_tail`:
234///
235///  1. For each peer name declared by P, look it up in `ancestor_scope`
236///     (nearest-ancestor-wins, since the scope is rebuilt per recursion).
237///     If missing, fall back to P's own entry in `dependencies` — the BFS
238///     enqueue above auto-installed it as a transitive, which matches
239///     pnpm's `auto-install-peers=true` default.
240///  2. Sort the (peer_name, resolution) pairs and serialize as
241///     `(n1@v1)(n2@v2)…` for the suffix.
242///  3. Produce a contextualized dep_path `name@version{suffix}`. If that
243///     key is already in `out_packages` (or currently on the DFS stack via
244///     `visiting`), short-circuit — we've already emitted this variant.
245///  4. Build a new scope for P's children by merging the ancestor scope
246///     with P's own `dependencies` (rewritten to point at contextualized
247///     children) and the resolved peer map. Recurse.
248///  5. Emit the contextualized LockedPackage.
249///
250/// Cycles: protected by `visiting` — if a package is re-entered via a
251/// dependency cycle, we return the already-computed dep_path without
252/// recursing again. The peer context is fixed at first visit; any cycle
253/// traversal uses whatever context was live at that first visit.
254///
255/// Nested peer suffixes: pnpm writes `(react-dom@18.2.0(react@18.2.0))`
256/// when a declared peer has its own resolved peers. A single top-down
257/// DFS pass can't produce that form, because when a parent P records
258/// a peer version in its children's scope, it only knows the canonical
259/// tail — the peer's OWN suffix is computed later when the peer itself
260/// gets visited. We solve this by running `apply_peer_contexts_once` in
261/// a fixed-point loop: the second iteration's input has Pass 1's
262/// contextualized tails in every `pkg.dependencies` map, so when a
263/// descendant looks a peer up in ancestor scope it sees the full
264/// nested tail and serializes it as such. Most peer chains converge in
265/// 2–3 iterations; we cap at 16 as a safety belt.
266///
267/// Limitations (documented as follow-ups in the README):
268///   - No per-peer range satisfaction — we take whatever the ancestor has,
269///     even if it technically doesn't match P's declared peer range.
270///
271/// Knobs controlling the peer-context pass. Plumbed from four
272/// pnpm-compatible settings (`dedupe-peer-dependents`, `dedupe-peers`,
273/// `resolve-peers-from-workspace-root`, `peers-suffix-max-length`)
274/// through the `Resolver`'s `with_*` setters.
275#[derive(Debug, Clone, Copy)]
276pub struct PeerContextOptions {
277    /// When true, run the cross-subtree peer-variant collapse pass
278    /// after every iteration of the fixed-point loop. Matches pnpm's
279    /// default.
280    pub dedupe_peer_dependents: bool,
281    /// When true, emit suffixes as `(version)` instead of
282    /// `(name@version)`. Affects both the package key, the reference
283    /// tails stored in `dependencies`, and the cycle-break form of
284    /// `contains_canonical_back_ref`.
285    pub dedupe_peers: bool,
286    /// When true, unresolved peers can be satisfied by a dep declared
287    /// at the root importer (`"."`) even if no ancestor scope carries
288    /// the peer. Runs between own-deps and graph-wide scan in the
289    /// peer-context visitor — see `visit_peer_context` in this
290    /// module for the owning implementation (intentionally crate-
291    /// private; the public API here is the option flag itself).
292    pub resolve_from_workspace_root: bool,
293    /// Byte cap on the peer-ID suffix after which the entire suffix
294    /// is hashed to `_<10-char-sha256-hex>`. pnpm's default is 1000.
295    pub peers_suffix_max_length: usize,
296}
297
298impl Default for PeerContextOptions {
299    fn default() -> Self {
300        Self {
301            dedupe_peer_dependents: true,
302            dedupe_peers: false,
303            resolve_from_workspace_root: true,
304            peers_suffix_max_length: 1000,
305        }
306    }
307}
308
309/// Compute peer-context suffixes over an already-resolved graph.
310///
311/// Takes a *canonical* graph — one `LockedPackage` per `(name,
312/// version)` with `peer_dependencies` populated — and produces a
313/// *contextualized* graph whose keys and transitive references carry
314/// `(peer@ver)` suffixes when packages resolve peers differently in
315/// different subtrees. Drives the sibling-symlink wiring in
316/// `aube-linker` for peers, so every fetch/materialize site sees a
317/// per-context identity for any package whose peers disambiguate.
318///
319/// Public so lockfile-driven installs can run the pass over graphs
320/// parsed from npm/yarn/bun lockfiles (which emit canonical form —
321/// no peer suffixes — and would otherwise leave peer-dependent
322/// packages without their peers as `.aube/<pkg>/node_modules/<peer>`
323/// siblings). Fresh resolves call it internally from
324/// `Resolver::resolve`.
325pub fn apply_peer_contexts(
326    canonical: LockfileGraph,
327    options: &PeerContextOptions,
328) -> Result<LockfileGraph, crate::Error> {
329    const MAX_ITERATIONS: usize = 16;
330    let mut current = canonical;
331    let mut converged = false;
332    // Hash both keys and dependency tails. A peer-context iteration can
333    // rewrite a dependency value to point at an existing key without
334    // adding a new key, so a key-only convergence test ships partially
335    // rewritten tails. Linker reads tails directly to locate sibling
336    // symlink targets, stale tails produce broken `node_modules`.
337    let graph_hash = |g: &LockfileGraph| -> u64 {
338        let total_deps: usize = g.packages.values().map(|p| p.dependencies.len()).sum();
339        let mut tokens: Vec<&str> = Vec::with_capacity(g.packages.len() * 3 + total_deps * 2);
340        for (k, pkg) in &g.packages {
341            tokens.push(k.as_str());
342            tokens.push("\x1f");
343            for (name, tail) in &pkg.dependencies {
344                tokens.push(name.as_str());
345                tokens.push(tail.as_str());
346            }
347            tokens.push("\x1e");
348        }
349        aube_util::hash::ordered_seq_hash(tokens.iter().copied())
350    };
351    // Carry the post-iteration hash forward as the next iteration's
352    // pre-hash. Saves one full graph walk per iteration (the loop runs
353    // up to 16 times; each `graph_hash` allocates a Vec<&str> sized
354    // to `pkgs * 3 + deps * 2` tokens — ~25k entries on a 1000-pkg
355    // graph). One hash per iter instead of two.
356    let mut before = graph_hash(&current);
357    for i in 0..MAX_ITERATIONS {
358        let after_once = apply_peer_contexts_once(current, options);
359        let next = if options.dedupe_peer_dependents {
360            dedupe_peer_variants(after_once)
361        } else {
362            after_once
363        };
364        let after = graph_hash(&next);
365        if before == after {
366            tracing::debug!("peer-context pass converged after {i} iteration(s)");
367            current = next;
368            converged = true;
369            break;
370        }
371        current = next;
372        before = after;
373    }
374    if !converged {
375        // Iteration cap hit. Returning the partial graph would ship
376        // broken node_modules. Now fatal.
377        tracing::error!(
378            code = aube_codes::errors::ERR_AUBE_PEER_CONTEXT_NOT_CONVERGED,
379            max_iterations = MAX_ITERATIONS,
380            "peer-context hit MAX_ITERATIONS={MAX_ITERATIONS} without convergence"
381        );
382        return Err(crate::Error::PeerContextDivergence(MAX_ITERATIONS));
383    }
384    // Propagate each package's peer-suffix segments up through its
385    // non-peer-declaring ancestors so a parent that pulls in a peer-
386    // bearing descendant carries the same `(peer@version)` suffix on
387    // its own dep_path. Matches pnpm's lockfile shape — pnpm 9 emits
388    // every peer-bearing package's resolved peer set on every
389    // ancestor in the chain (importer rows included), even when the
390    // ancestor itself doesn't declare those peers. Without the
391    // propagation aube would tag the suffix only on the package that
392    // declares peers, which differs from pnpm-lock.yaml in the
393    // `importers:` section any time a non-peer-declaring middle node
394    // sits between an importer and its peer-bearing descendant.
395    //
396    // Runs after the fixed-point loop converges so all self-suffixes
397    // are stable, and before `dedupe_peer_suffixes` so the latter's
398    // `(name@version)` → `(version)` collapse acts on the propagated
399    // form too.
400    let current = propagate_peer_suffixes_to_ancestors(current, options);
401    // `dedupe-peers=true` rewrites the parenthesized peer suffix to
402    // drop the `name@` prefix. Done as a post-pass rather than inline
403    // so cycle detection during the fixed-point loop keeps the full
404    // `name@version` form (otherwise unrelated same-version packages
405    // would false-positive as back-references).
406    let result = if options.dedupe_peers {
407        dedupe_peer_suffixes(current)
408    } else {
409        current
410    };
411    Ok(result)
412}
413
414/// Cross-subtree peer-variant dedupe. When `dedupe-peer-dependents` is
415/// on, packages that landed at different contextualized dep_paths but
416/// resolved every declared peer to the *same* version (ignoring the
417/// nested peer suffix on each peer tail) collapse into a single
418/// canonical variant — chosen as the lexicographically smallest key in
419/// the equivalence class. References in every surviving
420/// `LockedPackage.dependencies` map and every `importers[*]` direct
421/// dep get rewritten through the old→canonical map, and the
422/// non-canonical entries are dropped from `packages`.
423///
424/// Packages whose `peer_dependencies` map is empty — i.e. the canonical
425/// base already has only one variant — are skipped.
426pub(crate) fn dedupe_peer_variants(graph: LockfileGraph) -> LockfileGraph {
427    let canonical_base = |key: &str| -> String { canonical_tail(key).to_string() };
428    // Only the peer-bearing part of the resolved peer tail is
429    // comparable across subtrees — the nested suffix could differ even
430    // for peer-equivalent variants on mid-iterations of the outer
431    // fixed-point loop.
432    let peer_base = |tail: &str| -> String { canonical_tail(tail).to_string() };
433
434    // Group dep_paths by their peer-free base name.
435    let mut groups: BTreeMap<String, Vec<String>> = BTreeMap::new();
436    for key in graph.packages.keys() {
437        groups
438            .entry(canonical_base(key))
439            .or_default()
440            .push(key.clone());
441    }
442
443    let mut rewrite: BTreeMap<String, String> = BTreeMap::new();
444    for (_base, mut keys) in groups {
445        if keys.len() < 2 {
446            continue;
447        }
448        // Deterministic order for canonical selection + stable hashing.
449        keys.sort();
450        // Union-find over equivalence classes. Two variants are
451        // equivalent when each declared peer name resolves to the same
452        // peer base in both (or is missing from both).
453        let mut parent: Vec<usize> = (0..keys.len()).collect();
454        fn find(parent: &mut [usize], i: usize) -> usize {
455            if parent[i] == i {
456                i
457            } else {
458                let r = find(parent, parent[i]);
459                parent[i] = r;
460                r
461            }
462        }
463        for i in 0..keys.len() {
464            for j in (i + 1)..keys.len() {
465                let pa = &graph.packages[&keys[i]];
466                let pb = &graph.packages[&keys[j]];
467                // Same canonical version is required — packages with
468                // different versions but the same name would share no
469                // canonical_base only if the name-without-version
470                // collided, which doesn't happen (version is in the
471                // base). Still, belt-and-suspenders.
472                if pa.version != pb.version {
473                    continue;
474                }
475                let peer_names: BTreeSet<&String> = pa
476                    .peer_dependencies
477                    .keys()
478                    .chain(pb.peer_dependencies.keys())
479                    .collect();
480                let equivalent = peer_names.iter().all(|name| {
481                    match (
482                        pa.dependencies.get(name.as_str()),
483                        pb.dependencies.get(name.as_str()),
484                    ) {
485                        (Some(va), Some(vb)) => peer_base(va) == peer_base(vb),
486                        (None, None) => true,
487                        _ => false,
488                    }
489                });
490                if equivalent {
491                    let ri = find(&mut parent, i);
492                    let rj = find(&mut parent, j);
493                    if ri != rj {
494                        parent[ri] = rj;
495                    }
496                }
497            }
498        }
499        // Build class → canonical (smallest key) mapping. Using
500        // index-based iteration here because `find` takes a mutable
501        // reference into `parent`, so holding an immutable borrow
502        // from `keys.iter()` at the same time would double-borrow.
503        #[allow(clippy::needless_range_loop)]
504        {
505            let mut class_rep: BTreeMap<usize, String> = BTreeMap::new();
506            for i in 0..keys.len() {
507                let root = find(&mut parent, i);
508                class_rep
509                    .entry(root)
510                    .and_modify(|cur| {
511                        if keys[i] < *cur {
512                            *cur = keys[i].clone();
513                        }
514                    })
515                    .or_insert_with(|| keys[i].clone());
516            }
517            for i in 0..keys.len() {
518                let root = find(&mut parent, i);
519                let canonical = class_rep[&root].clone();
520                if keys[i] != canonical {
521                    rewrite.insert(keys[i].clone(), canonical);
522                }
523            }
524        }
525    }
526
527    if rewrite.is_empty() {
528        return graph;
529    }
530
531    // Rewrite package dependency tails and keep only canonicals.
532    let LockfileGraph {
533        importers,
534        packages,
535        settings,
536        overrides,
537        ignored_optional_dependencies,
538        times,
539        skipped_optional_dependencies,
540        catalogs,
541        bun_config_version,
542        patched_dependencies,
543        trusted_dependencies,
544        extra_fields,
545        workspace_extra_fields,
546    } = graph;
547
548    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
549    for (key, mut pkg) in packages {
550        if rewrite.contains_key(&key) {
551            continue;
552        }
553        for (dep_name, dep_tail) in pkg.dependencies.iter_mut() {
554            let dep_key = format!("{dep_name}@{dep_tail}");
555            if let Some(canonical) = rewrite.get(&dep_key) {
556                let new_tail = canonical
557                    .strip_prefix(&format!("{dep_name}@"))
558                    .map(|s| s.to_string())
559                    .unwrap_or_else(|| canonical.clone());
560                *dep_tail = new_tail;
561            }
562        }
563        new_packages.insert(key, pkg);
564    }
565
566    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
567    for (importer_path, deps) in importers {
568        let mut new_deps = Vec::with_capacity(deps.len());
569        for mut dep in deps {
570            if let Some(canonical) = rewrite.get(&dep.dep_path) {
571                dep.dep_path = canonical.clone();
572            }
573            new_deps.push(dep);
574        }
575        new_importers.insert(importer_path, new_deps);
576    }
577
578    LockfileGraph {
579        importers: new_importers,
580        packages: new_packages,
581        settings,
582        overrides,
583        ignored_optional_dependencies,
584        times,
585        skipped_optional_dependencies,
586        catalogs,
587        bun_config_version,
588        patched_dependencies,
589        trusted_dependencies,
590        extra_fields,
591        workspace_extra_fields,
592    }
593}
594
595/// Single pass of the peer-context computation. See `apply_peer_contexts`
596/// for the wrapping fixed-point loop.
597///
598/// Algorithm per visited package P, reached at some point in a DFS from an
599/// importer with `ancestor_scope: name -> dep_path_tail`:
600///
601///  1. For each peer name declared by P, look it up in `ancestor_scope`
602///     (nearest-ancestor-wins, since the scope is rebuilt per recursion).
603///     If missing, fall back to P's own entry in `dependencies` — the BFS
604///     enqueue auto-installed it as a transitive, matching pnpm's
605///     `auto-install-peers=true` default.
606///  2. Sort the (peer_name, resolution) pairs and serialize as
607///     `(n1@v1)(n2@v2)…` for the suffix.
608///  3. Produce a contextualized dep_path `name@version{suffix}`. If that
609///     key is already in `out_packages` (or currently on the DFS stack via
610///     `visiting`), short-circuit — we've already emitted this variant.
611///  4. Build a new scope for P's children by merging the ancestor scope
612///     with P's own `dependencies` and the resolved peer map. Recurse.
613///  5. Emit the contextualized LockedPackage.
614///
615/// Cycles: protected by `visiting` — if a package is re-entered via a
616/// dependency cycle, we return the already-computed dep_path without
617/// recursing again. The peer context is fixed at first visit; any cycle
618/// traversal uses whatever context was live at that first visit.
619fn apply_peer_contexts_once(
620    canonical: LockfileGraph,
621    options: &PeerContextOptions,
622) -> LockfileGraph {
623    let mut out_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
624    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
625
626    // Name-indexed view of the canonical graph, shared across
627    // every `visit_peer_context` call in this pass. Peer-resolution
628    // scan-by-name is the resolver's hottest inner loop. Without
629    // this, each peer runs `O(|graph|)` per package per fixed-point
630    // iter. Prebuilt index drops the scan to O(1) average.
631    //
632    // Pre-size to the package count: most graphs have one entry per
633    // name and only a handful of multi-version names, so capacity
634    // headroom is small and the upper bound saves 8+ rehashes on
635    // medium graphs (default 16 → 2048 covers ~1200 pkgs).
636    let mut name_index: FxHashMap<&str, Vec<&LockedPackage>> =
637        FxHashMap::with_capacity_and_hasher(canonical.packages.len(), Default::default());
638    for pkg in canonical.packages.values() {
639        name_index.entry(pkg.name.as_str()).or_default().push(pkg);
640    }
641
642    // Root-importer scope used by `resolve-peers-from-workspace-root`.
643    // Computed once from the canonical input so it reflects the
644    // contextualized state of every root dep on fixed-point iterations
645    // 2+ — same logic as per-importer `importer_scope` below.
646    let root_scope: FxHashMap<String, String> = canonical
647        .importers
648        .get(".")
649        .map(|deps| scope_map_from_deps(deps))
650        .unwrap_or_default();
651
652    for (importer_path, direct_deps) in &canonical.importers {
653        // An importer's own direct deps are in scope for its children's
654        // peer resolution — this is how pnpm's "auto-install at the root"
655        // path gets peer links that point at root-level packages.
656        //
657        // Use the *full contextualized tail* off each DirectDep rather
658        // than the package's plain version. On Pass 1 of the fixed-point
659        // loop the tail is canonical and equal to `p.version`; on Pass 2+
660        // it's already contextualized, and passing the plain version
661        // would make descendants look up keys that don't exist in the
662        // (now-nested) graph.
663        let importer_scope = scope_map_from_deps(direct_deps);
664
665        let mut new_deps = Vec::with_capacity(direct_deps.len());
666        for dep in direct_deps {
667            // `visiting` is the DFS stack guard for this particular descent
668            // — reset per direct dep so we don't incorrectly flag a package
669            // as a cycle when it's reached again from a sibling subtree.
670            // The shared `out_packages` still dedupes across siblings since
671            // the second visit hits the `contains_key` short-circuit below.
672            //
673            // Invariant (see `visit_peer_context` for the detailed handling):
674            // a dep_path returned from the cycle-break branch may not yet
675            // be present in `out_packages` at the moment of return, because
676            // the package is still being assembled up the call stack. The
677            // parent that records the returned tail will complete its own
678            // insertion before the recursion unwinds, so by the time
679            // anything reads the graph, every referenced dep_path exists.
680            let mut visiting: FxHashSet<String> = FxHashSet::default();
681            let new_dep_path = visit_peer_context(
682                &dep.dep_path,
683                &canonical,
684                &name_index,
685                &importer_scope,
686                &root_scope,
687                &mut out_packages,
688                &mut visiting,
689                options,
690            )
691            .unwrap_or_else(|| dep.dep_path.clone());
692            new_deps.push(DirectDep {
693                name: dep.name.clone(),
694                dep_path: new_dep_path,
695                dep_type: dep.dep_type,
696                specifier: dep.specifier.clone(),
697            });
698        }
699        new_importers.insert(importer_path.clone(), new_deps);
700    }
701
702    // Any canonical package that was never reached by the DFS (orphaned
703    // from every importer) is dropped — that matches the filter_deps
704    // semantics and avoids emitting dead entries into the lockfile.
705
706    LockfileGraph {
707        importers: new_importers,
708        packages: out_packages,
709        // The post-pass is pure — settings + overrides carry through
710        // from the input graph untouched.
711        settings: canonical.settings,
712        overrides: canonical.overrides,
713        ignored_optional_dependencies: canonical.ignored_optional_dependencies,
714        times: canonical.times,
715        skipped_optional_dependencies: canonical.skipped_optional_dependencies,
716        catalogs: canonical.catalogs,
717        bun_config_version: canonical.bun_config_version,
718        patched_dependencies: canonical.patched_dependencies,
719        trusted_dependencies: canonical.trusted_dependencies,
720        extra_fields: canonical.extra_fields,
721        workspace_extra_fields: canonical.workspace_extra_fields,
722    }
723}
724
725/// DFS helper for `apply_peer_contexts`. Returns the peer-contextualized
726/// dep_path of the visited package, or `None` if the canonical package is
727/// missing (shouldn't happen in practice but we degrade gracefully).
728/// Does `value` contain a peer-suffix reference to `canonical` as a
729/// proper name@version boundary (i.e. preceded by `(` and followed by
730/// `(` / `)` / end-of-string)? Used by the peer-context pass to detect
731/// when a nested tail loops back to the current package so it can
732/// short-circuit the chain instead of growing the suffix forever.
733/// If `s` ends with `_<10 lowercase hex>` (the marker written by
734/// `hash_peer_suffix`), strip it and return the prefix. Otherwise
735/// return `s` unchanged.
736///
737/// Safe against false positives: `s` here is always a post-split
738/// `name@version` base, and semver forbids `_` inside a version, so
739/// an underscore 10 chars from the end of `name@version` can only be
740/// our marker.
741/// Everything before the first `(` — i.e. the canonical `name@version`
742/// part of a dep-path with the peer-context suffix stripped. Returns
743/// the original string when no `(` is present. Borrowed; callers that
744/// need owned bump with `.to_string()`.
745fn canonical_tail(s: &str) -> &str {
746    s.split('(').next().unwrap_or(s)
747}
748
749/// Build a `name → contextualized tail` map from a direct-dep slice.
750/// The tail is the dep_path with the `{name}@` prefix stripped, which
751/// on pass 1 is equal to `pkg.version` and on pass 2+ carries the
752/// nested peer-context suffix. Used both for the root scope and for
753/// each importer's own scope inside `apply_peer_contexts_once`.
754fn scope_map_from_deps(deps: &[DirectDep]) -> FxHashMap<String, String> {
755    let mut out = FxHashMap::with_capacity_and_hasher(deps.len(), Default::default());
756    for d in deps {
757        let prefix_len = d.name.len() + 1;
758        let tail = if d.dep_path.len() > prefix_len
759            && d.dep_path.as_bytes().get(d.name.len()) == Some(&b'@')
760            && d.dep_path.as_bytes().starts_with(d.name.as_bytes())
761        {
762            d.dep_path[prefix_len..].to_string()
763        } else {
764            d.dep_path.clone()
765        };
766        out.insert(d.name.clone(), tail);
767    }
768    out
769}
770
771fn strip_hashed_peer_suffix(s: &str) -> &str {
772    const MARKER_LEN: usize = 11; // `_` + 10 hex chars
773    if s.len() < MARKER_LEN {
774        return s;
775    }
776    let tail = &s[s.len() - MARKER_LEN..];
777    if !tail.starts_with('_') {
778        return s;
779    }
780    if tail[1..]
781        .chars()
782        .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
783    {
784        &s[..s.len() - MARKER_LEN]
785    } else {
786        s
787    }
788}
789
790/// Hash a peer-ID suffix with SHA-256 and return `_<10-char-hex>`.
791/// Used by the peer-context pass when the raw suffix length exceeds
792/// `peersSuffixMaxLength`. Matches pnpm's format so lockfile dep_path
793/// keys stay portable.
794pub(crate) fn hash_peer_suffix(suffix: &str) -> String {
795    use sha2::{Digest, Sha256};
796    let digest = Sha256::digest(suffix.as_bytes());
797    let mut out = String::with_capacity(11);
798    out.push('_');
799    for byte in digest.iter().take(5) {
800        use std::fmt::Write;
801        let _ = write!(out, "{byte:02x}");
802    }
803    out
804}
805
806pub(crate) fn contains_canonical_back_ref(value: &str, canonical: &str) -> bool {
807    let bytes = value.as_bytes();
808    let target = canonical.as_bytes();
809    if target.is_empty() || target.len() > bytes.len() {
810        return false;
811    }
812    let mut i = 0;
813    while i + target.len() <= bytes.len() {
814        if &bytes[i..i + target.len()] == target {
815            let before = if i == 0 { b'\0' } else { bytes[i - 1] };
816            let after = bytes.get(i + target.len()).copied().unwrap_or(b'\0');
817            let before_ok = before == b'(';
818            let after_ok = after == b'(' || after == b')' || after == b'\0';
819            if before_ok && after_ok {
820                return true;
821            }
822        }
823        i += 1;
824    }
825    false
826}
827
828/// Split a dep_path tail's peer suffix into outer-level paren segments
829/// (each ending in a balanced `)`). Returns each segment with its parens
830/// included — `react-dom@18.2.0(react@18.2.0)(scheduler@1.0.0)` yields
831/// `["(react@18.2.0)", "(scheduler@1.0.0)"]`; nested forms like
832/// `consumer@1.0.0(react-dom@18.2.0(react@18.2.0))` yield the single
833/// segment `["(react-dom@18.2.0(react@18.2.0))"]` with the inner
834/// `(react@18.2.0)` preserved verbatim inside it.
835///
836/// Used by `propagate_peer_suffixes_to_ancestors` to lift a child's
837/// peer segments onto its non-peer-declaring ancestors.
838fn outer_paren_segments(s: &str) -> Vec<&str> {
839    let bytes = s.as_bytes();
840    let mut segments = Vec::new();
841    let mut i = 0;
842    // Skip canonical `name@version` head — anything up to the first `(`.
843    while i < bytes.len() && bytes[i] != b'(' {
844        i += 1;
845    }
846    while i < bytes.len() {
847        if bytes[i] != b'(' {
848            i += 1;
849            continue;
850        }
851        let start = i;
852        let mut depth: i32 = 0;
853        while i < bytes.len() {
854            match bytes[i] {
855                b'(' => depth += 1,
856                b')' => {
857                    depth -= 1;
858                    if depth == 0 {
859                        i += 1;
860                        segments.push(&s[start..i]);
861                        break;
862                    }
863                }
864                _ => {}
865            }
866            i += 1;
867        }
868        if depth != 0 {
869            // Unbalanced — bail out of further segmenting. Shouldn't
870            // happen on output of `apply_peer_contexts_once`, where every
871            // suffix segment is balanced by construction.
872            break;
873        }
874    }
875    segments
876}
877
878/// Extract the peer name from a paren segment like `(@scope/name@1.2.3)`
879/// or `(name@1.2.3(nested@9.9.9))`. The peer name is everything between
880/// the opening `(` and the LAST `@` that occurs before any nested `(`.
881/// Scoped packages contain two `@`s (`@scope/name@version`) and we want
882/// the rightmost outer one.
883///
884/// Returns `None` if the segment doesn't start with `(` or has no
885/// usable `@` separator.
886fn peer_name_from_segment(seg: &str) -> Option<&str> {
887    let inner = seg.strip_prefix('(')?;
888    // Scan for the last `@` that occurs before any `(` (the version-or-
889    // nested boundary). For a flat segment `name@version` everything
890    // between `(` and the last `@` is the name; for a nested segment
891    // `name@version(inner)` the last `@` BEFORE the first inner `(` is
892    // the boundary. We search up to the first `(` (or end-of-string).
893    let scan_end = inner.find('(').unwrap_or(inner.len());
894    let head = &inner[..scan_end];
895    head.rfind('@').map(|idx| &head[..idx])
896}
897
898/// Collect every peer name reachable from a set of outer-paren segments,
899/// recursing into nested `(name@version(...))` forms so that a self
900/// segment like `(helper@1.0.0(core@1.0.0))` reports both `helper` and
901/// `core`. Used by `propagate_peer_suffixes_to_ancestors` to suppress
902/// flat-segment additions for peer names already encoded transitively
903/// in a package's own (possibly nested) self-suffix.
904fn peer_names_in_segments_recursive(segments: &[&str]) -> BTreeSet<String> {
905    let mut names = BTreeSet::new();
906    for seg in segments {
907        if let Some(name) = peer_name_from_segment(seg) {
908            names.insert(name.to_string());
909        }
910        // Recurse into the nested portion (everything after the first
911        // inner `(` and before the final `)`).
912        let Some(inner) = seg.strip_prefix('(').and_then(|s| s.strip_suffix(')')) else {
913            continue;
914        };
915        if let Some(open) = inner.find('(') {
916            let nested = &inner[open..];
917            let nested_segments = outer_paren_segments(nested);
918            for nested_name in peer_names_in_segments_recursive(&nested_segments) {
919                names.insert(nested_name);
920            }
921        }
922    }
923    names
924}
925
926/// Walk the resolved graph from each node and accumulate the union of
927/// peer-suffix segments contributed by self + every reachable
928/// descendant (gated on the package having no declared peers of its
929/// own), then rewrite each node's dep_path to embed that union.
930///
931/// Why: pnpm's lockfile shape tags non-peer-declaring intermediaries
932/// with the same `(peer@version)` suffix their peer-declaring
933/// descendants produced — so a parent that pulls in a peer-bearing
934/// child carries the resolved peer set on its own dep_path. aube's
935/// `apply_peer_contexts_once` only emits the suffix on the package
936/// that *declares* the peer; without this post-pass an importer row
937/// for `parent → leaf(peer)` would render `parent: 1.0.0` (no
938/// suffix) where pnpm renders `parent: 1.0.0(peer@v)`.
939///
940/// pnpm-parity gate (inferred from observed lockfile shape): **a
941/// package gets descendant-peer propagation only if its own
942/// `peerDependencies` map is empty.** Packages that declare their
943/// own peers have an authoritative self-suffix encoding exactly the
944/// peers they care about; descendant peers don't bubble through
945/// because the descendant peers belong to a NESTED child, which the
946/// snapshot already encodes via the nested-tail form (see
947/// `apply_peer_contexts_once`'s nested-suffix handling). Two
948/// observable shapes this gate lines up with:
949///   - `@testing-library/react@14.0.0(react@18.2.0)(react-dom@18.2.0(react@18.2.0))`
950///     — declares peers, gets self-suffix only; `@types/react` from a
951///     descendant doesn't bubble up.
952///   - `abc-parent-with-missing-peers@1.0.0(peer-a@…)(peer-b@…)(peer-c@…)`
953///     — no declared peers, picks up descendant peers from `abc`.
954///
955/// Algorithm:
956///  1. Build a forward dep map: `pkg_key → [child_key]` from each
957///     LockedPackage's `dependencies`.
958///  2. Memoized DFS. For each node, compute
959///     `cumulative_segments = outer_paren_segments(node.key)`. If the
960///     node has no declared peers, also union in
961///     `⋃ cumulative(child)` (gated by the rule above).
962///  3. Cycles short-circuit via a `visiting` guard — cycle members
963///     can't add new peers from each other beyond what reaches them
964///     through non-cycle paths, so returning the empty set on
965///     re-entry is safe (the non-cycle entry path computes the full
966///     set).
967///  4. Dedupe by peer name. Suppressed names: every peer name reachable
968///     transitively in self-segments (so `(helper@1(core@1))` covers
969///     `core` and a flat `(core@1)` from descendants is dropped) plus
970///     the package's own canonical name (mutual-peer cycle break).
971///  5. Build a rewrite map `old_key → new_key` and apply to package
972///     keys, dep edges (each dep's stored tail), and importer
973///     dep_paths.
974fn propagate_peer_suffixes_to_ancestors(
975    graph: LockfileGraph,
976    options: &PeerContextOptions,
977) -> LockfileGraph {
978    // Forward dep map. Edges that don't resolve to a present package
979    // (e.g. an unresolved peer that `detect_unmet_peers` will warn
980    // about) are dropped — they can't contribute cumulative peers.
981    let mut forward: BTreeMap<String, Vec<String>> = BTreeMap::new();
982    // Per-package "has declared peers" lookup. Packages that declare
983    // their own peers don't accept descendant-peer propagation (see
984    // the rule in the doc comment above).
985    let mut has_own_peers: BTreeMap<String, bool> = BTreeMap::new();
986    for (key, pkg) in &graph.packages {
987        let children: Vec<String> = pkg
988            .dependencies
989            .iter()
990            .map(|(n, t)| format!("{n}@{t}"))
991            .filter(|k| graph.packages.contains_key(k))
992            .collect();
993        forward.insert(key.clone(), children);
994        has_own_peers.insert(key.clone(), !pkg.peer_dependencies.is_empty());
995    }
996
997    // Memoized DFS. `cumulative` stores the by-name segment map per
998    // package key; `visiting` is the cycle-break stack.
999    let mut cumulative: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
1000    let mut visiting: BTreeSet<String> = BTreeSet::new();
1001
1002    fn collect(
1003        key: &str,
1004        forward: &BTreeMap<String, Vec<String>>,
1005        has_own_peers: &BTreeMap<String, bool>,
1006        cumulative: &mut BTreeMap<String, BTreeMap<String, String>>,
1007        visiting: &mut BTreeSet<String>,
1008    ) -> BTreeMap<String, String> {
1009        if let Some(c) = cumulative.get(key) {
1010            return c.clone();
1011        }
1012        if !visiting.insert(key.to_string()) {
1013            // Cycle: contribute nothing. Whichever cycle member is
1014            // first reached from outside the cycle will compute the
1015            // full set; the visit guard cap on the others prevents
1016            // infinite recursion. Edge case: a fully-isolated cycle
1017            // never gets a non-cycle entry, in which case all members
1018            // compute empty cumulatives — that's identical to their
1019            // canonical state, so they get no rewrite. Acceptable.
1020            return BTreeMap::new();
1021        }
1022
1023        // Self-suffix segments. Each segment becomes one (name → segment)
1024        // entry. Nested segments like `(react-dom@18.2.0(react@18.2.0))`
1025        // are preserved as a single segment with the nested form intact.
1026        let self_segments = outer_paren_segments(key);
1027        let mut acc: BTreeMap<String, String> = BTreeMap::new();
1028        for seg in &self_segments {
1029            if let Some(name) = peer_name_from_segment(seg) {
1030                acc.entry(name.to_string())
1031                    .or_insert_with(|| seg.to_string());
1032            }
1033        }
1034
1035        // Pnpm-parity gate: only packages with no declared peers absorb
1036        // descendant-peer propagation. The cycle-break visiting guard
1037        // is still released for symmetry with the non-gated branch.
1038        if has_own_peers.get(key).copied().unwrap_or(false) {
1039            visiting.remove(key);
1040            cumulative.insert(key.to_string(), acc.clone());
1041            return acc;
1042        }
1043
1044        // Names suppressed when merging child contributions:
1045        //   1. Every peer name reachable transitively in self segments —
1046        //      e.g. a self segment `(helper@1.0.0(core@1.0.0))` covers
1047        //      both `helper` and `core`, so a descendant flat-listing
1048        //      `(core@1.0.0)` shouldn't double-emit. Pnpm lists each
1049        //      peer name once; we match.
1050        //   2. The package's own canonical name — for mutual-peer
1051        //      cycles `a` peers on `b` and `b` peers on `a`, the
1052        //      descendant set lifts `(a@…)` back up onto `a` itself,
1053        //      which would write `a@1.0.0(a@…)(b@…)`. Self-listing
1054        //      isn't valid pnpm shape; suppress it. (Reachable here
1055        //      only when this branch handles a node with no declared
1056        //      peers — but defensive in case future graph shapes
1057        //      surface a self-cycle through a peer-less node.)
1058        let canonical_name = canonical_tail(key)
1059            .rsplit_once('@')
1060            .map(|(name, _ver)| name.to_string())
1061            .unwrap_or_default();
1062        let mut suppressed: BTreeSet<String> = peer_names_in_segments_recursive(&self_segments);
1063        if !canonical_name.is_empty() {
1064            suppressed.insert(canonical_name);
1065        }
1066
1067        // Child contributions.
1068        if let Some(children) = forward.get(key) {
1069            for child in children {
1070                let child_peers = collect(child, forward, has_own_peers, cumulative, visiting);
1071                for (name, seg) in child_peers {
1072                    if suppressed.contains(&name) {
1073                        continue;
1074                    }
1075                    acc.entry(name).or_insert(seg);
1076                }
1077            }
1078        }
1079        visiting.remove(key);
1080        cumulative.insert(key.to_string(), acc.clone());
1081        acc
1082    }
1083
1084    // Compute cumulative for every package + every importer DirectDep
1085    // root. Done in stable order so the lex-smaller old-key tiebreaker
1086    // below is deterministic.
1087    let pkg_keys: Vec<String> = graph.packages.keys().cloned().collect();
1088    for key in &pkg_keys {
1089        collect(
1090            key,
1091            &forward,
1092            &has_own_peers,
1093            &mut cumulative,
1094            &mut visiting,
1095        );
1096    }
1097    for deps in graph.importers.values() {
1098        for dep in deps {
1099            collect(
1100                &dep.dep_path,
1101                &forward,
1102                &has_own_peers,
1103                &mut cumulative,
1104                &mut visiting,
1105            );
1106        }
1107    }
1108
1109    // Build rewrite map. A package's new key is its canonical_base
1110    // (`name@version`) plus the cumulative segments concatenated in
1111    // peer-name lex order — same order `apply_peer_contexts_once`
1112    // already produces for self segments, so when a package's
1113    // cumulative is identical to its self set the rewrite is a no-op
1114    // and we skip it.
1115    //
1116    // Hashed-suffix keys (`name@version_<10hex>`, produced when a
1117    // package's own peer suffix exceeded `peersSuffixMaxLength`) are
1118    // left untouched. The hash form discards the textual peer set
1119    // by design — `outer_paren_segments` can't recover its
1120    // contribution, so any rewrite we built for it would either drop
1121    // the hash entirely (losing identity) or merge an incomplete
1122    // descendant set with the hashed self. Preserving the original
1123    // form is the conservative choice; pnpm's parity gap in that
1124    // regime is bounded by the hash collision space anyway.
1125    //
1126    // If the propagated suffix itself exceeds the cap, hash it the
1127    // same way `visit_peer_context` does for self suffixes — keeps
1128    // dep_path keys bounded across the whole graph.
1129    let mut rewrite: BTreeMap<String, String> = BTreeMap::new();
1130    for key in &pkg_keys {
1131        let Some(segments) = cumulative.get(key) else {
1132            continue;
1133        };
1134        let original_tail = canonical_tail(key);
1135        let canonical = strip_hashed_peer_suffix(original_tail);
1136        if canonical.len() != original_tail.len() {
1137            // Original key already has the hashed marker. Skip — see
1138            // comment above.
1139            continue;
1140        }
1141        let suffix: String = segments.values().cloned().collect();
1142        let effective_suffix = if suffix.len() > options.peers_suffix_max_length {
1143            hash_peer_suffix(&suffix)
1144        } else {
1145            suffix
1146        };
1147        let new_key = format!("{canonical}{effective_suffix}");
1148        if new_key != *key {
1149            rewrite.insert(key.clone(), new_key);
1150        }
1151    }
1152
1153    if rewrite.is_empty() {
1154        return graph;
1155    }
1156
1157    // Helper: rewrite a `dependencies` tail (the part after `name@`).
1158    // Reconstruct the target's old full key, look up its rewrite, and
1159    // strip the `name@` prefix off the result to recover the new tail.
1160    // Targets without a rewrite keep the original tail.
1161    let rewrite_tail = |child_name: &str, tail: &str| -> String {
1162        let old_key = format!("{child_name}@{tail}");
1163        match rewrite.get(&old_key) {
1164            Some(new_key) => new_key
1165                .strip_prefix(&format!("{child_name}@"))
1166                .map(|s| s.to_string())
1167                .unwrap_or_else(|| tail.to_string()),
1168            None => tail.to_string(),
1169        }
1170    };
1171
1172    let LockfileGraph {
1173        importers,
1174        packages,
1175        settings,
1176        overrides,
1177        ignored_optional_dependencies,
1178        times,
1179        skipped_optional_dependencies,
1180        catalogs,
1181        bun_config_version,
1182        patched_dependencies,
1183        trusted_dependencies,
1184        extra_fields,
1185        workspace_extra_fields,
1186    } = graph;
1187
1188    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
1189    for (old_key, mut pkg) in packages {
1190        let new_key = rewrite.get(&old_key).cloned().unwrap_or(old_key);
1191        for (name, tail) in pkg.dependencies.iter_mut() {
1192            *tail = rewrite_tail(name, tail);
1193        }
1194        for (name, tail) in pkg.optional_dependencies.iter_mut() {
1195            *tail = rewrite_tail(name, tail);
1196        }
1197        pkg.dep_path = new_key.clone();
1198        // Two old keys mapping to one new key: the lex-smaller old key
1199        // wins. Because `packages` is a `BTreeMap` we iterate
1200        // `(old_key, pkg)` pairs in lex order — the first insertion
1201        // for any given `new_key` is therefore the one whose old_key
1202        // sorts lowest, and `or_insert` makes every subsequent
1203        // collision a no-op. Bodies are equal in the common case
1204        // anyway (same canonical_base + same cumulative ⇒ same dep
1205        // tree), so this is effectively cosmetic determinism.
1206        new_packages.entry(new_key).or_insert(pkg);
1207    }
1208
1209    let new_importers: BTreeMap<String, Vec<DirectDep>> = importers
1210        .into_iter()
1211        .map(|(path, deps)| {
1212            let rewritten = deps
1213                .into_iter()
1214                .map(|d| {
1215                    let new_dep_path = rewrite.get(&d.dep_path).cloned().unwrap_or(d.dep_path);
1216                    DirectDep {
1217                        name: d.name,
1218                        dep_path: new_dep_path,
1219                        dep_type: d.dep_type,
1220                        specifier: d.specifier,
1221                    }
1222                })
1223                .collect();
1224            (path, rewritten)
1225        })
1226        .collect();
1227
1228    LockfileGraph {
1229        importers: new_importers,
1230        packages: new_packages,
1231        settings,
1232        overrides,
1233        ignored_optional_dependencies,
1234        times,
1235        skipped_optional_dependencies,
1236        catalogs,
1237        bun_config_version,
1238        patched_dependencies,
1239        trusted_dependencies,
1240        extra_fields,
1241        workspace_extra_fields,
1242    }
1243}
1244
1245/// Dedupe-peers post-pass: strip the `name@` prefix from every
1246/// parenthesized peer segment in every dep_path key and reference,
1247/// turning `react-dom@18.2.0(react@18.2.0)` into
1248/// `react-dom@18.2.0(18.2.0)`. Nested segments get the same treatment
1249/// so `a@1(b@2(c@3))` becomes `a@1(2(3))`.
1250///
1251/// Running this as a final post-pass (instead of inline during suffix
1252/// assembly in `visit_peer_context`) keeps cycle detection correct:
1253/// the detection path works against the full `name@version` form
1254/// throughout the fixed-point loop, and only the serialized output
1255/// gets the shorter form. A version-only inline approach would
1256/// false-positive on unrelated packages that coincidentally share a
1257/// version with the current package's canonical base.
1258///
1259/// Pure: no-op when `dedupe_peers` is off (caller gates the call);
1260/// otherwise rewrites every package key, every `LockedPackage.dep_path`
1261/// and `LockedPackage.dependencies` value, and every `importers[*]`
1262/// DirectDep `dep_path` through the same `apply_dedupe_peers_to_tail`
1263/// helper. Package bodies (integrity, metadata, etc.) are cloned
1264/// verbatim.
1265pub(crate) fn dedupe_peer_suffixes(graph: LockfileGraph) -> LockfileGraph {
1266    // Pass 1: compute the intended deduped key for each package and
1267    // tally how many distinct full-form keys map to it. Stripping
1268    // `name@` from suffix segments is lossy — two variants whose peer
1269    // *names* differ but whose peer *versions* coincide would collapse
1270    // onto the same deduped key (e.g. `consumer@1.0.0(foo@1.0.0)` and
1271    // `consumer@1.0.0(bar@1.0.0)` both → `consumer@1.0.0(1.0.0)`).
1272    // `dedupe_peer_variants` already merged the peer-equivalent
1273    // duplicates, so any remaining collision here represents genuinely
1274    // distinct variants — losing one would silently drop its
1275    // dependency wiring. We detect those collisions and keep both
1276    // sides in full form.
1277    let mut target_counts: BTreeMap<String, usize> = BTreeMap::new();
1278    let mut intended: BTreeMap<String, String> = BTreeMap::new();
1279    for key in graph.packages.keys() {
1280        let new_key = apply_dedupe_peers_to_key(key);
1281        *target_counts.entry(new_key.clone()).or_insert(0) += 1;
1282        intended.insert(key.clone(), new_key);
1283    }
1284    let rewrite: BTreeMap<String, String> = intended
1285        .into_iter()
1286        .map(|(old, new)| {
1287            if target_counts.get(&new).copied().unwrap_or(0) > 1 {
1288                tracing::warn!(
1289                    code = aube_codes::warnings::WARN_AUBE_PEER_DEDUPE_COLLISION,
1290                    "dedupe-peers: collision on {new} — keeping {old} in full form to avoid \
1291                     dropping a distinct peer-variant"
1292                );
1293                (old.clone(), old)
1294            } else {
1295                (old, new)
1296            }
1297        })
1298        .collect();
1299
1300    // Rewrite a `(child_name, tail)` reference by reconstructing the
1301    // target's full-form key, looking up its effective rewrite, and
1302    // stripping `child_name@` off the result to recover the tail.
1303    // Tails always follow their target package's rewrite decision,
1304    // so references stay consistent when a collision forces a target
1305    // back to full form.
1306    let rewrite_tail = |child_name: &str, tail: &str| -> String {
1307        let old_key = format!("{child_name}@{tail}");
1308        match rewrite.get(&old_key) {
1309            Some(new_key) => new_key
1310                .strip_prefix(&format!("{child_name}@"))
1311                .map(|s| s.to_string())
1312                .unwrap_or_else(|| tail.to_string()),
1313            None => apply_dedupe_peers_to_tail(tail),
1314        }
1315    };
1316
1317    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
1318    for (old_key, pkg) in graph.packages {
1319        let new_key = rewrite
1320            .get(&old_key)
1321            .cloned()
1322            .unwrap_or_else(|| old_key.clone());
1323        let new_dependencies: BTreeMap<String, String> = pkg
1324            .dependencies
1325            .into_iter()
1326            .map(|(n, v)| {
1327                let new_v = rewrite_tail(&n, &v);
1328                (n, new_v)
1329            })
1330            .collect();
1331        let new_optional_dependencies: BTreeMap<String, String> = pkg
1332            .optional_dependencies
1333            .into_iter()
1334            .map(|(n, v)| {
1335                let new_v = rewrite_tail(&n, &v);
1336                (n, new_v)
1337            })
1338            .collect();
1339        new_packages.insert(
1340            new_key.clone(),
1341            LockedPackage {
1342                name: pkg.name,
1343                version: pkg.version,
1344                integrity: pkg.integrity,
1345                dependencies: new_dependencies,
1346                optional_dependencies: new_optional_dependencies,
1347                peer_dependencies: pkg.peer_dependencies,
1348                peer_dependencies_meta: pkg.peer_dependencies_meta,
1349                dep_path: new_key,
1350                local_source: pkg.local_source,
1351                os: pkg.os,
1352                cpu: pkg.cpu,
1353                libc: pkg.libc,
1354                bundled_dependencies: pkg.bundled_dependencies,
1355                optional: pkg.optional,
1356                transitive_peer_dependencies: pkg.transitive_peer_dependencies,
1357                tarball_url: pkg.tarball_url,
1358                alias_of: pkg.alias_of,
1359                yarn_checksum: pkg.yarn_checksum,
1360                engines: pkg.engines,
1361                bin: pkg.bin,
1362                declared_dependencies: pkg.declared_dependencies,
1363                license: pkg.license,
1364                funding_url: pkg.funding_url,
1365                extra_meta: pkg.extra_meta,
1366            },
1367        );
1368    }
1369
1370    let new_importers: BTreeMap<String, Vec<DirectDep>> = graph
1371        .importers
1372        .into_iter()
1373        .map(|(path, deps)| {
1374            let rewritten = deps
1375                .into_iter()
1376                .map(|d| {
1377                    let new_dep_path = rewrite
1378                        .get(&d.dep_path)
1379                        .cloned()
1380                        .unwrap_or_else(|| apply_dedupe_peers_to_key(&d.dep_path));
1381                    DirectDep {
1382                        name: d.name,
1383                        dep_path: new_dep_path,
1384                        dep_type: d.dep_type,
1385                        specifier: d.specifier,
1386                    }
1387                })
1388                .collect();
1389            (path, rewritten)
1390        })
1391        .collect();
1392
1393    LockfileGraph {
1394        importers: new_importers,
1395        packages: new_packages,
1396        settings: graph.settings,
1397        overrides: graph.overrides,
1398        ignored_optional_dependencies: graph.ignored_optional_dependencies,
1399        times: graph.times,
1400        skipped_optional_dependencies: graph.skipped_optional_dependencies,
1401        catalogs: graph.catalogs,
1402        bun_config_version: graph.bun_config_version,
1403        patched_dependencies: graph.patched_dependencies,
1404        trusted_dependencies: graph.trusted_dependencies,
1405        extra_fields: graph.extra_fields,
1406        workspace_extra_fields: graph.workspace_extra_fields,
1407    }
1408}
1409
1410/// Strip `name@` from inside every parenthesized segment of a full
1411/// dep_path key (e.g. `react-dom@18.2.0(react@18.2.0)` →
1412/// `react-dom@18.2.0(18.2.0)`). The first `name@version` outside any
1413/// parens is preserved verbatim — that's the canonical head of the
1414/// dep_path and `dedupe-peers` only affects the peer suffix.
1415pub(crate) fn apply_dedupe_peers_to_key(key: &str) -> String {
1416    let mut parts = key.split('(');
1417    let Some(first) = parts.next() else {
1418        return key.to_string();
1419    };
1420    let mut out = String::with_capacity(key.len());
1421    out.push_str(first);
1422    for part in parts {
1423        out.push('(');
1424        // In a well-formed key, `part` looks like `name@version)` /
1425        // `name@version` / `version)` / ... We strip everything up to
1426        // and including the LAST `@` (scoped packages like
1427        // `@types/react@18.2.0` contain two `@`s; the separator is the
1428        // rightmost one). We only strip if that `@` comes before the
1429        // first `)` or `(` (i.e. the segment actually starts with
1430        // `name@`, not the outer parens closing with no name inside).
1431        if let Some(at_idx) = part.rfind('@') {
1432            let close_idx = part.find([')', '(']).unwrap_or(usize::MAX);
1433            if at_idx < close_idx {
1434                out.push_str(&part[at_idx + 1..]);
1435                continue;
1436            }
1437        }
1438        out.push_str(part);
1439    }
1440    out
1441}
1442
1443/// Same as [`apply_dedupe_peers_to_key`] but for dep-tail values
1444/// stored in `LockedPackage.dependencies` (e.g. `18.2.0(react@18.2.0)`
1445/// → `18.2.0(18.2.0)`). Tails differ from keys only by lacking the
1446/// leading `name@` prefix — both use the same parens-based suffix
1447/// shape, so the algorithm is identical.
1448fn apply_dedupe_peers_to_tail(tail: &str) -> String {
1449    apply_dedupe_peers_to_key(tail)
1450}
1451
1452#[allow(clippy::too_many_arguments)]
1453fn visit_peer_context<'g>(
1454    input_dep_path: &str,
1455    graph: &'g LockfileGraph,
1456    name_index: &FxHashMap<&'g str, Vec<&'g LockedPackage>>,
1457    ancestor_scope: &FxHashMap<String, String>,
1458    root_scope: &FxHashMap<String, String>,
1459    out_packages: &mut BTreeMap<String, LockedPackage>,
1460    visiting: &mut FxHashSet<String>,
1461    options: &PeerContextOptions,
1462) -> Option<String> {
1463    let pkg = graph.packages.get(input_dep_path)?;
1464
1465    // The input key may already carry a peer suffix (fixed-point loop
1466    // Pass 2+). Drop it before we build a new one — otherwise we'd
1467    // append the new suffix on top of the old and grow unboundedly
1468    // across iterations (classic mutual-peer-cycle blow-up).
1469    //
1470    // Two suffix forms can be present from a prior pass:
1471    //   1. `(name@version)(…)` — the normal nested peer suffix. Stripped
1472    //      by splitting on the first `(`.
1473    //   2. `_<10-char-sha256-hex>` — the hashed form produced when the
1474    //      normal suffix exceeded `peersSuffixMaxLength`. Must also be
1475    //      stripped; otherwise each pass re-hashes the already-hashed
1476    //      key and appends another marker (exposed by the
1477    //      `peer_suffix_is_hashed_when_exceeding_cap` unit test).
1478    let canonical_base = canonical_tail(input_dep_path);
1479    let canonical_base = strip_hashed_peer_suffix(canonical_base).to_string();
1480
1481    // Compute peer context: walk declared peers, resolve from ancestors
1482    // (nearest wins — the scope is rebuilt as we recurse) or from the
1483    // package's own dependency map as the auto-install fallback. Both
1484    // sides may produce nested tails on the second and later iterations
1485    // of the fixed-point loop.
1486    // Resolution source priority for each declared peer:
1487    //   1. Ancestor scope — if the ancestor's version actually
1488    //      satisfies the declared peer range. Different subtrees
1489    //      naturally see different ancestors (lib-a in subtree-A
1490    //      and lib-b in subtree-B keep their own peer pins), so
1491    //      preferring the closest ancestor here doesn't conflate
1492    //      cross-subtree variants.
1493    //   2. The current package's own `pkg.dependencies` entry — the
1494    //      BFS peer-walk enqueued this peer with the declared range,
1495    //      so whatever got picked there is guaranteed to satisfy.
1496    //      Captures the case where a single subtree holds two
1497    //      consumers with conflicting peer ranges (lib-a@^17 next to
1498    //      a parent that pins react@18): the BFS auto-installs the
1499    //      satisfying version into lib-a's own deps, which beats the
1500    //      ancestor's incompatible version.
1501    //   3. Ancestor scope — even when the version doesn't satisfy
1502    //      the declared range. This mirrors what Node's module
1503    //      resolution would surface (`require('peer')` from the
1504    //      package would walk up node_modules and find the parent's
1505    //      version). pnpm and bun do the same and emit an unmet-peer
1506    //      warning rather than picking a more-distant matching
1507    //      version. `detect_unmet_peers` flags the mismatch after
1508    //      the pass.
1509    //   4. The current package's own `pkg.dependencies` entry,
1510    //      ignoring range satisfaction — symmetric to (3) for the
1511    //      BFS-installed case.
1512    //   5. Workspace root scope (compatible) — `resolve-peers-from-
1513    //      workspace-root` fallback for monorepos that pin shared
1514    //      peers at the root.
1515    //   6. A graph-wide scan: any package whose name matches and
1516    //      whose version satisfies the declared range. Last resort
1517    //      for nested-context callers when nothing closer has it.
1518    //   7. Workspace root scope, ignoring range satisfaction.
1519    //
1520    // If nothing in the graph holds a version of this peer at all,
1521    // it's left out of the context entirely — `detect_unmet_peers`
1522    // will surface it as a warning after the pass.
1523    let mut peer_context: Vec<(String, String)> = Vec::new();
1524    for (peer_name, declared_range) in &pkg.peer_dependencies {
1525        let satisfies_declared = |v: &str| -> bool {
1526            // The tail may carry a nested peer suffix on fixed-point
1527            // iterations 2+; strip it before checking the semver.
1528            let canonical = canonical_tail(v);
1529            version_satisfies(canonical, declared_range)
1530        };
1531
1532        let from_ancestor = ancestor_scope
1533            .get(peer_name)
1534            .filter(|v| satisfies_declared(v))
1535            .cloned();
1536        let from_ancestor_incompatible = ancestor_scope.get(peer_name).cloned();
1537
1538        let from_pkg_deps = pkg
1539            .dependencies
1540            .get(peer_name)
1541            .filter(|v| satisfies_declared(v))
1542            .cloned();
1543        let from_pkg_deps_incompatible = pkg.dependencies.get(peer_name).cloned();
1544
1545        // `resolve-peers-from-workspace-root`: fall back to the root
1546        // importer's direct deps before the graph-wide scan. Common in
1547        // monorepos where the workspace root pins shared peers (e.g.
1548        // `react`) that leaf packages peer on without declaring them
1549        // in their own subtree. Skipped when the setting is off —
1550        // matches pnpm's `resolve-peers-from-workspace-root=false`.
1551        let from_root = if options.resolve_from_workspace_root {
1552            root_scope
1553                .get(peer_name)
1554                .filter(|v| satisfies_declared(v))
1555                .cloned()
1556        } else {
1557            None
1558        };
1559        let from_root_incompatible = if options.resolve_from_workspace_root {
1560            root_scope.get(peer_name).cloned()
1561        } else {
1562            None
1563        };
1564
1565        // Return the full dep_path TAIL (the part after `name@`), not
1566        // just `p.version`. On fixed-point iteration 2+, the input
1567        // graph's keys are contextualized — e.g. `react-dom` lives at
1568        // `react-dom@18.2.0(react@18.2.0)`. Downstream code
1569        // reconstructs the child lookup key with
1570        // `format!("{child_name}@{tail}")` and needs the tail to
1571        // match whatever the graph has keyed it under, otherwise the
1572        // lookup returns None and the peer gets silently dropped
1573        // from `new_dependencies`. The semver check is against the
1574        // package's canonical `version` field, not the tail, because
1575        // the tail may carry a peer suffix that isn't valid semver.
1576        let from_graph_scan = || {
1577            name_index
1578                .get(peer_name.as_str())
1579                .into_iter()
1580                .flat_map(|bucket| bucket.iter().copied())
1581                .filter(|p| version_satisfies(&p.version, declared_range))
1582                .filter_map(|p| {
1583                    let tail = p
1584                        .dep_path
1585                        .strip_prefix(&format!("{}@", p.name))
1586                        .map(|s| s.to_string())
1587                        .unwrap_or_else(|| p.version.clone());
1588                    node_semver::Version::parse(&p.version)
1589                        .ok()
1590                        .map(|ver| (ver, tail))
1591                })
1592                .max_by(|a, b| a.0.cmp(&b.0))
1593                .map(|(_, tail)| tail)
1594        };
1595
1596        if let Some(version) = from_ancestor
1597            .or(from_pkg_deps)
1598            .or(from_ancestor_incompatible)
1599            .or(from_pkg_deps_incompatible)
1600            .or(from_root)
1601            .or_else(from_graph_scan)
1602            .or(from_root_incompatible)
1603        {
1604            peer_context.push((peer_name.clone(), version));
1605        }
1606    }
1607    peer_context.sort_by(|a, b| a.0.cmp(&b.0));
1608
1609    // For the SUFFIX we build a cycle-broken copy: any peer value that
1610    // nests a reference back to the current package's canonical base
1611    // gets stripped to its plain version. Without this, mutual peer
1612    // cycles (a peers on b, b peers on a) grow the suffix one level
1613    // per iteration of the fixed-point loop and never converge.
1614    //
1615    // The non-cycle paths are untouched, so a regular nested chain
1616    // like `(react-dom@18.2.0(react@18.2.0))` still serializes fully.
1617    // We deliberately keep the full nested tails in `peer_context` for
1618    // downstream scope propagation and child lookups — suffix cycle-
1619    // breaking is cosmetic and should not change what packages exist
1620    // or which snapshot entries reference each other.
1621    //
1622    // Cycle detection is always done against the full `name@version`
1623    // canonical base — even when `dedupe-peers=true` is on, because
1624    // the version-only form is ambiguous (two unrelated packages at
1625    // the same version would false-positive). `dedupe-peers` is
1626    // applied as a post-pass over the final graph in
1627    // `dedupe_peer_suffixes` after cycle detection is done.
1628    let suffix: String = peer_context
1629        .iter()
1630        .map(|(n, v)| {
1631            let cycles_back = contains_canonical_back_ref(v, &canonical_base);
1632            let display_v = if cycles_back {
1633                canonical_tail(v).to_string()
1634            } else {
1635                v.clone()
1636            };
1637            format!("({n}@{display_v})")
1638        })
1639        .collect();
1640    // pnpm's `peersSuffixMaxLength`: when the built suffix exceeds the
1641    // cap, replace the entire suffix with `_<10-char-sha256-hex>` so the
1642    // lockfile key stays bounded. Matches pnpm's lockfile format, so
1643    // lockfiles shared between aube and pnpm stay comparable.
1644    let effective_suffix = if suffix.len() > options.peers_suffix_max_length {
1645        hash_peer_suffix(&suffix)
1646    } else {
1647        suffix
1648    };
1649    let contextualized = format!("{canonical_base}{effective_suffix}");
1650
1651    if out_packages.contains_key(&contextualized) || visiting.contains(&contextualized) {
1652        return Some(contextualized);
1653    }
1654    visiting.insert(contextualized.clone());
1655
1656    // Build the scope for P's children. This is ancestor_scope, overlaid
1657    // with P's own dependencies and its resolved peer map. Children see
1658    // their grandparents too — this mirrors pnpm's all-the-way-up peer
1659    // walk.
1660    //
1661    // We deliberately do NOT strip any existing peer-context suffix
1662    // off the tails we put into the scope. On the first pass the
1663    // values are plain (BFS output has no suffixes), so preserving
1664    // them is a no-op; on subsequent passes (see the fixed-point loop
1665    // in `apply_peer_contexts`) the input graph already carries
1666    // contextualized tails, and keeping them in scope is exactly how
1667    // nested peer suffixes propagate down to consumers — a package
1668    // that peers on `react-dom` and reaches it through a parent whose
1669    // `react-dom` entry is already `18.2.0(react@18.2.0)` will see
1670    // that nested tail in its own scope, and its own suffix will
1671    // serialize as `(react-dom@18.2.0(react@18.2.0))`. That's the
1672    // nested form pnpm writes.
1673    let mut child_scope = ancestor_scope.clone();
1674    for (name, version) in &pkg.dependencies {
1675        child_scope.insert(name.clone(), version.clone());
1676    }
1677    for (name, version) in &peer_context {
1678        child_scope.insert(name.clone(), version.clone());
1679    }
1680
1681    // Recurse into each child, rewriting its dependency map entry to
1682    // point at the contextualized dep_path's tail. A child whose visit
1683    // fails (orphaned / missing) keeps its own tail.
1684    //
1685    // For declared peer names, the peer context (filled from the
1686    // ancestor scope) is authoritative — we override whatever the BFS
1687    // peer walk auto-installed. Otherwise the snapshot suffix and the
1688    // actual wired `dependencies[peer]` could disagree, which made the
1689    // sibling symlink target inconsistent with the peer-context claim.
1690    // When the ancestor's version doesn't satisfy the declared range,
1691    // `detect_unmet_peers` will flag it as a warning after the pass.
1692    let peer_context_versions: FxHashMap<String, String> = peer_context.iter().cloned().collect();
1693
1694    let mut new_dependencies: BTreeMap<String, String> = BTreeMap::new();
1695    let mut visited_dep_names: FxHashSet<String> = FxHashSet::default();
1696
1697    for (child_name, child_version_tail) in &pkg.dependencies {
1698        // If this child is a declared peer, its tail comes from the
1699        // peer context (which may be nested). Otherwise we use the
1700        // tail we already have — also possibly nested on a 2nd pass.
1701        let lookup_tail = match peer_context_versions.get(child_name) {
1702            Some(v) => v.clone(),
1703            None => child_version_tail.clone(),
1704        };
1705        let child_canonical_dep_path = format!("{child_name}@{lookup_tail}");
1706        let child_new = visit_peer_context(
1707            &child_canonical_dep_path,
1708            graph,
1709            name_index,
1710            &child_scope,
1711            root_scope,
1712            out_packages,
1713            visiting,
1714            options,
1715        );
1716        let new_tail = match child_new {
1717            Some(new_dep_path) => new_dep_path
1718                .strip_prefix(&format!("{child_name}@"))
1719                .map(|s| s.to_string())
1720                .unwrap_or_else(|| lookup_tail.clone()),
1721            None => lookup_tail.clone(),
1722        };
1723        new_dependencies.insert(child_name.clone(), new_tail);
1724        visited_dep_names.insert(child_name.clone());
1725    }
1726
1727    // Peers that were satisfied purely from the ancestor scope may not
1728    // have been in `pkg.dependencies` at all (no auto-install needed).
1729    // Wire them as deps now so the linker creates the sibling symlink
1730    // and the lockfile snapshot records them.
1731    for (peer_name, peer_version) in &peer_context {
1732        if visited_dep_names.contains(peer_name) {
1733            continue;
1734        }
1735        let child_canonical_dep_path = format!("{peer_name}@{peer_version}");
1736        let child_new = visit_peer_context(
1737            &child_canonical_dep_path,
1738            graph,
1739            name_index,
1740            &child_scope,
1741            root_scope,
1742            out_packages,
1743            visiting,
1744            options,
1745        );
1746        if let Some(new_dep_path) = child_new {
1747            let new_tail = new_dep_path
1748                .strip_prefix(&format!("{peer_name}@"))
1749                .map(|s| s.to_string())
1750                .unwrap_or_else(|| peer_version.clone());
1751            new_dependencies.insert(peer_name.clone(), new_tail);
1752        }
1753    }
1754
1755    visiting.remove(&contextualized);
1756    let new_optional_dependencies: BTreeMap<String, String> = pkg
1757        .optional_dependencies
1758        .keys()
1759        .filter_map(|name| {
1760            new_dependencies
1761                .get(name)
1762                .map(|tail| (name.clone(), tail.clone()))
1763        })
1764        .collect();
1765
1766    out_packages.insert(
1767        contextualized.clone(),
1768        LockedPackage {
1769            name: pkg.name.clone(),
1770            version: pkg.version.clone(),
1771            integrity: pkg.integrity.clone(),
1772            dependencies: new_dependencies,
1773            optional_dependencies: new_optional_dependencies,
1774            peer_dependencies: pkg.peer_dependencies.clone(),
1775            peer_dependencies_meta: pkg.peer_dependencies_meta.clone(),
1776            dep_path: contextualized.clone(),
1777            local_source: pkg.local_source.clone(),
1778            os: pkg.os.clone(),
1779            cpu: pkg.cpu.clone(),
1780            libc: pkg.libc.clone(),
1781            bundled_dependencies: pkg.bundled_dependencies.clone(),
1782            optional: pkg.optional,
1783            transitive_peer_dependencies: pkg.transitive_peer_dependencies.clone(),
1784            tarball_url: pkg.tarball_url.clone(),
1785            alias_of: pkg.alias_of.clone(),
1786            yarn_checksum: pkg.yarn_checksum.clone(),
1787            engines: pkg.engines.clone(),
1788            bin: pkg.bin.clone(),
1789            declared_dependencies: pkg.declared_dependencies.clone(),
1790            license: pkg.license.clone(),
1791            funding_url: pkg.funding_url.clone(),
1792            extra_meta: pkg.extra_meta.clone(),
1793        },
1794    );
1795    Some(contextualized)
1796}