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 aube_lockfile::{DepType, DirectDep, LockedPackage, LockfileGraph};
22use rustc_hash::{FxHashMap, FxHashSet};
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) -> LockfileGraph {
329    const MAX_ITERATIONS: usize = 16;
330    let mut current = canonical;
331    let mut converged = false;
332    let key_set_hash = |g: &LockfileGraph| -> u64 {
333        aube_util::hash::ordered_seq_hash(g.packages.keys().map(String::as_str))
334    };
335    for i in 0..MAX_ITERATIONS {
336        let before = key_set_hash(&current);
337        let after_once = apply_peer_contexts_once(current, options);
338        let next = if options.dedupe_peer_dependents {
339            dedupe_peer_variants(after_once)
340        } else {
341            after_once
342        };
343        if before == key_set_hash(&next) {
344            tracing::debug!("peer-context pass converged after {i} iteration(s)");
345            current = next;
346            converged = true;
347            break;
348        }
349        current = next;
350    }
351    if !converged {
352        // Hit iteration cap. Means mutually recursive peers or
353        // genuine cycle. Lockfile now has partial nested suffixes.
354        // Linker downstream will wire symlinks against incomplete
355        // graph. Returning this silently ships broken node_modules.
356        // Old code used warn!, warn gets swallowed in CI. Bump to
357        // error! so ops see it. Proper fix is returning a Result
358        // from apply_peer_contexts but that cascades up through
359        // Resolver::resolve signature, do that separately.
360        tracing::error!(
361            "peer-context hit MAX_ITERATIONS={MAX_ITERATIONS} without convergence. \
362             mutually recursive peers likely. lockfile incomplete, linker output will be wrong"
363        );
364    }
365    // `dedupe-peers=true` rewrites the parenthesized peer suffix to
366    // drop the `name@` prefix. Done as a post-pass rather than inline
367    // so cycle detection during the fixed-point loop keeps the full
368    // `name@version` form (otherwise unrelated same-version packages
369    // would false-positive as back-references).
370    if options.dedupe_peers {
371        dedupe_peer_suffixes(current)
372    } else {
373        current
374    }
375}
376
377/// Cross-subtree peer-variant dedupe. When `dedupe-peer-dependents` is
378/// on, packages that landed at different contextualized dep_paths but
379/// resolved every declared peer to the *same* version (ignoring the
380/// nested peer suffix on each peer tail) collapse into a single
381/// canonical variant — chosen as the lexicographically smallest key in
382/// the equivalence class. References in every surviving
383/// `LockedPackage.dependencies` map and every `importers[*]` direct
384/// dep get rewritten through the old→canonical map, and the
385/// non-canonical entries are dropped from `packages`.
386///
387/// Packages whose `peer_dependencies` map is empty — i.e. the canonical
388/// base already has only one variant — are skipped.
389pub(crate) fn dedupe_peer_variants(graph: LockfileGraph) -> LockfileGraph {
390    let canonical_base = |key: &str| -> String { canonical_tail(key).to_string() };
391    // Only the peer-bearing part of the resolved peer tail is
392    // comparable across subtrees — the nested suffix could differ even
393    // for peer-equivalent variants on mid-iterations of the outer
394    // fixed-point loop.
395    let peer_base = |tail: &str| -> String { canonical_tail(tail).to_string() };
396
397    // Group dep_paths by their peer-free base name.
398    let mut groups: BTreeMap<String, Vec<String>> = BTreeMap::new();
399    for key in graph.packages.keys() {
400        groups
401            .entry(canonical_base(key))
402            .or_default()
403            .push(key.clone());
404    }
405
406    let mut rewrite: BTreeMap<String, String> = BTreeMap::new();
407    for (_base, mut keys) in groups {
408        if keys.len() < 2 {
409            continue;
410        }
411        // Deterministic order for canonical selection + stable hashing.
412        keys.sort();
413        // Union-find over equivalence classes. Two variants are
414        // equivalent when each declared peer name resolves to the same
415        // peer base in both (or is missing from both).
416        let mut parent: Vec<usize> = (0..keys.len()).collect();
417        fn find(parent: &mut [usize], i: usize) -> usize {
418            if parent[i] == i {
419                i
420            } else {
421                let r = find(parent, parent[i]);
422                parent[i] = r;
423                r
424            }
425        }
426        for i in 0..keys.len() {
427            for j in (i + 1)..keys.len() {
428                let pa = &graph.packages[&keys[i]];
429                let pb = &graph.packages[&keys[j]];
430                // Same canonical version is required — packages with
431                // different versions but the same name would share no
432                // canonical_base only if the name-without-version
433                // collided, which doesn't happen (version is in the
434                // base). Still, belt-and-suspenders.
435                if pa.version != pb.version {
436                    continue;
437                }
438                let peer_names: BTreeSet<&String> = pa
439                    .peer_dependencies
440                    .keys()
441                    .chain(pb.peer_dependencies.keys())
442                    .collect();
443                let equivalent = peer_names.iter().all(|name| {
444                    match (
445                        pa.dependencies.get(name.as_str()),
446                        pb.dependencies.get(name.as_str()),
447                    ) {
448                        (Some(va), Some(vb)) => peer_base(va) == peer_base(vb),
449                        (None, None) => true,
450                        _ => false,
451                    }
452                });
453                if equivalent {
454                    let ri = find(&mut parent, i);
455                    let rj = find(&mut parent, j);
456                    if ri != rj {
457                        parent[ri] = rj;
458                    }
459                }
460            }
461        }
462        // Build class → canonical (smallest key) mapping. Using
463        // index-based iteration here because `find` takes a mutable
464        // reference into `parent`, so holding an immutable borrow
465        // from `keys.iter()` at the same time would double-borrow.
466        #[allow(clippy::needless_range_loop)]
467        {
468            let mut class_rep: BTreeMap<usize, String> = BTreeMap::new();
469            for i in 0..keys.len() {
470                let root = find(&mut parent, i);
471                class_rep
472                    .entry(root)
473                    .and_modify(|cur| {
474                        if keys[i] < *cur {
475                            *cur = keys[i].clone();
476                        }
477                    })
478                    .or_insert_with(|| keys[i].clone());
479            }
480            for i in 0..keys.len() {
481                let root = find(&mut parent, i);
482                let canonical = class_rep[&root].clone();
483                if keys[i] != canonical {
484                    rewrite.insert(keys[i].clone(), canonical);
485                }
486            }
487        }
488    }
489
490    if rewrite.is_empty() {
491        return graph;
492    }
493
494    // Rewrite package dependency tails and keep only canonicals.
495    let LockfileGraph {
496        importers,
497        packages,
498        settings,
499        overrides,
500        ignored_optional_dependencies,
501        times,
502        skipped_optional_dependencies,
503        catalogs,
504        bun_config_version,
505        patched_dependencies,
506        trusted_dependencies,
507        extra_fields,
508        workspace_extra_fields,
509    } = graph;
510
511    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
512    for (key, mut pkg) in packages {
513        if rewrite.contains_key(&key) {
514            continue;
515        }
516        for (dep_name, dep_tail) in pkg.dependencies.iter_mut() {
517            let dep_key = format!("{dep_name}@{dep_tail}");
518            if let Some(canonical) = rewrite.get(&dep_key) {
519                let new_tail = canonical
520                    .strip_prefix(&format!("{dep_name}@"))
521                    .map(|s| s.to_string())
522                    .unwrap_or_else(|| canonical.clone());
523                *dep_tail = new_tail;
524            }
525        }
526        new_packages.insert(key, pkg);
527    }
528
529    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
530    for (importer_path, deps) in importers {
531        let mut new_deps = Vec::with_capacity(deps.len());
532        for mut dep in deps {
533            if let Some(canonical) = rewrite.get(&dep.dep_path) {
534                dep.dep_path = canonical.clone();
535            }
536            new_deps.push(dep);
537        }
538        new_importers.insert(importer_path, new_deps);
539    }
540
541    LockfileGraph {
542        importers: new_importers,
543        packages: new_packages,
544        settings,
545        overrides,
546        ignored_optional_dependencies,
547        times,
548        skipped_optional_dependencies,
549        catalogs,
550        bun_config_version,
551        patched_dependencies,
552        trusted_dependencies,
553        extra_fields,
554        workspace_extra_fields,
555    }
556}
557
558/// Single pass of the peer-context computation. See `apply_peer_contexts`
559/// for the wrapping fixed-point loop.
560///
561/// Algorithm per visited package P, reached at some point in a DFS from an
562/// importer with `ancestor_scope: name -> dep_path_tail`:
563///
564///  1. For each peer name declared by P, look it up in `ancestor_scope`
565///     (nearest-ancestor-wins, since the scope is rebuilt per recursion).
566///     If missing, fall back to P's own entry in `dependencies` — the BFS
567///     enqueue auto-installed it as a transitive, matching pnpm's
568///     `auto-install-peers=true` default.
569///  2. Sort the (peer_name, resolution) pairs and serialize as
570///     `(n1@v1)(n2@v2)…` for the suffix.
571///  3. Produce a contextualized dep_path `name@version{suffix}`. If that
572///     key is already in `out_packages` (or currently on the DFS stack via
573///     `visiting`), short-circuit — we've already emitted this variant.
574///  4. Build a new scope for P's children by merging the ancestor scope
575///     with P's own `dependencies` and the resolved peer map. Recurse.
576///  5. Emit the contextualized LockedPackage.
577///
578/// Cycles: protected by `visiting` — if a package is re-entered via a
579/// dependency cycle, we return the already-computed dep_path without
580/// recursing again. The peer context is fixed at first visit; any cycle
581/// traversal uses whatever context was live at that first visit.
582fn apply_peer_contexts_once(
583    canonical: LockfileGraph,
584    options: &PeerContextOptions,
585) -> LockfileGraph {
586    let mut out_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
587    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
588
589    // Name-indexed view of the canonical graph, shared across
590    // every `visit_peer_context` call in this pass. Peer-resolution
591    // scan-by-name is the resolver's hottest inner loop. Without
592    // this, each peer runs `O(|graph|)` per package per fixed-point
593    // iter. Prebuilt index drops the scan to O(1) average.
594    let mut name_index: FxHashMap<&str, Vec<&LockedPackage>> = FxHashMap::default();
595    for pkg in canonical.packages.values() {
596        name_index.entry(pkg.name.as_str()).or_default().push(pkg);
597    }
598
599    // Root-importer scope used by `resolve-peers-from-workspace-root`.
600    // Computed once from the canonical input so it reflects the
601    // contextualized state of every root dep on fixed-point iterations
602    // 2+ — same logic as per-importer `importer_scope` below.
603    let root_scope: FxHashMap<String, String> = canonical
604        .importers
605        .get(".")
606        .map(|deps| scope_map_from_deps(deps))
607        .unwrap_or_default();
608
609    for (importer_path, direct_deps) in &canonical.importers {
610        // An importer's own direct deps are in scope for its children's
611        // peer resolution — this is how pnpm's "auto-install at the root"
612        // path gets peer links that point at root-level packages.
613        //
614        // Use the *full contextualized tail* off each DirectDep rather
615        // than the package's plain version. On Pass 1 of the fixed-point
616        // loop the tail is canonical and equal to `p.version`; on Pass 2+
617        // it's already contextualized, and passing the plain version
618        // would make descendants look up keys that don't exist in the
619        // (now-nested) graph.
620        let importer_scope = scope_map_from_deps(direct_deps);
621
622        let mut new_deps = Vec::with_capacity(direct_deps.len());
623        for dep in direct_deps {
624            // `visiting` is the DFS stack guard for this particular descent
625            // — reset per direct dep so we don't incorrectly flag a package
626            // as a cycle when it's reached again from a sibling subtree.
627            // The shared `out_packages` still dedupes across siblings since
628            // the second visit hits the `contains_key` short-circuit below.
629            //
630            // Invariant (see `visit_peer_context` for the detailed handling):
631            // a dep_path returned from the cycle-break branch may not yet
632            // be present in `out_packages` at the moment of return, because
633            // the package is still being assembled up the call stack. The
634            // parent that records the returned tail will complete its own
635            // insertion before the recursion unwinds, so by the time
636            // anything reads the graph, every referenced dep_path exists.
637            let mut visiting: FxHashSet<String> = FxHashSet::default();
638            let new_dep_path = visit_peer_context(
639                &dep.dep_path,
640                &canonical,
641                &name_index,
642                &importer_scope,
643                &root_scope,
644                &mut out_packages,
645                &mut visiting,
646                options,
647            )
648            .unwrap_or_else(|| dep.dep_path.clone());
649            new_deps.push(DirectDep {
650                name: dep.name.clone(),
651                dep_path: new_dep_path,
652                dep_type: dep.dep_type,
653                specifier: dep.specifier.clone(),
654            });
655        }
656        new_importers.insert(importer_path.clone(), new_deps);
657    }
658
659    // Any canonical package that was never reached by the DFS (orphaned
660    // from every importer) is dropped — that matches the filter_deps
661    // semantics and avoids emitting dead entries into the lockfile.
662
663    LockfileGraph {
664        importers: new_importers,
665        packages: out_packages,
666        // The post-pass is pure — settings + overrides carry through
667        // from the input graph untouched.
668        settings: canonical.settings,
669        overrides: canonical.overrides,
670        ignored_optional_dependencies: canonical.ignored_optional_dependencies,
671        times: canonical.times,
672        skipped_optional_dependencies: canonical.skipped_optional_dependencies,
673        catalogs: canonical.catalogs,
674        bun_config_version: canonical.bun_config_version,
675        patched_dependencies: canonical.patched_dependencies,
676        trusted_dependencies: canonical.trusted_dependencies,
677        extra_fields: canonical.extra_fields,
678        workspace_extra_fields: canonical.workspace_extra_fields,
679    }
680}
681
682/// DFS helper for `apply_peer_contexts`. Returns the peer-contextualized
683/// dep_path of the visited package, or `None` if the canonical package is
684/// missing (shouldn't happen in practice but we degrade gracefully).
685/// Does `value` contain a peer-suffix reference to `canonical` as a
686/// proper name@version boundary (i.e. preceded by `(` and followed by
687/// `(` / `)` / end-of-string)? Used by the peer-context pass to detect
688/// when a nested tail loops back to the current package so it can
689/// short-circuit the chain instead of growing the suffix forever.
690/// If `s` ends with `_<10 lowercase hex>` (the marker written by
691/// `hash_peer_suffix`), strip it and return the prefix. Otherwise
692/// return `s` unchanged.
693///
694/// Safe against false positives: `s` here is always a post-split
695/// `name@version` base, and semver forbids `_` inside a version, so
696/// an underscore 10 chars from the end of `name@version` can only be
697/// our marker.
698/// Everything before the first `(` — i.e. the canonical `name@version`
699/// part of a dep-path with the peer-context suffix stripped. Returns
700/// the original string when no `(` is present. Borrowed; callers that
701/// need owned bump with `.to_string()`.
702fn canonical_tail(s: &str) -> &str {
703    s.split('(').next().unwrap_or(s)
704}
705
706/// Build a `name → contextualized tail` map from a direct-dep slice.
707/// The tail is the dep_path with the `{name}@` prefix stripped, which
708/// on pass 1 is equal to `pkg.version` and on pass 2+ carries the
709/// nested peer-context suffix. Used both for the root scope and for
710/// each importer's own scope inside `apply_peer_contexts_once`.
711fn scope_map_from_deps(deps: &[DirectDep]) -> FxHashMap<String, String> {
712    let mut out = FxHashMap::with_capacity_and_hasher(deps.len(), Default::default());
713    for d in deps {
714        let prefix_len = d.name.len() + 1;
715        let tail = if d.dep_path.len() > prefix_len
716            && d.dep_path.as_bytes().get(d.name.len()) == Some(&b'@')
717            && d.dep_path.as_bytes().starts_with(d.name.as_bytes())
718        {
719            d.dep_path[prefix_len..].to_string()
720        } else {
721            d.dep_path.clone()
722        };
723        out.insert(d.name.clone(), tail);
724    }
725    out
726}
727
728fn strip_hashed_peer_suffix(s: &str) -> &str {
729    const MARKER_LEN: usize = 11; // `_` + 10 hex chars
730    if s.len() < MARKER_LEN {
731        return s;
732    }
733    let tail = &s[s.len() - MARKER_LEN..];
734    if !tail.starts_with('_') {
735        return s;
736    }
737    if tail[1..]
738        .chars()
739        .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
740    {
741        &s[..s.len() - MARKER_LEN]
742    } else {
743        s
744    }
745}
746
747/// Hash a peer-ID suffix with SHA-256 and return `_<10-char-hex>`.
748/// Used by the peer-context pass when the raw suffix length exceeds
749/// `peersSuffixMaxLength`. Matches pnpm's format so lockfile dep_path
750/// keys stay portable.
751pub(crate) fn hash_peer_suffix(suffix: &str) -> String {
752    use sha2::{Digest, Sha256};
753    let digest = Sha256::digest(suffix.as_bytes());
754    let mut out = String::with_capacity(11);
755    out.push('_');
756    for byte in digest.iter().take(5) {
757        use std::fmt::Write;
758        let _ = write!(out, "{byte:02x}");
759    }
760    out
761}
762
763pub(crate) fn contains_canonical_back_ref(value: &str, canonical: &str) -> bool {
764    let bytes = value.as_bytes();
765    let target = canonical.as_bytes();
766    if target.is_empty() || target.len() > bytes.len() {
767        return false;
768    }
769    let mut i = 0;
770    while i + target.len() <= bytes.len() {
771        if &bytes[i..i + target.len()] == target {
772            let before = if i == 0 { b'\0' } else { bytes[i - 1] };
773            let after = bytes.get(i + target.len()).copied().unwrap_or(b'\0');
774            let before_ok = before == b'(';
775            let after_ok = after == b'(' || after == b')' || after == b'\0';
776            if before_ok && after_ok {
777                return true;
778            }
779        }
780        i += 1;
781    }
782    false
783}
784
785/// Dedupe-peers post-pass: strip the `name@` prefix from every
786/// parenthesized peer segment in every dep_path key and reference,
787/// turning `react-dom@18.2.0(react@18.2.0)` into
788/// `react-dom@18.2.0(18.2.0)`. Nested segments get the same treatment
789/// so `a@1(b@2(c@3))` becomes `a@1(2(3))`.
790///
791/// Running this as a final post-pass (instead of inline during suffix
792/// assembly in `visit_peer_context`) keeps cycle detection correct:
793/// the detection path works against the full `name@version` form
794/// throughout the fixed-point loop, and only the serialized output
795/// gets the shorter form. A version-only inline approach would
796/// false-positive on unrelated packages that coincidentally share a
797/// version with the current package's canonical base.
798///
799/// Pure: no-op when `dedupe_peers` is off (caller gates the call);
800/// otherwise rewrites every package key, every `LockedPackage.dep_path`
801/// and `LockedPackage.dependencies` value, and every `importers[*]`
802/// DirectDep `dep_path` through the same `apply_dedupe_peers_to_tail`
803/// helper. Package bodies (integrity, metadata, etc.) are cloned
804/// verbatim.
805pub(crate) fn dedupe_peer_suffixes(graph: LockfileGraph) -> LockfileGraph {
806    // Pass 1: compute the intended deduped key for each package and
807    // tally how many distinct full-form keys map to it. Stripping
808    // `name@` from suffix segments is lossy — two variants whose peer
809    // *names* differ but whose peer *versions* coincide would collapse
810    // onto the same deduped key (e.g. `consumer@1.0.0(foo@1.0.0)` and
811    // `consumer@1.0.0(bar@1.0.0)` both → `consumer@1.0.0(1.0.0)`).
812    // `dedupe_peer_variants` already merged the peer-equivalent
813    // duplicates, so any remaining collision here represents genuinely
814    // distinct variants — losing one would silently drop its
815    // dependency wiring. We detect those collisions and keep both
816    // sides in full form.
817    let mut target_counts: BTreeMap<String, usize> = BTreeMap::new();
818    let mut intended: BTreeMap<String, String> = BTreeMap::new();
819    for key in graph.packages.keys() {
820        let new_key = apply_dedupe_peers_to_key(key);
821        *target_counts.entry(new_key.clone()).or_insert(0) += 1;
822        intended.insert(key.clone(), new_key);
823    }
824    let rewrite: BTreeMap<String, String> = intended
825        .into_iter()
826        .map(|(old, new)| {
827            if target_counts.get(&new).copied().unwrap_or(0) > 1 {
828                tracing::warn!(
829                    "dedupe-peers: collision on {new} — keeping {old} in full form to avoid \
830                     dropping a distinct peer-variant"
831                );
832                (old.clone(), old)
833            } else {
834                (old, new)
835            }
836        })
837        .collect();
838
839    // Rewrite a `(child_name, tail)` reference by reconstructing the
840    // target's full-form key, looking up its effective rewrite, and
841    // stripping `child_name@` off the result to recover the tail.
842    // Tails always follow their target package's rewrite decision,
843    // so references stay consistent when a collision forces a target
844    // back to full form.
845    let rewrite_tail = |child_name: &str, tail: &str| -> String {
846        let old_key = format!("{child_name}@{tail}");
847        match rewrite.get(&old_key) {
848            Some(new_key) => new_key
849                .strip_prefix(&format!("{child_name}@"))
850                .map(|s| s.to_string())
851                .unwrap_or_else(|| tail.to_string()),
852            None => apply_dedupe_peers_to_tail(tail),
853        }
854    };
855
856    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
857    for (old_key, pkg) in graph.packages {
858        let new_key = rewrite
859            .get(&old_key)
860            .cloned()
861            .unwrap_or_else(|| old_key.clone());
862        let new_dependencies: BTreeMap<String, String> = pkg
863            .dependencies
864            .into_iter()
865            .map(|(n, v)| {
866                let new_v = rewrite_tail(&n, &v);
867                (n, new_v)
868            })
869            .collect();
870        let new_optional_dependencies: BTreeMap<String, String> = pkg
871            .optional_dependencies
872            .into_iter()
873            .map(|(n, v)| {
874                let new_v = rewrite_tail(&n, &v);
875                (n, new_v)
876            })
877            .collect();
878        new_packages.insert(
879            new_key.clone(),
880            LockedPackage {
881                name: pkg.name,
882                version: pkg.version,
883                integrity: pkg.integrity,
884                dependencies: new_dependencies,
885                optional_dependencies: new_optional_dependencies,
886                peer_dependencies: pkg.peer_dependencies,
887                peer_dependencies_meta: pkg.peer_dependencies_meta,
888                dep_path: new_key,
889                local_source: pkg.local_source,
890                os: pkg.os,
891                cpu: pkg.cpu,
892                libc: pkg.libc,
893                bundled_dependencies: pkg.bundled_dependencies,
894                optional: pkg.optional,
895                transitive_peer_dependencies: pkg.transitive_peer_dependencies,
896                tarball_url: pkg.tarball_url,
897                alias_of: pkg.alias_of,
898                yarn_checksum: pkg.yarn_checksum,
899                engines: pkg.engines,
900                bin: pkg.bin,
901                declared_dependencies: pkg.declared_dependencies,
902                license: pkg.license,
903                funding_url: pkg.funding_url,
904                extra_meta: pkg.extra_meta,
905            },
906        );
907    }
908
909    let new_importers: BTreeMap<String, Vec<DirectDep>> = graph
910        .importers
911        .into_iter()
912        .map(|(path, deps)| {
913            let rewritten = deps
914                .into_iter()
915                .map(|d| {
916                    let new_dep_path = rewrite
917                        .get(&d.dep_path)
918                        .cloned()
919                        .unwrap_or_else(|| apply_dedupe_peers_to_key(&d.dep_path));
920                    DirectDep {
921                        name: d.name,
922                        dep_path: new_dep_path,
923                        dep_type: d.dep_type,
924                        specifier: d.specifier,
925                    }
926                })
927                .collect();
928            (path, rewritten)
929        })
930        .collect();
931
932    LockfileGraph {
933        importers: new_importers,
934        packages: new_packages,
935        settings: graph.settings,
936        overrides: graph.overrides,
937        ignored_optional_dependencies: graph.ignored_optional_dependencies,
938        times: graph.times,
939        skipped_optional_dependencies: graph.skipped_optional_dependencies,
940        catalogs: graph.catalogs,
941        bun_config_version: graph.bun_config_version,
942        patched_dependencies: graph.patched_dependencies,
943        trusted_dependencies: graph.trusted_dependencies,
944        extra_fields: graph.extra_fields,
945        workspace_extra_fields: graph.workspace_extra_fields,
946    }
947}
948
949/// Strip `name@` from inside every parenthesized segment of a full
950/// dep_path key (e.g. `react-dom@18.2.0(react@18.2.0)` →
951/// `react-dom@18.2.0(18.2.0)`). The first `name@version` outside any
952/// parens is preserved verbatim — that's the canonical head of the
953/// dep_path and `dedupe-peers` only affects the peer suffix.
954pub(crate) fn apply_dedupe_peers_to_key(key: &str) -> String {
955    let mut parts = key.split('(');
956    let Some(first) = parts.next() else {
957        return key.to_string();
958    };
959    let mut out = String::with_capacity(key.len());
960    out.push_str(first);
961    for part in parts {
962        out.push('(');
963        // In a well-formed key, `part` looks like `name@version)` /
964        // `name@version` / `version)` / ... We strip everything up to
965        // and including the LAST `@` (scoped packages like
966        // `@types/react@18.2.0` contain two `@`s; the separator is the
967        // rightmost one). We only strip if that `@` comes before the
968        // first `)` or `(` (i.e. the segment actually starts with
969        // `name@`, not the outer parens closing with no name inside).
970        if let Some(at_idx) = part.rfind('@') {
971            let close_idx = part.find([')', '(']).unwrap_or(usize::MAX);
972            if at_idx < close_idx {
973                out.push_str(&part[at_idx + 1..]);
974                continue;
975            }
976        }
977        out.push_str(part);
978    }
979    out
980}
981
982/// Same as [`apply_dedupe_peers_to_key`] but for dep-tail values
983/// stored in `LockedPackage.dependencies` (e.g. `18.2.0(react@18.2.0)`
984/// → `18.2.0(18.2.0)`). Tails differ from keys only by lacking the
985/// leading `name@` prefix — both use the same parens-based suffix
986/// shape, so the algorithm is identical.
987fn apply_dedupe_peers_to_tail(tail: &str) -> String {
988    apply_dedupe_peers_to_key(tail)
989}
990
991#[allow(clippy::too_many_arguments)]
992fn visit_peer_context<'g>(
993    input_dep_path: &str,
994    graph: &'g LockfileGraph,
995    name_index: &FxHashMap<&'g str, Vec<&'g LockedPackage>>,
996    ancestor_scope: &FxHashMap<String, String>,
997    root_scope: &FxHashMap<String, String>,
998    out_packages: &mut BTreeMap<String, LockedPackage>,
999    visiting: &mut FxHashSet<String>,
1000    options: &PeerContextOptions,
1001) -> Option<String> {
1002    let pkg = graph.packages.get(input_dep_path)?;
1003
1004    // The input key may already carry a peer suffix (fixed-point loop
1005    // Pass 2+). Drop it before we build a new one — otherwise we'd
1006    // append the new suffix on top of the old and grow unboundedly
1007    // across iterations (classic mutual-peer-cycle blow-up).
1008    //
1009    // Two suffix forms can be present from a prior pass:
1010    //   1. `(name@version)(…)` — the normal nested peer suffix. Stripped
1011    //      by splitting on the first `(`.
1012    //   2. `_<10-char-sha256-hex>` — the hashed form produced when the
1013    //      normal suffix exceeded `peersSuffixMaxLength`. Must also be
1014    //      stripped; otherwise each pass re-hashes the already-hashed
1015    //      key and appends another marker (exposed by the
1016    //      `peer_suffix_is_hashed_when_exceeding_cap` unit test).
1017    let canonical_base = canonical_tail(input_dep_path);
1018    let canonical_base = strip_hashed_peer_suffix(canonical_base).to_string();
1019
1020    // Compute peer context: walk declared peers, resolve from ancestors
1021    // (nearest wins — the scope is rebuilt as we recurse) or from the
1022    // package's own dependency map as the auto-install fallback. Both
1023    // sides may produce nested tails on the second and later iterations
1024    // of the fixed-point loop.
1025    // Resolution source priority for each declared peer:
1026    //   1. Ancestor scope — if the ancestor's version actually
1027    //      satisfies the declared peer range. Different subtrees can
1028    //      pin different versions of the same peer name (classic
1029    //      `lib-a peers on react@^17`, `lib-b peers on react@^18`),
1030    //      and silently reusing the ancestor's version regardless of
1031    //      the declared range would force both libs onto the same
1032    //      version — exactly the behavior we want to fix here.
1033    //   2. The current package's own `pkg.dependencies` entry — the
1034    //      BFS peer-walk enqueued this peer with the declared range,
1035    //      so whatever got picked there is guaranteed to satisfy.
1036    //   3. A graph-wide scan as a last resort: any package whose name
1037    //      matches and whose version satisfies the declared range.
1038    //      This keeps nested-context callers from losing their peer
1039    //      resolution when neither ancestor nor own-deps has it.
1040    //   4. If no satisfying version exists, fall back to the nearest
1041    //      incompatible ancestor/root/pkg dependency. pnpm still wires
1042    //      that user-declared version into the peer context and then
1043    //      reports the semver mismatch; omitting it would produce a
1044    //      weaker "missing peer" warning and an unsuffixed snapshot.
1045    //
1046    // If nothing in the graph satisfies, the peer is left out of the
1047    // context entirely — `detect_unmet_peers` will surface it as a
1048    // warning after the pass.
1049    let mut peer_context: Vec<(String, String)> = Vec::new();
1050    for (peer_name, declared_range) in &pkg.peer_dependencies {
1051        let satisfies_declared = |v: &str| -> bool {
1052            // The tail may carry a nested peer suffix on fixed-point
1053            // iterations 2+; strip it before checking the semver.
1054            let canonical = canonical_tail(v);
1055            version_satisfies(canonical, declared_range)
1056        };
1057
1058        let from_ancestor = ancestor_scope
1059            .get(peer_name)
1060            .filter(|v| satisfies_declared(v))
1061            .cloned();
1062        let from_ancestor_incompatible = ancestor_scope.get(peer_name).cloned();
1063
1064        let from_pkg_deps = pkg
1065            .dependencies
1066            .get(peer_name)
1067            .filter(|v| satisfies_declared(v))
1068            .cloned();
1069        let from_pkg_deps_incompatible = pkg.dependencies.get(peer_name).cloned();
1070
1071        // `resolve-peers-from-workspace-root`: fall back to the root
1072        // importer's direct deps before the graph-wide scan. Common in
1073        // monorepos where the workspace root pins shared peers (e.g.
1074        // `react`) that leaf packages peer on without declaring them
1075        // in their own subtree. Skipped when the setting is off —
1076        // matches pnpm's `resolve-peers-from-workspace-root=false`.
1077        let from_root = if options.resolve_from_workspace_root {
1078            root_scope
1079                .get(peer_name)
1080                .filter(|v| satisfies_declared(v))
1081                .cloned()
1082        } else {
1083            None
1084        };
1085        let from_root_incompatible = if options.resolve_from_workspace_root {
1086            root_scope.get(peer_name).cloned()
1087        } else {
1088            None
1089        };
1090
1091        // Return the full dep_path TAIL (the part after `name@`), not
1092        // just `p.version`. On fixed-point iteration 2+, the input
1093        // graph's keys are contextualized — e.g. `react-dom` lives at
1094        // `react-dom@18.2.0(react@18.2.0)`. Downstream code
1095        // reconstructs the child lookup key with
1096        // `format!("{child_name}@{tail}")` and needs the tail to
1097        // match whatever the graph has keyed it under, otherwise the
1098        // lookup returns None and the peer gets silently dropped
1099        // from `new_dependencies`. The semver check is against the
1100        // package's canonical `version` field, not the tail, because
1101        // the tail may carry a peer suffix that isn't valid semver.
1102        let from_graph_scan = || {
1103            name_index
1104                .get(peer_name.as_str())
1105                .into_iter()
1106                .flat_map(|bucket| bucket.iter().copied())
1107                .filter(|p| version_satisfies(&p.version, declared_range))
1108                .filter_map(|p| {
1109                    let tail = p
1110                        .dep_path
1111                        .strip_prefix(&format!("{}@", p.name))
1112                        .map(|s| s.to_string())
1113                        .unwrap_or_else(|| p.version.clone());
1114                    node_semver::Version::parse(&p.version)
1115                        .ok()
1116                        .map(|ver| (ver, tail))
1117                })
1118                .max_by(|a, b| a.0.cmp(&b.0))
1119                .map(|(_, tail)| tail)
1120        };
1121
1122        if let Some(version) = from_ancestor
1123            .or(from_pkg_deps)
1124            .or(from_root)
1125            .or_else(from_graph_scan)
1126            .or(from_ancestor_incompatible)
1127            .or(from_pkg_deps_incompatible)
1128            .or(from_root_incompatible)
1129        {
1130            peer_context.push((peer_name.clone(), version));
1131        }
1132    }
1133    peer_context.sort_by(|a, b| a.0.cmp(&b.0));
1134
1135    // For the SUFFIX we build a cycle-broken copy: any peer value that
1136    // nests a reference back to the current package's canonical base
1137    // gets stripped to its plain version. Without this, mutual peer
1138    // cycles (a peers on b, b peers on a) grow the suffix one level
1139    // per iteration of the fixed-point loop and never converge.
1140    //
1141    // The non-cycle paths are untouched, so a regular nested chain
1142    // like `(react-dom@18.2.0(react@18.2.0))` still serializes fully.
1143    // We deliberately keep the full nested tails in `peer_context` for
1144    // downstream scope propagation and child lookups — suffix cycle-
1145    // breaking is cosmetic and should not change what packages exist
1146    // or which snapshot entries reference each other.
1147    //
1148    // Cycle detection is always done against the full `name@version`
1149    // canonical base — even when `dedupe-peers=true` is on, because
1150    // the version-only form is ambiguous (two unrelated packages at
1151    // the same version would false-positive). `dedupe-peers` is
1152    // applied as a post-pass over the final graph in
1153    // `dedupe_peer_suffixes` after cycle detection is done.
1154    let suffix: String = peer_context
1155        .iter()
1156        .map(|(n, v)| {
1157            let cycles_back = contains_canonical_back_ref(v, &canonical_base);
1158            let display_v = if cycles_back {
1159                canonical_tail(v).to_string()
1160            } else {
1161                v.clone()
1162            };
1163            format!("({n}@{display_v})")
1164        })
1165        .collect();
1166    // pnpm's `peersSuffixMaxLength`: when the built suffix exceeds the
1167    // cap, replace the entire suffix with `_<10-char-sha256-hex>` so the
1168    // lockfile key stays bounded. Matches pnpm's lockfile format, so
1169    // lockfiles shared between aube and pnpm stay comparable.
1170    let effective_suffix = if suffix.len() > options.peers_suffix_max_length {
1171        hash_peer_suffix(&suffix)
1172    } else {
1173        suffix
1174    };
1175    let contextualized = format!("{canonical_base}{effective_suffix}");
1176
1177    if out_packages.contains_key(&contextualized) || visiting.contains(&contextualized) {
1178        return Some(contextualized);
1179    }
1180    visiting.insert(contextualized.clone());
1181
1182    // Build the scope for P's children. This is ancestor_scope, overlaid
1183    // with P's own dependencies and its resolved peer map. Children see
1184    // their grandparents too — this mirrors pnpm's all-the-way-up peer
1185    // walk.
1186    //
1187    // We deliberately do NOT strip any existing peer-context suffix
1188    // off the tails we put into the scope. On the first pass the
1189    // values are plain (BFS output has no suffixes), so preserving
1190    // them is a no-op; on subsequent passes (see the fixed-point loop
1191    // in `apply_peer_contexts`) the input graph already carries
1192    // contextualized tails, and keeping them in scope is exactly how
1193    // nested peer suffixes propagate down to consumers — a package
1194    // that peers on `react-dom` and reaches it through a parent whose
1195    // `react-dom` entry is already `18.2.0(react@18.2.0)` will see
1196    // that nested tail in its own scope, and its own suffix will
1197    // serialize as `(react-dom@18.2.0(react@18.2.0))`. That's the
1198    // nested form pnpm writes.
1199    let mut child_scope = ancestor_scope.clone();
1200    for (name, version) in &pkg.dependencies {
1201        child_scope.insert(name.clone(), version.clone());
1202    }
1203    for (name, version) in &peer_context {
1204        child_scope.insert(name.clone(), version.clone());
1205    }
1206
1207    // Recurse into each child, rewriting its dependency map entry to
1208    // point at the contextualized dep_path's tail. A child whose visit
1209    // fails (orphaned / missing) keeps its own tail.
1210    //
1211    // For declared peer names, the peer context (filled from the
1212    // ancestor scope) is authoritative — we override whatever the BFS
1213    // peer walk auto-installed. Otherwise the snapshot suffix and the
1214    // actual wired `dependencies[peer]` could disagree, which made the
1215    // sibling symlink target inconsistent with the peer-context claim.
1216    // When the ancestor's version doesn't satisfy the declared range,
1217    // `detect_unmet_peers` will flag it as a warning after the pass.
1218    let peer_context_versions: FxHashMap<String, String> = peer_context.iter().cloned().collect();
1219
1220    let mut new_dependencies: BTreeMap<String, String> = BTreeMap::new();
1221    let mut visited_dep_names: FxHashSet<String> = FxHashSet::default();
1222
1223    for (child_name, child_version_tail) in &pkg.dependencies {
1224        // If this child is a declared peer, its tail comes from the
1225        // peer context (which may be nested). Otherwise we use the
1226        // tail we already have — also possibly nested on a 2nd pass.
1227        let lookup_tail = match peer_context_versions.get(child_name) {
1228            Some(v) => v.clone(),
1229            None => child_version_tail.clone(),
1230        };
1231        let child_canonical_dep_path = format!("{child_name}@{lookup_tail}");
1232        let child_new = visit_peer_context(
1233            &child_canonical_dep_path,
1234            graph,
1235            name_index,
1236            &child_scope,
1237            root_scope,
1238            out_packages,
1239            visiting,
1240            options,
1241        );
1242        let new_tail = match child_new {
1243            Some(new_dep_path) => new_dep_path
1244                .strip_prefix(&format!("{child_name}@"))
1245                .map(|s| s.to_string())
1246                .unwrap_or_else(|| lookup_tail.clone()),
1247            None => lookup_tail.clone(),
1248        };
1249        new_dependencies.insert(child_name.clone(), new_tail);
1250        visited_dep_names.insert(child_name.clone());
1251    }
1252
1253    // Peers that were satisfied purely from the ancestor scope may not
1254    // have been in `pkg.dependencies` at all (no auto-install needed).
1255    // Wire them as deps now so the linker creates the sibling symlink
1256    // and the lockfile snapshot records them.
1257    for (peer_name, peer_version) in &peer_context {
1258        if visited_dep_names.contains(peer_name) {
1259            continue;
1260        }
1261        let child_canonical_dep_path = format!("{peer_name}@{peer_version}");
1262        let child_new = visit_peer_context(
1263            &child_canonical_dep_path,
1264            graph,
1265            name_index,
1266            &child_scope,
1267            root_scope,
1268            out_packages,
1269            visiting,
1270            options,
1271        );
1272        if let Some(new_dep_path) = child_new {
1273            let new_tail = new_dep_path
1274                .strip_prefix(&format!("{peer_name}@"))
1275                .map(|s| s.to_string())
1276                .unwrap_or_else(|| peer_version.clone());
1277            new_dependencies.insert(peer_name.clone(), new_tail);
1278        }
1279    }
1280
1281    visiting.remove(&contextualized);
1282    let new_optional_dependencies: BTreeMap<String, String> = pkg
1283        .optional_dependencies
1284        .keys()
1285        .filter_map(|name| {
1286            new_dependencies
1287                .get(name)
1288                .map(|tail| (name.clone(), tail.clone()))
1289        })
1290        .collect();
1291
1292    out_packages.insert(
1293        contextualized.clone(),
1294        LockedPackage {
1295            name: pkg.name.clone(),
1296            version: pkg.version.clone(),
1297            integrity: pkg.integrity.clone(),
1298            dependencies: new_dependencies,
1299            optional_dependencies: new_optional_dependencies,
1300            peer_dependencies: pkg.peer_dependencies.clone(),
1301            peer_dependencies_meta: pkg.peer_dependencies_meta.clone(),
1302            dep_path: contextualized.clone(),
1303            local_source: pkg.local_source.clone(),
1304            os: pkg.os.clone(),
1305            cpu: pkg.cpu.clone(),
1306            libc: pkg.libc.clone(),
1307            bundled_dependencies: pkg.bundled_dependencies.clone(),
1308            optional: pkg.optional,
1309            transitive_peer_dependencies: pkg.transitive_peer_dependencies.clone(),
1310            tarball_url: pkg.tarball_url.clone(),
1311            alias_of: pkg.alias_of.clone(),
1312            yarn_checksum: pkg.yarn_checksum.clone(),
1313            engines: pkg.engines.clone(),
1314            bin: pkg.bin.clone(),
1315            declared_dependencies: pkg.declared_dependencies.clone(),
1316            license: pkg.license.clone(),
1317            funding_url: pkg.funding_url.clone(),
1318            extra_meta: pkg.extra_meta.clone(),
1319        },
1320    );
1321    Some(contextualized)
1322}