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, LocalSource, 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 -> peer provider`:
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 body after which the entire
294    /// suffix is replaced by a parenthesized short hash `(<short-hash>)`
295    /// (pnpm's `createPeerDepGraphHash`). pnpm's default is 1000.
296    pub peers_suffix_max_length: usize,
297}
298
299impl Default for PeerContextOptions {
300    fn default() -> Self {
301        Self {
302            dedupe_peer_dependents: true,
303            dedupe_peers: false,
304            resolve_from_workspace_root: true,
305            peers_suffix_max_length: 1000,
306        }
307    }
308}
309
310/// Compute peer-context suffixes over an already-resolved graph.
311///
312/// Takes a *canonical* graph — one `LockedPackage` per `(name,
313/// version)` with `peer_dependencies` populated — and produces a
314/// *contextualized* graph whose keys and transitive references carry
315/// `(peer@ver)` suffixes when packages resolve peers differently in
316/// different subtrees. Drives the sibling-symlink wiring in
317/// `aube-linker` for peers, so every fetch/materialize site sees a
318/// per-context identity for any package whose peers disambiguate.
319///
320/// Public so lockfile-driven installs can run the pass over graphs
321/// parsed from npm/yarn/bun lockfiles (which emit canonical form —
322/// no peer suffixes — and would otherwise leave peer-dependent
323/// packages without their peers as `.aube/<pkg>/node_modules/<peer>`
324/// siblings). Fresh resolves call it internally from
325/// `Resolver::resolve`.
326pub fn apply_peer_contexts(
327    canonical: LockfileGraph,
328    options: &PeerContextOptions,
329) -> Result<LockfileGraph, crate::Error> {
330    const MAX_ITERATIONS: usize = 16;
331    let mut current = canonical;
332    let mut converged = false;
333    // Hash both keys and dependency tails. A peer-context iteration can
334    // rewrite a dependency value to point at an existing key without
335    // adding a new key, so a key-only convergence test ships partially
336    // rewritten tails. Linker reads tails directly to locate sibling
337    // symlink targets, stale tails produce broken `node_modules`.
338    let graph_hash = |g: &LockfileGraph| -> u64 {
339        let total_deps: usize = g.packages.values().map(|p| p.dependencies.len()).sum();
340        let mut tokens: Vec<&str> = Vec::with_capacity(g.packages.len() * 3 + total_deps * 2);
341        for (k, pkg) in &g.packages {
342            tokens.push(k.as_str());
343            tokens.push("\x1f");
344            for (name, tail) in &pkg.dependencies {
345                tokens.push(name.as_str());
346                tokens.push(tail.as_str());
347            }
348            tokens.push("\x1e");
349        }
350        aube_util::hash::ordered_seq_hash(tokens.iter().copied())
351    };
352    // Carry the post-iteration hash forward as the next iteration's
353    // pre-hash. Saves one full graph walk per iteration (the loop runs
354    // up to 16 times; each `graph_hash` allocates a Vec<&str> sized
355    // to `pkgs * 3 + deps * 2` tokens — ~25k entries on a 1000-pkg
356    // graph). One hash per iter instead of two.
357    let mut before = graph_hash(&current);
358    for i in 0..MAX_ITERATIONS {
359        let after_once = apply_peer_contexts_once(current, options);
360        let next = if options.dedupe_peer_dependents {
361            dedupe_peer_variants(after_once)
362        } else {
363            after_once
364        };
365        let after = graph_hash(&next);
366        if before == after {
367            tracing::debug!("peer-context pass converged after {i} iteration(s)");
368            current = next;
369            converged = true;
370            break;
371        }
372        current = next;
373        before = after;
374    }
375    if !converged {
376        // Iteration cap hit. Returning the partial graph would ship
377        // broken node_modules. Now fatal.
378        tracing::error!(
379            code = aube_codes::errors::ERR_AUBE_PEER_CONTEXT_NOT_CONVERGED,
380            max_iterations = MAX_ITERATIONS,
381            "peer-context hit MAX_ITERATIONS={MAX_ITERATIONS} without convergence"
382        );
383        return Err(crate::Error::PeerContextDivergence(MAX_ITERATIONS));
384    }
385    // Propagate each package's peer-suffix segments up through its
386    // non-peer-declaring ancestors so a parent that pulls in a peer-
387    // bearing descendant carries the same `(peer@version)` suffix on
388    // its own dep_path. Matches pnpm's lockfile shape — pnpm 9 emits
389    // every peer-bearing package's resolved peer set on every
390    // ancestor in the chain (importer rows included), even when the
391    // ancestor itself doesn't declare those peers. Without the
392    // propagation aube would tag the suffix only on the package that
393    // declares peers, which differs from pnpm-lock.yaml in the
394    // `importers:` section any time a non-peer-declaring middle node
395    // sits between an importer and its peer-bearing descendant.
396    //
397    // Runs after the fixed-point loop converges so all self-suffixes
398    // are stable, and before `dedupe_peer_suffixes` so the latter's
399    // `(name@version)` → `(version)` collapse acts on the propagated
400    // form too.
401    let current = propagate_peer_suffixes_to_ancestors(current, options);
402    // `dedupe-peers=true` rewrites the parenthesized peer suffix to
403    // drop the `name@` prefix. Done as a post-pass rather than inline
404    // so cycle detection during the fixed-point loop keeps the full
405    // `name@version` form (otherwise unrelated same-version packages
406    // would false-positive as back-references).
407    let result = if options.dedupe_peers {
408        dedupe_peer_suffixes(current)
409    } else {
410        current
411    };
412    Ok(result)
413}
414
415/// Cross-subtree peer-variant dedupe. When `dedupe-peer-dependents` is
416/// on, packages that landed at different contextualized dep_paths but
417/// resolved every declared peer to the *same* version (ignoring the
418/// nested peer suffix on each peer tail) collapse into a single
419/// canonical variant — chosen as the lexicographically smallest key in
420/// the equivalence class. References in every surviving
421/// `LockedPackage.dependencies` map and every `importers[*]` direct
422/// dep get rewritten through the old→canonical map, and the
423/// non-canonical entries are dropped from `packages`.
424///
425/// Packages whose `peer_dependencies` map is empty — i.e. the canonical
426/// base already has only one variant — are skipped.
427pub(crate) fn dedupe_peer_variants(graph: LockfileGraph) -> LockfileGraph {
428    let canonical_base = |key: &str| -> String { canonical_tail(key).to_string() };
429    // Only the peer-bearing part of the resolved peer tail is
430    // comparable across subtrees — the nested suffix could differ even
431    // for peer-equivalent variants on mid-iterations of the outer
432    // fixed-point loop.
433    let peer_base = |tail: &str| -> String { canonical_tail(tail).to_string() };
434
435    // Group dep_paths by their peer-free base name.
436    let mut groups: BTreeMap<String, Vec<String>> = BTreeMap::new();
437    for key in graph.packages.keys() {
438        groups
439            .entry(canonical_base(key))
440            .or_default()
441            .push(key.clone());
442    }
443
444    let mut rewrite: BTreeMap<String, String> = BTreeMap::new();
445    for (_base, mut keys) in groups {
446        if keys.len() < 2 {
447            continue;
448        }
449        // Deterministic order for canonical selection + stable hashing.
450        keys.sort();
451        // Union-find over equivalence classes. Two variants are
452        // equivalent when each declared peer name resolves to the same
453        // peer base in both (or is missing from both).
454        let mut parent: Vec<usize> = (0..keys.len()).collect();
455        fn find(parent: &mut [usize], i: usize) -> usize {
456            if parent[i] == i {
457                i
458            } else {
459                let r = find(parent, parent[i]);
460                parent[i] = r;
461                r
462            }
463        }
464        for i in 0..keys.len() {
465            for j in (i + 1)..keys.len() {
466                let pa = &graph.packages[&keys[i]];
467                let pb = &graph.packages[&keys[j]];
468                // Same canonical version is required — packages with
469                // different versions but the same name would share no
470                // canonical_base only if the name-without-version
471                // collided, which doesn't happen (version is in the
472                // base). Still, belt-and-suspenders.
473                if pa.version != pb.version {
474                    continue;
475                }
476                let peer_names: BTreeSet<&String> = pa
477                    .peer_dependencies
478                    .keys()
479                    .chain(pb.peer_dependencies.keys())
480                    .collect();
481                let equivalent = peer_names.iter().all(|name| {
482                    match (
483                        pa.dependencies.get(name.as_str()),
484                        pb.dependencies.get(name.as_str()),
485                    ) {
486                        (Some(va), Some(vb)) => peer_base(va) == peer_base(vb),
487                        (None, None) => true,
488                        _ => false,
489                    }
490                });
491                if equivalent {
492                    let ri = find(&mut parent, i);
493                    let rj = find(&mut parent, j);
494                    if ri != rj {
495                        parent[ri] = rj;
496                    }
497                }
498            }
499        }
500        // Build class → canonical (smallest key) mapping. Using
501        // index-based iteration here because `find` takes a mutable
502        // reference into `parent`, so holding an immutable borrow
503        // from `keys.iter()` at the same time would double-borrow.
504        #[allow(clippy::needless_range_loop)]
505        {
506            let mut class_rep: BTreeMap<usize, String> = BTreeMap::new();
507            for i in 0..keys.len() {
508                let root = find(&mut parent, i);
509                class_rep
510                    .entry(root)
511                    .and_modify(|cur| {
512                        if keys[i] < *cur {
513                            *cur = keys[i].clone();
514                        }
515                    })
516                    .or_insert_with(|| keys[i].clone());
517            }
518            for i in 0..keys.len() {
519                let root = find(&mut parent, i);
520                let canonical = class_rep[&root].clone();
521                if keys[i] != canonical {
522                    rewrite.insert(keys[i].clone(), canonical);
523                }
524            }
525        }
526    }
527
528    if rewrite.is_empty() {
529        return graph;
530    }
531
532    // Rewrite package dependency tails and keep only canonicals.
533    let LockfileGraph {
534        importers,
535        packages,
536        settings,
537        overrides,
538        package_extensions_checksum,
539        pnpmfile_checksum,
540        ignored_optional_dependencies,
541        times,
542        skipped_optional_dependencies,
543        catalogs,
544        bun_config_version,
545        patched_dependencies,
546        trusted_dependencies,
547        runtimes,
548        extra_fields,
549        workspace_extra_fields,
550    } = graph;
551
552    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
553    for (key, mut pkg) in packages {
554        if rewrite.contains_key(&key) {
555            continue;
556        }
557        for (dep_name, dep_tail) in pkg.dependencies.iter_mut() {
558            let dep_key = format!("{dep_name}@{dep_tail}");
559            if let Some(canonical) = rewrite.get(&dep_key) {
560                let new_tail = canonical
561                    .strip_prefix(&format!("{dep_name}@"))
562                    .map(|s| s.to_string())
563                    .unwrap_or_else(|| canonical.clone());
564                *dep_tail = new_tail;
565            }
566        }
567        new_packages.insert(key, pkg);
568    }
569
570    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
571    for (importer_path, deps) in importers {
572        let mut new_deps = Vec::with_capacity(deps.len());
573        for mut dep in deps {
574            if let Some(canonical) = rewrite.get(&dep.dep_path) {
575                dep.dep_path = canonical.clone();
576            }
577            new_deps.push(dep);
578        }
579        new_importers.insert(importer_path, new_deps);
580    }
581
582    LockfileGraph {
583        importers: new_importers,
584        packages: new_packages,
585        settings,
586        overrides,
587        package_extensions_checksum,
588        pnpmfile_checksum,
589        ignored_optional_dependencies,
590        times,
591        skipped_optional_dependencies,
592        catalogs,
593        bun_config_version,
594        patched_dependencies,
595        trusted_dependencies,
596        runtimes,
597        extra_fields,
598        workspace_extra_fields,
599    }
600}
601
602/// Single pass of the peer-context computation. See `apply_peer_contexts`
603/// for the wrapping fixed-point loop.
604///
605/// Algorithm per visited package P, reached at some point in a DFS from an
606/// importer with `ancestor_scope: name -> peer provider`:
607///
608///  1. For each peer name declared by P, look it up in `ancestor_scope`
609///     (nearest-ancestor-wins, since the scope is rebuilt per recursion).
610///     If missing, fall back to P's own entry in `dependencies` — the BFS
611///     enqueue auto-installed it as a transitive, matching pnpm's
612///     `auto-install-peers=true` default.
613///  2. Sort the (peer_name, resolution) pairs and serialize as
614///     `(n1@v1)(n2@v2)…` for the suffix.
615///  3. Produce a contextualized dep_path `name@version{suffix}`. If that
616///     key is already in `out_packages` (or currently on the DFS stack via
617///     `visiting`), short-circuit — we've already emitted this variant.
618///  4. Build a new scope for P's children by merging the ancestor scope
619///     with P's own `dependencies` and the resolved peer map. Recurse.
620///  5. Emit the contextualized LockedPackage.
621///
622/// Cycles: protected by `visiting` — if a package is re-entered via a
623/// dependency cycle, we return the already-computed dep_path without
624/// recursing again. The peer context is fixed at first visit; any cycle
625/// traversal uses whatever context was live at that first visit.
626fn apply_peer_contexts_once(
627    canonical: LockfileGraph,
628    options: &PeerContextOptions,
629) -> LockfileGraph {
630    let mut out_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
631    let mut new_importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
632
633    // Name-indexed view of the canonical graph, shared across
634    // every `visit_peer_context` call in this pass. Peer-resolution
635    // scan-by-name is the resolver's hottest inner loop. Without
636    // this, each peer runs `O(|graph|)` per package per fixed-point
637    // iter. Prebuilt index drops the scan to O(1) average.
638    //
639    // Pre-size to the package count: most graphs have one entry per
640    // name and only a handful of multi-version names, so capacity
641    // headroom is small and the upper bound saves 8+ rehashes on
642    // medium graphs (default 16 → 2048 covers ~1200 pkgs).
643    let mut name_index: FxHashMap<&str, Vec<&LockedPackage>> =
644        FxHashMap::with_capacity_and_hasher(canonical.packages.len(), Default::default());
645    for pkg in canonical.packages.values() {
646        name_index.entry(pkg.name.as_str()).or_default().push(pkg);
647    }
648
649    // Root-importer scope used by `resolve-peers-from-workspace-root`.
650    // Computed once from the canonical input so it reflects the
651    // contextualized state of every root dep on fixed-point iterations
652    // 2+ — same logic as per-importer `importer_scope` below.
653    let root_scope: FxHashMap<String, PeerProvider> = canonical
654        .importers
655        .get(".")
656        .map(|deps| scope_map_from_deps(&canonical, deps))
657        .unwrap_or_default();
658
659    for (importer_path, direct_deps) in &canonical.importers {
660        // An importer's own direct deps are in scope for its children's
661        // peer resolution — this is how pnpm's "auto-install at the root"
662        // path gets peer links that point at root-level packages.
663        //
664        // Use the *full contextualized tail* off each DirectDep rather
665        // than the package's plain version. On Pass 1 of the fixed-point
666        // loop the tail is canonical and equal to `p.version`; on Pass 2+
667        // it's already contextualized, and passing the plain version
668        // would make descendants look up keys that don't exist in the
669        // (now-nested) graph.
670        let importer_scope = scope_map_from_deps(&canonical, direct_deps);
671
672        let mut new_deps = Vec::with_capacity(direct_deps.len());
673        for dep in direct_deps {
674            // `visiting` is the DFS stack guard for this particular descent
675            // — reset per direct dep so we don't incorrectly flag a package
676            // as a cycle when it's reached again from a sibling subtree.
677            // The shared `out_packages` still dedupes across siblings since
678            // the second visit hits the `contains_key` short-circuit below.
679            //
680            // Invariant (see `visit_peer_context` for the detailed handling):
681            // a dep_path returned from the cycle-break branch may not yet
682            // be present in `out_packages` at the moment of return, because
683            // the package is still being assembled up the call stack. The
684            // parent that records the returned tail will complete its own
685            // insertion before the recursion unwinds, so by the time
686            // anything reads the graph, every referenced dep_path exists.
687            let mut visiting: FxHashSet<String> = FxHashSet::default();
688            let new_dep_path = visit_peer_context(
689                &dep.dep_path,
690                &canonical,
691                &name_index,
692                &importer_scope,
693                &root_scope,
694                &mut out_packages,
695                &mut visiting,
696                options,
697            )
698            .unwrap_or_else(|| dep.dep_path.clone());
699            new_deps.push(DirectDep {
700                name: dep.name.clone(),
701                dep_path: new_dep_path,
702                dep_type: dep.dep_type,
703                specifier: dep.specifier.clone(),
704            });
705        }
706        new_importers.insert(importer_path.clone(), new_deps);
707    }
708
709    // Any canonical package that was never reached by the DFS (orphaned
710    // from every importer) is dropped — that matches the filter_deps
711    // semantics and avoids emitting dead entries into the lockfile.
712
713    LockfileGraph {
714        importers: new_importers,
715        packages: out_packages,
716        // The post-pass is pure — settings + overrides carry through
717        // from the input graph untouched.
718        settings: canonical.settings,
719        overrides: canonical.overrides,
720        package_extensions_checksum: canonical.package_extensions_checksum,
721        pnpmfile_checksum: canonical.pnpmfile_checksum,
722        ignored_optional_dependencies: canonical.ignored_optional_dependencies,
723        runtimes: canonical.runtimes,
724        times: canonical.times,
725        skipped_optional_dependencies: canonical.skipped_optional_dependencies,
726        catalogs: canonical.catalogs,
727        bun_config_version: canonical.bun_config_version,
728        patched_dependencies: canonical.patched_dependencies,
729        trusted_dependencies: canonical.trusted_dependencies,
730        extra_fields: canonical.extra_fields,
731        workspace_extra_fields: canonical.workspace_extra_fields,
732    }
733}
734
735/// DFS helper for `apply_peer_contexts`. Returns the peer-contextualized
736/// dep_path of the visited package, or `None` if the canonical package is
737/// missing (shouldn't happen in practice but we degrade gracefully).
738/// Does `value` contain a peer-suffix reference to `canonical` as a
739/// proper name@version boundary (i.e. preceded by `(` and followed by
740/// `(` / `)` / end-of-string)? Used by the peer-context pass to detect
741/// when a nested tail loops back to the current package so it can
742/// short-circuit the chain instead of growing the suffix forever.
743/// Everything before the first `(` — i.e. the canonical `name@version`
744/// part of a dep-path with the peer-context suffix stripped. Returns
745/// the original string when no `(` is present. Borrowed; callers that
746/// need owned bump with `.to_string()`.
747fn canonical_tail(s: &str) -> &str {
748    s.split('(').next().unwrap_or(s)
749}
750
751/// A peer provider's graph target and semver identity.
752///
753/// Those are normally the same tail. For linked directories, the target
754/// remains the content-addressed local dep path while peer matching and
755/// suffixes use the target manifest's version.
756#[derive(Debug, Clone)]
757struct PeerProvider {
758    /// Tail used to find and link the package in the graph.
759    target_tail: String,
760    /// Tail used for semver checks and the consumer's peer suffix.
761    context_tail: String,
762}
763
764fn peer_provider(graph: &LockfileGraph, name: &str, target_tail: &str) -> PeerProvider {
765    let context_tail =
766        aube_lockfile::resolve_dep_edge(name, target_tail, |key| graph.packages.contains_key(key))
767            .and_then(|key| graph.packages.get(&key))
768            .filter(|pkg| {
769                matches!(
770                    pkg.local_source,
771                    Some(LocalSource::Directory(_) | LocalSource::Link(_) | LocalSource::Portal(_))
772                )
773            })
774            .map(|pkg| pkg.version.clone())
775            .unwrap_or_else(|| target_tail.to_string());
776    PeerProvider {
777        target_tail: target_tail.to_string(),
778        context_tail,
779    }
780}
781
782/// Build a `name → provider` map from a direct-dependency slice.
783///
784/// Used for the workspace root and for each importer's own scope inside
785/// `apply_peer_contexts_once`.
786fn scope_map_from_deps(
787    graph: &LockfileGraph,
788    deps: &[DirectDep],
789) -> FxHashMap<String, PeerProvider> {
790    let mut out = FxHashMap::with_capacity_and_hasher(deps.len(), Default::default());
791    for d in deps {
792        let prefix_len = d.name.len() + 1;
793        let tail = if d.dep_path.len() > prefix_len
794            && d.dep_path.as_bytes().get(d.name.len()) == Some(&b'@')
795            && d.dep_path.as_bytes().starts_with(d.name.as_bytes())
796        {
797            d.dep_path[prefix_len..].to_string()
798        } else {
799            d.dep_path.clone()
800        };
801        out.insert(d.name.clone(), peer_provider(graph, &d.name, &tail));
802    }
803    out
804}
805
806/// True when `s` is a single hashed peer suffix `(<32 lowercase hex>)`
807/// as emitted by [`effective_peer_suffix`] once a suffix exceeds
808/// `peersSuffixMaxLength`. The hashed form discards the textual peer
809/// set, so the propagation pass recognizes such keys and leaves them
810/// untouched (their per-peer contribution can't be recovered). A real
811/// peer segment always contains `@`, so the all-hex check can't
812/// false-positive on a `(name@version)` group.
813pub(crate) fn is_hashed_peer_suffix(s: &str) -> bool {
814    let Some(inner) = s.strip_prefix('(').and_then(|x| x.strip_suffix(')')) else {
815        return false;
816    };
817    inner.len() == 32
818        && inner
819            .bytes()
820            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
821}
822
823/// pnpm's `createShortHash`: the lowercase SHA-256 hex digest of
824/// `input`, truncated to its first 32 characters (16 bytes).
825fn short_peer_hash(input: &str) -> String {
826    use sha2::{Digest, Sha256};
827    let digest = Sha256::digest(input.as_bytes());
828    let mut out = String::with_capacity(32);
829    for byte in digest.iter().take(16) {
830        use std::fmt::Write;
831        let _ = write!(out, "{byte:02x}");
832    }
833    out
834}
835
836/// Final peer-context tail for an already-built `(name@version)…`
837/// `suffix`, mirroring pnpm's `createPeerDepGraphHash`. pnpm derives
838/// `dirName` by joining the sorted peer ids with `)(` — i.e. the suffix
839/// without its outer parens — hashes it with `createShortHash` when it
840/// exceeds `peersSuffixMaxLength`, and always re-wraps the result in a
841/// single `(...)`. Keeping that shape means a capped suffix aube writes
842/// into `pnpm-lock.yaml` is `(<short-hash>)` — byte-compatible with
843/// pnpm — never a bare `_<hex>` marker.
844pub(crate) fn effective_peer_suffix(suffix: &str, max_length: usize) -> String {
845    // `dir_name` == pnpm's `dirName`: the suffix without the outer `(`
846    // and `)` that wrap the first and last peer segment. `suffix` is
847    // always a concatenation of `(…)` groups here, so stripping one
848    // byte off each end is safe; an empty suffix degrades to empty.
849    let dir_name = suffix
850        .strip_prefix('(')
851        .and_then(|s| s.strip_suffix(')'))
852        .unwrap_or(suffix);
853    if dir_name.len() > max_length {
854        format!("({})", short_peer_hash(dir_name))
855    } else {
856        suffix.to_string()
857    }
858}
859
860pub(crate) fn contains_canonical_back_ref(value: &str, canonical: &str) -> bool {
861    let bytes = value.as_bytes();
862    let target = canonical.as_bytes();
863    if target.is_empty() || target.len() > bytes.len() {
864        return false;
865    }
866    let mut i = 0;
867    while i + target.len() <= bytes.len() {
868        if &bytes[i..i + target.len()] == target {
869            let before = if i == 0 { b'\0' } else { bytes[i - 1] };
870            let after = bytes.get(i + target.len()).copied().unwrap_or(b'\0');
871            let before_ok = before == b'(';
872            let after_ok = after == b'(' || after == b')' || after == b'\0';
873            if before_ok && after_ok {
874                return true;
875            }
876        }
877        i += 1;
878    }
879    false
880}
881
882/// Split a dep_path tail's peer suffix into outer-level paren segments
883/// (each ending in a balanced `)`). Returns each segment with its parens
884/// included — `react-dom@18.2.0(react@18.2.0)(scheduler@1.0.0)` yields
885/// `["(react@18.2.0)", "(scheduler@1.0.0)"]`; nested forms like
886/// `consumer@1.0.0(react-dom@18.2.0(react@18.2.0))` yield the single
887/// segment `["(react-dom@18.2.0(react@18.2.0))"]` with the inner
888/// `(react@18.2.0)` preserved verbatim inside it.
889///
890/// Used by `propagate_peer_suffixes_to_ancestors` to lift a child's
891/// peer segments onto its non-peer-declaring ancestors.
892fn outer_paren_segments(s: &str) -> Vec<&str> {
893    let bytes = s.as_bytes();
894    let mut segments = Vec::new();
895    let mut i = 0;
896    // Skip canonical `name@version` head — anything up to the first `(`.
897    while i < bytes.len() && bytes[i] != b'(' {
898        i += 1;
899    }
900    while i < bytes.len() {
901        if bytes[i] != b'(' {
902            i += 1;
903            continue;
904        }
905        let start = i;
906        let mut depth: i32 = 0;
907        while i < bytes.len() {
908            match bytes[i] {
909                b'(' => depth += 1,
910                b')' => {
911                    depth -= 1;
912                    if depth == 0 {
913                        i += 1;
914                        segments.push(&s[start..i]);
915                        break;
916                    }
917                }
918                _ => {}
919            }
920            i += 1;
921        }
922        if depth != 0 {
923            // Unbalanced — bail out of further segmenting. Shouldn't
924            // happen on output of `apply_peer_contexts_once`, where every
925            // suffix segment is balanced by construction.
926            break;
927        }
928    }
929    segments
930}
931
932/// Extract the peer name from a paren segment like `(@scope/name@1.2.3)`
933/// or `(name@1.2.3(nested@9.9.9))`. The peer name is everything between
934/// the opening `(` and the LAST `@` that occurs before any nested `(`.
935/// Scoped packages contain two `@`s (`@scope/name@version`) and we want
936/// the rightmost outer one.
937///
938/// Returns `None` if the segment doesn't start with `(` or has no
939/// usable `@` separator.
940fn peer_name_from_segment(seg: &str) -> Option<&str> {
941    let inner = seg.strip_prefix('(')?;
942    // Scan for the last `@` that occurs before any `(` (the version-or-
943    // nested boundary). For a flat segment `name@version` everything
944    // between `(` and the last `@` is the name; for a nested segment
945    // `name@version(inner)` the last `@` BEFORE the first inner `(` is
946    // the boundary. We search up to the first `(` (or end-of-string).
947    let scan_end = inner.find('(').unwrap_or(inner.len());
948    let head = &inner[..scan_end];
949    head.rfind('@').map(|idx| &head[..idx])
950}
951
952/// Collect every peer name reachable from a set of outer-paren segments,
953/// recursing into nested `(name@version(...))` forms so that a self
954/// segment like `(helper@1.0.0(core@1.0.0))` reports both `helper` and
955/// `core`. Used by `propagate_peer_suffixes_to_ancestors` to suppress
956/// flat-segment additions for peer names already encoded transitively
957/// in a package's own (possibly nested) self-suffix.
958fn peer_names_in_segments_recursive(segments: &[&str]) -> BTreeSet<String> {
959    let mut names = BTreeSet::new();
960    for seg in segments {
961        if let Some(name) = peer_name_from_segment(seg) {
962            names.insert(name.to_string());
963        }
964        // Recurse into the nested portion (everything after the first
965        // inner `(` and before the final `)`).
966        let Some(inner) = seg.strip_prefix('(').and_then(|s| s.strip_suffix(')')) else {
967            continue;
968        };
969        if let Some(open) = inner.find('(') {
970            let nested = &inner[open..];
971            let nested_segments = outer_paren_segments(nested);
972            for nested_name in peer_names_in_segments_recursive(&nested_segments) {
973                names.insert(nested_name);
974            }
975        }
976    }
977    names
978}
979
980/// Walk the resolved graph from each node and accumulate the union of
981/// peer-suffix segments contributed by self + every reachable
982/// descendant (gated on the package having no declared peers of its
983/// own), then rewrite each node's dep_path to embed that union.
984///
985/// Why: pnpm's lockfile shape tags non-peer-declaring intermediaries
986/// with the same `(peer@version)` suffix their peer-declaring
987/// descendants produced — so a parent that pulls in a peer-bearing
988/// child carries the resolved peer set on its own dep_path. aube's
989/// `apply_peer_contexts_once` only emits the suffix on the package
990/// that *declares* the peer; without this post-pass an importer row
991/// for `parent → leaf(peer)` would render `parent: 1.0.0` (no
992/// suffix) where pnpm renders `parent: 1.0.0(peer@v)`.
993///
994/// pnpm-parity gate (inferred from observed lockfile shape): **a
995/// package gets descendant-peer propagation only if its own
996/// `peerDependencies` map is empty.** Packages that declare their
997/// own peers have an authoritative self-suffix encoding exactly the
998/// peers they care about; descendant peers don't bubble through
999/// because the descendant peers belong to a NESTED child, which the
1000/// snapshot already encodes via the nested-tail form (see
1001/// `apply_peer_contexts_once`'s nested-suffix handling). Two
1002/// observable shapes this gate lines up with:
1003///   - `@testing-library/react@14.0.0(react@18.2.0)(react-dom@18.2.0(react@18.2.0))`
1004///     — declares peers, gets self-suffix only; `@types/react` from a
1005///     descendant doesn't bubble up.
1006///   - `abc-parent-with-missing-peers@1.0.0(peer-a@…)(peer-b@…)(peer-c@…)`
1007///     — no declared peers, picks up descendant peers from `abc`.
1008///
1009/// Algorithm:
1010///  1. Build a forward dep map: `pkg_key → [child_key]` from each
1011///     LockedPackage's `dependencies`.
1012///  2. Memoized DFS. For each node, compute
1013///     `cumulative_segments = outer_paren_segments(node.key)`. If the
1014///     node has no declared peers, also union in
1015///     `⋃ cumulative(child)` (gated by the rule above).
1016///  3. Cycles short-circuit via a `visiting` guard — cycle members
1017///     can't add new peers from each other beyond what reaches them
1018///     through non-cycle paths, so returning the empty set on
1019///     re-entry is safe (the non-cycle entry path computes the full
1020///     set).
1021///  4. Dedupe by peer name. Suppressed names: every peer name reachable
1022///     transitively in self-segments (so `(helper@1(core@1))` covers
1023///     `core` and a flat `(core@1)` from descendants is dropped) plus
1024///     the package's own canonical name (mutual-peer cycle break).
1025///  5. Build a rewrite map `old_key → new_key` and apply to package
1026///     keys, dep edges (each dep's stored tail), and importer
1027///     dep_paths.
1028fn propagate_peer_suffixes_to_ancestors(
1029    graph: LockfileGraph,
1030    options: &PeerContextOptions,
1031) -> LockfileGraph {
1032    // Forward dep map. Edges that don't resolve to a present package
1033    // (e.g. an unresolved peer that `detect_unmet_peers` will warn
1034    // about) are dropped — they can't contribute cumulative peers.
1035    let mut forward: BTreeMap<String, Vec<String>> = BTreeMap::new();
1036    // Per-package "has declared peers" lookup. Packages that declare
1037    // their own peers don't accept descendant-peer propagation (see
1038    // the rule in the doc comment above).
1039    let mut has_own_peers: BTreeMap<String, bool> = BTreeMap::new();
1040    // Per-package set of dependency names a package supplies itself
1041    // (regular or optional). A peer a descendant needs is *resolved* at
1042    // the nearest ancestor that supplies it, so the `(peer@version)`
1043    // suffix must stop there — that supplier, and everything above it,
1044    // stays bare. pnpm leaves e.g. `tinyglobby@0.2.17` bare because it
1045    // lists `picomatch` in its own `dependencies` (resolving `fdir`'s
1046    // optional peer); only `fdir` keeps the suffix. Without this gate the
1047    // suffix leaks onto every ancestor up to the importer.
1048    let mut provides: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
1049    for (key, pkg) in &graph.packages {
1050        let children: Vec<String> = pkg
1051            .dependencies
1052            .iter()
1053            .map(|(n, t)| format!("{n}@{t}"))
1054            .filter(|k| graph.packages.contains_key(k))
1055            .collect();
1056        forward.insert(key.clone(), children);
1057        has_own_peers.insert(key.clone(), !pkg.peer_dependencies.is_empty());
1058        let supplied: BTreeSet<String> = pkg
1059            .dependencies
1060            .keys()
1061            .chain(pkg.optional_dependencies.keys())
1062            .cloned()
1063            .collect();
1064        provides.insert(key.clone(), supplied);
1065    }
1066
1067    // Memoized DFS. `cumulative` stores the by-name segment map per
1068    // package key; `visiting` is the cycle-break stack.
1069    let mut cumulative: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
1070    let mut visiting: BTreeSet<String> = BTreeSet::new();
1071
1072    fn collect(
1073        key: &str,
1074        forward: &BTreeMap<String, Vec<String>>,
1075        has_own_peers: &BTreeMap<String, bool>,
1076        provides: &BTreeMap<String, BTreeSet<String>>,
1077        cumulative: &mut BTreeMap<String, BTreeMap<String, String>>,
1078        visiting: &mut BTreeSet<String>,
1079    ) -> BTreeMap<String, String> {
1080        if let Some(c) = cumulative.get(key) {
1081            return c.clone();
1082        }
1083        if !visiting.insert(key.to_string()) {
1084            // Cycle: contribute nothing. Whichever cycle member is
1085            // first reached from outside the cycle will compute the
1086            // full set; the visit guard cap on the others prevents
1087            // infinite recursion. Edge case: a fully-isolated cycle
1088            // never gets a non-cycle entry, in which case all members
1089            // compute empty cumulatives — that's identical to their
1090            // canonical state, so they get no rewrite. Acceptable.
1091            return BTreeMap::new();
1092        }
1093
1094        // Self-suffix segments. Each segment becomes one (name → segment)
1095        // entry. Nested segments like `(react-dom@18.2.0(react@18.2.0))`
1096        // are preserved as a single segment with the nested form intact.
1097        let self_segments = outer_paren_segments(key);
1098        let mut acc: BTreeMap<String, String> = BTreeMap::new();
1099        for seg in &self_segments {
1100            if let Some(name) = peer_name_from_segment(seg) {
1101                acc.entry(name.to_string())
1102                    .or_insert_with(|| seg.to_string());
1103            }
1104        }
1105
1106        // Pnpm-parity gate: only packages with no declared peers absorb
1107        // descendant-peer propagation. The cycle-break visiting guard
1108        // is still released for symmetry with the non-gated branch.
1109        if has_own_peers.get(key).copied().unwrap_or(false) {
1110            visiting.remove(key);
1111            cumulative.insert(key.to_string(), acc.clone());
1112            return acc;
1113        }
1114
1115        // Names suppressed when merging child contributions:
1116        //   1. Every peer name reachable transitively in self segments —
1117        //      e.g. a self segment `(helper@1.0.0(core@1.0.0))` covers
1118        //      both `helper` and `core`, so a descendant flat-listing
1119        //      `(core@1.0.0)` shouldn't double-emit. Pnpm lists each
1120        //      peer name once; we match.
1121        //   2. The package's own canonical name — for mutual-peer
1122        //      cycles `a` peers on `b` and `b` peers on `a`, the
1123        //      descendant set lifts `(a@…)` back up onto `a` itself,
1124        //      which would write `a@1.0.0(a@…)(b@…)`. Self-listing
1125        //      isn't valid pnpm shape; suppress it. (Reachable here
1126        //      only when this branch handles a node with no declared
1127        //      peers — but defensive in case future graph shapes
1128        //      surface a self-cycle through a peer-less node.)
1129        let canonical_name = canonical_tail(key)
1130            .rsplit_once('@')
1131            .map(|(name, _ver)| name.to_string())
1132            .unwrap_or_default();
1133        let mut suppressed: BTreeSet<String> = peer_names_in_segments_recursive(&self_segments);
1134        if !canonical_name.is_empty() {
1135            suppressed.insert(canonical_name);
1136        }
1137        // A peer this package supplies itself is resolved here, so it must
1138        // neither decorate this package's dep_path nor propagate above it
1139        // (pnpm stops the suffix at the supplier). This is what keeps a
1140        // supplier like `tinyglobby` (and its non-peer ancestors) bare
1141        // while `fdir`, which only *declares* the peer, keeps its suffix.
1142        if let Some(supplied) = provides.get(key) {
1143            suppressed.extend(supplied.iter().cloned());
1144        }
1145
1146        // Child contributions.
1147        if let Some(children) = forward.get(key) {
1148            for child in children {
1149                let child_peers = collect(
1150                    child,
1151                    forward,
1152                    has_own_peers,
1153                    provides,
1154                    cumulative,
1155                    visiting,
1156                );
1157                for (name, seg) in child_peers {
1158                    if suppressed.contains(&name) {
1159                        continue;
1160                    }
1161                    acc.entry(name).or_insert(seg);
1162                }
1163            }
1164        }
1165        visiting.remove(key);
1166        cumulative.insert(key.to_string(), acc.clone());
1167        acc
1168    }
1169
1170    // Compute cumulative for every package + every importer DirectDep
1171    // root. Done in stable order so the lex-smaller old-key tiebreaker
1172    // below is deterministic.
1173    let pkg_keys: Vec<String> = graph.packages.keys().cloned().collect();
1174    for key in &pkg_keys {
1175        collect(
1176            key,
1177            &forward,
1178            &has_own_peers,
1179            &provides,
1180            &mut cumulative,
1181            &mut visiting,
1182        );
1183    }
1184    for deps in graph.importers.values() {
1185        for dep in deps {
1186            collect(
1187                &dep.dep_path,
1188                &forward,
1189                &has_own_peers,
1190                &provides,
1191                &mut cumulative,
1192                &mut visiting,
1193            );
1194        }
1195    }
1196
1197    // Build rewrite map. A package's new key is its canonical_base
1198    // (`name@version`) plus the cumulative segments concatenated in
1199    // peer-name lex order — same order `apply_peer_contexts_once`
1200    // already produces for self segments, so when a package's
1201    // cumulative is identical to its self set the rewrite is a no-op
1202    // and we skip it.
1203    //
1204    // Hashed-suffix keys (`name@version(<short-hash>)`, produced when a
1205    // package's own peer suffix exceeded `peersSuffixMaxLength`) are
1206    // left untouched. The hash form discards the textual peer set
1207    // by design — `outer_paren_segments` can't recover its
1208    // contribution, so any rewrite we built for it would either drop
1209    // the hash entirely (losing identity) or merge an incomplete
1210    // descendant set with the hashed self. Preserving the original
1211    // form is the conservative choice; pnpm's parity gap in that
1212    // regime is bounded by the hash collision space anyway.
1213    //
1214    // If the propagated suffix itself exceeds the cap, hash it the
1215    // same way `visit_peer_context` does for self suffixes — keeps
1216    // dep_path keys bounded across the whole graph.
1217    let mut rewrite: BTreeMap<String, String> = BTreeMap::new();
1218    for key in &pkg_keys {
1219        let Some(segments) = cumulative.get(key) else {
1220            continue;
1221        };
1222        // Git / remote-tarball (globally-shareable) packages keep a bare
1223        // dep_path keyed solely by their content-pinned URL — pnpm never
1224        // appends a `(peer@ver)` suffix to a non-registry depPath. Every
1225        // git/tarball key in a real pnpm-lock.yaml is bare even when its
1226        // subtree resolves peers: e.g. `<pkg>@<url>` sits bare above a
1227        // registry descendant like `<child>@6.5.1(@types/node@…)`.
1228        // Absorbing a descendant's `(@types/node@…)` here would (a) diverge
1229        // from the lockfile and (b) give the same content-identical tarball
1230        // a different dep_path per consuming subtree, splitting the single
1231        // shared global-virtual-store entry into duplicates (so one
1232        // content-pinned singleton would load twice → "Cannot find
1233        // module"). The descendant peers still propagate onto this node's
1234        // *registry* ancestors through `cumulative`, so a registry parent
1235        // keeps its own `(@types/node@…)` suffix; only the git/tarball node
1236        // itself stays bare.
1237        if graph
1238            .packages
1239            .get(key)
1240            .and_then(|p| p.local_source.as_ref())
1241            .is_some_and(|s| s.is_globally_shareable())
1242        {
1243            continue;
1244        }
1245        let canonical = canonical_tail(key);
1246        if is_hashed_peer_suffix(&key[canonical.len()..]) {
1247            // Original key already carries the hashed suffix `(…)` — see
1248            // comment above. Its textual peer set is irrecoverable, so
1249            // leave the key untouched.
1250            continue;
1251        }
1252        let suffix: String = segments.values().cloned().collect();
1253        let effective_suffix = effective_peer_suffix(&suffix, options.peers_suffix_max_length);
1254        let new_key = format!("{canonical}{effective_suffix}");
1255        if new_key != *key {
1256            rewrite.insert(key.clone(), new_key);
1257        }
1258    }
1259
1260    if rewrite.is_empty() {
1261        return graph;
1262    }
1263
1264    // Helper: rewrite a `dependencies` tail (the part after `name@`).
1265    // Reconstruct the target's old full key, look up its rewrite, and
1266    // strip the `name@` prefix off the result to recover the new tail.
1267    // Targets without a rewrite keep the original tail.
1268    let rewrite_tail = |child_name: &str, tail: &str| -> String {
1269        let old_key = format!("{child_name}@{tail}");
1270        match rewrite.get(&old_key) {
1271            Some(new_key) => new_key
1272                .strip_prefix(&format!("{child_name}@"))
1273                .map(|s| s.to_string())
1274                .unwrap_or_else(|| tail.to_string()),
1275            None => tail.to_string(),
1276        }
1277    };
1278
1279    let LockfileGraph {
1280        importers,
1281        packages,
1282        settings,
1283        overrides,
1284        package_extensions_checksum,
1285        pnpmfile_checksum,
1286        ignored_optional_dependencies,
1287        times,
1288        skipped_optional_dependencies,
1289        catalogs,
1290        bun_config_version,
1291        patched_dependencies,
1292        trusted_dependencies,
1293        runtimes,
1294        extra_fields,
1295        workspace_extra_fields,
1296    } = graph;
1297
1298    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
1299    for (old_key, mut pkg) in packages {
1300        let new_key = rewrite.get(&old_key).cloned().unwrap_or(old_key);
1301        for (name, tail) in pkg.dependencies.iter_mut() {
1302            *tail = rewrite_tail(name, tail);
1303        }
1304        for (name, tail) in pkg.optional_dependencies.iter_mut() {
1305            *tail = rewrite_tail(name, tail);
1306        }
1307        pkg.dep_path = new_key.clone();
1308        // Two old keys mapping to one new key: the lex-smaller old key
1309        // wins. Because `packages` is a `BTreeMap` we iterate
1310        // `(old_key, pkg)` pairs in lex order — the first insertion
1311        // for any given `new_key` is therefore the one whose old_key
1312        // sorts lowest, and `or_insert` makes every subsequent
1313        // collision a no-op. Bodies are equal in the common case
1314        // anyway (same canonical_base + same cumulative ⇒ same dep
1315        // tree), so this is effectively cosmetic determinism.
1316        new_packages.entry(new_key).or_insert(pkg);
1317    }
1318
1319    let new_importers: BTreeMap<String, Vec<DirectDep>> = importers
1320        .into_iter()
1321        .map(|(path, deps)| {
1322            let rewritten = deps
1323                .into_iter()
1324                .map(|d| {
1325                    let new_dep_path = rewrite.get(&d.dep_path).cloned().unwrap_or(d.dep_path);
1326                    DirectDep {
1327                        name: d.name,
1328                        dep_path: new_dep_path,
1329                        dep_type: d.dep_type,
1330                        specifier: d.specifier,
1331                    }
1332                })
1333                .collect();
1334            (path, rewritten)
1335        })
1336        .collect();
1337
1338    LockfileGraph {
1339        importers: new_importers,
1340        packages: new_packages,
1341        settings,
1342        overrides,
1343        package_extensions_checksum,
1344        pnpmfile_checksum,
1345        ignored_optional_dependencies,
1346        times,
1347        skipped_optional_dependencies,
1348        catalogs,
1349        bun_config_version,
1350        patched_dependencies,
1351        trusted_dependencies,
1352        runtimes,
1353        extra_fields,
1354        workspace_extra_fields,
1355    }
1356}
1357
1358/// Dedupe-peers post-pass: strip the `name@` prefix from every
1359/// parenthesized peer segment in every dep_path key and reference,
1360/// turning `react-dom@18.2.0(react@18.2.0)` into
1361/// `react-dom@18.2.0(18.2.0)`. Nested segments get the same treatment
1362/// so `a@1(b@2(c@3))` becomes `a@1(2(3))`.
1363///
1364/// Running this as a final post-pass (instead of inline during suffix
1365/// assembly in `visit_peer_context`) keeps cycle detection correct:
1366/// the detection path works against the full `name@version` form
1367/// throughout the fixed-point loop, and only the serialized output
1368/// gets the shorter form. A version-only inline approach would
1369/// false-positive on unrelated packages that coincidentally share a
1370/// version with the current package's canonical base.
1371///
1372/// Pure: no-op when `dedupe_peers` is off (caller gates the call);
1373/// otherwise rewrites every package key, every `LockedPackage.dep_path`
1374/// and `LockedPackage.dependencies` value, and every `importers[*]`
1375/// DirectDep `dep_path` through the same `apply_dedupe_peers_to_tail`
1376/// helper. Package bodies (integrity, metadata, etc.) are cloned
1377/// verbatim.
1378pub(crate) fn dedupe_peer_suffixes(graph: LockfileGraph) -> LockfileGraph {
1379    // Pass 1: compute the intended deduped key for each package and
1380    // tally how many distinct full-form keys map to it. Stripping
1381    // `name@` from suffix segments is lossy — two variants whose peer
1382    // *names* differ but whose peer *versions* coincide would collapse
1383    // onto the same deduped key (e.g. `consumer@1.0.0(foo@1.0.0)` and
1384    // `consumer@1.0.0(bar@1.0.0)` both → `consumer@1.0.0(1.0.0)`).
1385    // `dedupe_peer_variants` already merged the peer-equivalent
1386    // duplicates, so any remaining collision here represents genuinely
1387    // distinct variants — losing one would silently drop its
1388    // dependency wiring. We detect those collisions and keep both
1389    // sides in full form.
1390    let mut target_counts: BTreeMap<String, usize> = BTreeMap::new();
1391    let mut intended: BTreeMap<String, String> = BTreeMap::new();
1392    for key in graph.packages.keys() {
1393        let new_key = apply_dedupe_peers_to_key(key);
1394        *target_counts.entry(new_key.clone()).or_insert(0) += 1;
1395        intended.insert(key.clone(), new_key);
1396    }
1397    let rewrite: BTreeMap<String, String> = intended
1398        .into_iter()
1399        .map(|(old, new)| {
1400            if target_counts.get(&new).copied().unwrap_or(0) > 1 {
1401                tracing::warn!(
1402                    code = aube_codes::warnings::WARN_AUBE_PEER_DEDUPE_COLLISION,
1403                    "dedupe-peers: collision on {new} — keeping {old} in full form to avoid \
1404                     dropping a distinct peer-variant"
1405                );
1406                (old.clone(), old)
1407            } else {
1408                (old, new)
1409            }
1410        })
1411        .collect();
1412
1413    // Rewrite a `(child_name, tail)` reference by reconstructing the
1414    // target's full-form key, looking up its effective rewrite, and
1415    // stripping `child_name@` off the result to recover the tail.
1416    // Tails always follow their target package's rewrite decision,
1417    // so references stay consistent when a collision forces a target
1418    // back to full form.
1419    let rewrite_tail = |child_name: &str, tail: &str| -> String {
1420        let old_key = format!("{child_name}@{tail}");
1421        match rewrite.get(&old_key) {
1422            Some(new_key) => new_key
1423                .strip_prefix(&format!("{child_name}@"))
1424                .map(|s| s.to_string())
1425                .unwrap_or_else(|| tail.to_string()),
1426            None => apply_dedupe_peers_to_tail(tail),
1427        }
1428    };
1429
1430    let mut new_packages: BTreeMap<String, LockedPackage> = BTreeMap::new();
1431    for (old_key, pkg) in graph.packages {
1432        let new_key = rewrite
1433            .get(&old_key)
1434            .cloned()
1435            .unwrap_or_else(|| old_key.clone());
1436        let new_dependencies: BTreeMap<String, String> = pkg
1437            .dependencies
1438            .into_iter()
1439            .map(|(n, v)| {
1440                let new_v = rewrite_tail(&n, &v);
1441                (n, new_v)
1442            })
1443            .collect();
1444        let new_optional_dependencies: BTreeMap<String, String> = pkg
1445            .optional_dependencies
1446            .into_iter()
1447            .map(|(n, v)| {
1448                let new_v = rewrite_tail(&n, &v);
1449                (n, new_v)
1450            })
1451            .collect();
1452        new_packages.insert(
1453            new_key.clone(),
1454            LockedPackage {
1455                name: pkg.name,
1456                version: pkg.version,
1457                integrity: pkg.integrity,
1458                dependencies: new_dependencies,
1459                optional_dependencies: new_optional_dependencies,
1460                peer_dependencies: pkg.peer_dependencies,
1461                peer_dependencies_meta: pkg.peer_dependencies_meta,
1462                dep_path: new_key,
1463                local_source: pkg.local_source,
1464                os: pkg.os,
1465                cpu: pkg.cpu,
1466                libc: pkg.libc,
1467                bundled_dependencies: pkg.bundled_dependencies,
1468                optional: pkg.optional,
1469                transitive_peer_dependencies: pkg.transitive_peer_dependencies,
1470                tarball_url: pkg.tarball_url,
1471                registry_git_hosted: pkg.registry_git_hosted,
1472                alias_of: pkg.alias_of,
1473                yarn_checksum: pkg.yarn_checksum,
1474                engines: pkg.engines,
1475                bin: pkg.bin,
1476                declared_dependencies: pkg.declared_dependencies,
1477                license: pkg.license,
1478                funding_url: pkg.funding_url,
1479                extra_meta: pkg.extra_meta,
1480            },
1481        );
1482    }
1483
1484    let new_importers: BTreeMap<String, Vec<DirectDep>> = graph
1485        .importers
1486        .into_iter()
1487        .map(|(path, deps)| {
1488            let rewritten = deps
1489                .into_iter()
1490                .map(|d| {
1491                    let new_dep_path = rewrite
1492                        .get(&d.dep_path)
1493                        .cloned()
1494                        .unwrap_or_else(|| apply_dedupe_peers_to_key(&d.dep_path));
1495                    DirectDep {
1496                        name: d.name,
1497                        dep_path: new_dep_path,
1498                        dep_type: d.dep_type,
1499                        specifier: d.specifier,
1500                    }
1501                })
1502                .collect();
1503            (path, rewritten)
1504        })
1505        .collect();
1506
1507    LockfileGraph {
1508        importers: new_importers,
1509        packages: new_packages,
1510        settings: graph.settings,
1511        overrides: graph.overrides,
1512        package_extensions_checksum: graph.package_extensions_checksum,
1513        pnpmfile_checksum: graph.pnpmfile_checksum,
1514        ignored_optional_dependencies: graph.ignored_optional_dependencies,
1515        runtimes: graph.runtimes,
1516        times: graph.times,
1517        skipped_optional_dependencies: graph.skipped_optional_dependencies,
1518        catalogs: graph.catalogs,
1519        bun_config_version: graph.bun_config_version,
1520        patched_dependencies: graph.patched_dependencies,
1521        trusted_dependencies: graph.trusted_dependencies,
1522        extra_fields: graph.extra_fields,
1523        workspace_extra_fields: graph.workspace_extra_fields,
1524    }
1525}
1526
1527/// Strip `name@` from inside every parenthesized segment of a full
1528/// dep_path key (e.g. `react-dom@18.2.0(react@18.2.0)` →
1529/// `react-dom@18.2.0(18.2.0)`). The first `name@version` outside any
1530/// parens is preserved verbatim — that's the canonical head of the
1531/// dep_path and `dedupe-peers` only affects the peer suffix.
1532pub(crate) fn apply_dedupe_peers_to_key(key: &str) -> String {
1533    let mut parts = key.split('(');
1534    let Some(first) = parts.next() else {
1535        return key.to_string();
1536    };
1537    let mut out = String::with_capacity(key.len());
1538    out.push_str(first);
1539    for part in parts {
1540        out.push('(');
1541        // In a well-formed key, `part` looks like `name@version)` /
1542        // `name@version` / `version)` / ... We strip everything up to
1543        // and including the LAST `@` (scoped packages like
1544        // `@types/react@18.2.0` contain two `@`s; the separator is the
1545        // rightmost one). We only strip if that `@` comes before the
1546        // first `)` or `(` (i.e. the segment actually starts with
1547        // `name@`, not the outer parens closing with no name inside).
1548        if let Some(at_idx) = part.rfind('@') {
1549            let close_idx = part.find([')', '(']).unwrap_or(usize::MAX);
1550            if at_idx < close_idx {
1551                out.push_str(&part[at_idx + 1..]);
1552                continue;
1553            }
1554        }
1555        out.push_str(part);
1556    }
1557    out
1558}
1559
1560/// Same as [`apply_dedupe_peers_to_key`] but for dep-tail values
1561/// stored in `LockedPackage.dependencies` (e.g. `18.2.0(react@18.2.0)`
1562/// → `18.2.0(18.2.0)`). Tails differ from keys only by lacking the
1563/// leading `name@` prefix — both use the same parens-based suffix
1564/// shape, so the algorithm is identical.
1565fn apply_dedupe_peers_to_tail(tail: &str) -> String {
1566    apply_dedupe_peers_to_key(tail)
1567}
1568
1569#[allow(clippy::too_many_arguments)]
1570fn visit_peer_context<'g>(
1571    input_dep_path: &str,
1572    graph: &'g LockfileGraph,
1573    name_index: &FxHashMap<&'g str, Vec<&'g LockedPackage>>,
1574    ancestor_scope: &FxHashMap<String, PeerProvider>,
1575    root_scope: &FxHashMap<String, PeerProvider>,
1576    out_packages: &mut BTreeMap<String, LockedPackage>,
1577    visiting: &mut FxHashSet<String>,
1578    options: &PeerContextOptions,
1579) -> Option<String> {
1580    let pkg = graph.packages.get(input_dep_path)?;
1581
1582    // The input key may already carry a peer suffix (fixed-point loop
1583    // Pass 2+). Drop it before we build a new one — otherwise we'd
1584    // append the new suffix on top of the old and grow unboundedly
1585    // across iterations (classic mutual-peer-cycle blow-up).
1586    //
1587    // Both suffix forms are parenthesized — the normal nested
1588    // `(name@version)(…)` and the capped `(<short-hash>)` that
1589    // `effective_peer_suffix` emits past `peersSuffixMaxLength` — so
1590    // splitting on the first `(` strips either one. Otherwise each
1591    // pass would re-hash the already-hashed key and grow it (covered
1592    // by the `peer_suffix_is_hashed_when_exceeding_cap` unit test).
1593    let canonical_base = canonical_tail(input_dep_path).to_string();
1594
1595    // Compute peer context: walk declared peers, resolve from ancestors
1596    // (nearest wins — the scope is rebuilt as we recurse) or from the
1597    // package's own dependency map as the auto-install fallback. Both
1598    // sides may produce nested tails on the second and later iterations
1599    // of the fixed-point loop.
1600    // Resolution source priority for each declared peer:
1601    //   1. Ancestor scope — if the ancestor's version actually
1602    //      satisfies the declared peer range. Different subtrees
1603    //      naturally see different ancestors (lib-a in subtree-A
1604    //      and lib-b in subtree-B keep their own peer pins), so
1605    //      preferring the closest ancestor here doesn't conflate
1606    //      cross-subtree variants.
1607    //   2. The current package's own `pkg.dependencies` entry — the
1608    //      BFS peer-walk enqueued this peer with the declared range,
1609    //      so whatever got picked there is guaranteed to satisfy.
1610    //      Captures the case where a single subtree holds two
1611    //      consumers with conflicting peer ranges (lib-a@^17 next to
1612    //      a parent that pins react@18): the BFS auto-installs the
1613    //      satisfying version into lib-a's own deps, which beats the
1614    //      ancestor's incompatible version.
1615    //   3. Ancestor scope — even when the version doesn't satisfy
1616    //      the declared range. This mirrors what Node's module
1617    //      resolution would surface (`require('peer')` from the
1618    //      package would walk up node_modules and find the parent's
1619    //      version). pnpm and bun do the same and emit an unmet-peer
1620    //      warning rather than picking a more-distant matching
1621    //      version. `detect_unmet_peers` flags the mismatch after
1622    //      the pass.
1623    //   4. The current package's own `pkg.dependencies` entry,
1624    //      ignoring range satisfaction — symmetric to (3) for the
1625    //      BFS-installed case.
1626    //   5. Workspace root scope (compatible) — `resolve-peers-from-
1627    //      workspace-root` fallback for monorepos that pin shared
1628    //      peers at the root.
1629    //   6. A graph-wide scan: any package whose name matches and
1630    //      whose version satisfies the declared range. Last resort
1631    //      for nested-context callers when nothing closer has it.
1632    //   7. Workspace root scope, ignoring range satisfaction.
1633    //
1634    // If nothing in the graph holds a version of this peer at all,
1635    // it's left out of the context entirely — `detect_unmet_peers`
1636    // will surface it as a warning after the pass.
1637    //
1638    // Only peers the package actually *declares* in `peerDependencies`
1639    // build a dep_path suffix here. A name present solely in
1640    // `peerDependenciesMeta` (a meta-only optional peer — the way
1641    // `follow-redirects` declares `debug`, for instance) is deliberately
1642    // NOT folded in: pnpm treats such a peer as resolvable but then
1643    // collapses the binding back out via `dedupe-peer-dependents`
1644    // whenever a peer-free path exists, so the realistic lockfile leaves
1645    // the whole chain bare even when a distant ancestor carries that peer
1646    // as a plain dependency. Eagerly binding the meta-only peer from that
1647    // ancestor scope produced `(peer@ver)`-suffixed variants that aube's
1648    // dedupe pass (which only collapses *declared*-peer variants) never
1649    // merged, so the same subtree hashed differently per install scope
1650    // (whole-workspace vs single-member), splitting a shared
1651    // global-virtual-store singleton in two and surfacing at runtime as a
1652    // duplicate-instance "Cannot find module". Matching pnpm's *deduped*
1653    // output — bare — keeps the singleton intact.
1654    let mut peer_context: Vec<(String, PeerProvider)> = Vec::new();
1655    for (peer_name, declared_range) in &pkg.peer_dependencies {
1656        let satisfies_declared = |provider: &PeerProvider| -> bool {
1657            // The tail may carry a nested peer suffix on fixed-point
1658            // iterations 2+; strip it before checking the semver.
1659            let canonical = canonical_tail(&provider.context_tail);
1660            version_satisfies(canonical, declared_range)
1661        };
1662
1663        let from_ancestor = ancestor_scope
1664            .get(peer_name)
1665            .filter(|provider| satisfies_declared(provider))
1666            .cloned();
1667        let from_ancestor_incompatible = ancestor_scope.get(peer_name).cloned();
1668
1669        let from_pkg_deps = pkg
1670            .dependencies
1671            .get(peer_name)
1672            .map(|tail| peer_provider(graph, peer_name, tail))
1673            .filter(|provider| satisfies_declared(provider));
1674        let from_pkg_deps_incompatible = pkg
1675            .dependencies
1676            .get(peer_name)
1677            .map(|tail| peer_provider(graph, peer_name, tail));
1678
1679        // `resolve-peers-from-workspace-root`: fall back to the root
1680        // importer's direct deps before the graph-wide scan. Common in
1681        // monorepos where the workspace root pins shared peers (e.g.
1682        // `react`) that leaf packages peer on without declaring them
1683        // in their own subtree. Skipped when the setting is off —
1684        // matches pnpm's `resolve-peers-from-workspace-root=false`.
1685        let from_root = if options.resolve_from_workspace_root {
1686            root_scope
1687                .get(peer_name)
1688                .filter(|provider| satisfies_declared(provider))
1689                .cloned()
1690        } else {
1691            None
1692        };
1693        let from_root_incompatible = if options.resolve_from_workspace_root {
1694            root_scope.get(peer_name).cloned()
1695        } else {
1696            None
1697        };
1698
1699        // Return the full dep_path TAIL (the part after `name@`), not
1700        // just `p.version`. On fixed-point iteration 2+, the input
1701        // graph's keys are contextualized — e.g. `react-dom` lives at
1702        // `react-dom@18.2.0(react@18.2.0)`. Downstream code
1703        // reconstructs the child lookup key with
1704        // `format!("{child_name}@{tail}")` and needs the tail to
1705        // match whatever the graph has keyed it under, otherwise the
1706        // lookup returns None and the peer gets silently dropped
1707        // from `new_dependencies`. The semver check is against the
1708        // package's canonical `version` field, not the tail, because
1709        // the tail may carry a peer suffix that isn't valid semver.
1710        let from_graph_scan = || {
1711            name_index
1712                .get(peer_name.as_str())
1713                .into_iter()
1714                .flat_map(|bucket| bucket.iter().copied())
1715                .filter(|p| version_satisfies(&p.version, declared_range))
1716                .filter_map(|p| {
1717                    let tail = p
1718                        .dep_path
1719                        .strip_prefix(&format!("{}@", p.name))
1720                        .map(|s| s.to_string())
1721                        .unwrap_or_else(|| p.version.clone());
1722                    node_semver::Version::parse(&p.version).ok().map(|ver| {
1723                        let provider = peer_provider(graph, peer_name, &tail);
1724                        (ver, provider)
1725                    })
1726                })
1727                .max_by(|a, b| a.0.cmp(&b.0))
1728                .map(|(_, provider)| provider)
1729        };
1730
1731        // pnpm resolves an *optional* peer (one flagged
1732        // `peerDependenciesMeta.optional`) only from the resolution path it
1733        // is actually on — the nearest ancestor, the package's own
1734        // auto-installed deps, or the workspace root — and otherwise leaves
1735        // it unresolved so it surfaces under `transitivePeerDependencies`.
1736        // It never reaches for a range-incompatible version or scans the
1737        // whole graph for an unrelated copy. Mirroring that is what lets
1738        // `typescript` (an optional peer the root provides) take a dep-path
1739        // suffix while debug's optional `supports-color` (which nothing on
1740        // the path provides) bubbles up instead of binding to a cousin.
1741        let is_optional = pkg
1742            .peer_dependencies_meta
1743            .get(peer_name)
1744            .is_some_and(|m| m.optional);
1745        let resolved = if is_optional {
1746            from_ancestor.or(from_pkg_deps).or(from_root)
1747        } else {
1748            from_ancestor
1749                .or(from_pkg_deps)
1750                .or(from_ancestor_incompatible)
1751                .or(from_pkg_deps_incompatible)
1752                .or(from_root)
1753                .or_else(from_graph_scan)
1754                .or(from_root_incompatible)
1755        };
1756        if let Some(provider) = resolved {
1757            peer_context.push((peer_name.clone(), provider));
1758        }
1759    }
1760    peer_context.sort_by(|a, b| a.0.cmp(&b.0));
1761
1762    // For the SUFFIX we build a cycle-broken copy: any peer value that
1763    // nests a reference back to the current package's canonical base
1764    // gets stripped to its plain version. Without this, mutual peer
1765    // cycles (a peers on b, b peers on a) grow the suffix one level
1766    // per iteration of the fixed-point loop and never converge.
1767    //
1768    // The non-cycle paths are untouched, so a regular nested chain
1769    // like `(react-dom@18.2.0(react@18.2.0))` still serializes fully.
1770    // We deliberately keep the full nested tails in `peer_context` for
1771    // downstream scope propagation and child lookups — suffix cycle-
1772    // breaking is cosmetic and should not change what packages exist
1773    // or which snapshot entries reference each other.
1774    //
1775    // Cycle detection is always done against the full `name@version`
1776    // canonical base — even when `dedupe-peers=true` is on, because
1777    // the version-only form is ambiguous (two unrelated packages at
1778    // the same version would false-positive). `dedupe-peers` is
1779    // applied as a post-pass over the final graph in
1780    // `dedupe_peer_suffixes` after cycle detection is done.
1781    let suffix: String = peer_context
1782        .iter()
1783        .map(|(n, provider)| {
1784            let cycles_back = contains_canonical_back_ref(&provider.context_tail, &canonical_base);
1785            let display_v = if cycles_back {
1786                canonical_tail(&provider.context_tail).to_string()
1787            } else {
1788                provider.context_tail.clone()
1789            };
1790            format!("({n}@{display_v})")
1791        })
1792        .collect();
1793    // pnpm's `peersSuffixMaxLength`: when the suffix body exceeds the
1794    // cap, `effective_peer_suffix` replaces the whole suffix with a
1795    // parenthesized short hash `(<hash>)` so the lockfile key stays
1796    // bounded and byte-compatible with pnpm's `createPeerDepGraphHash`.
1797    let effective_suffix = effective_peer_suffix(&suffix, options.peers_suffix_max_length);
1798    let contextualized = format!("{canonical_base}{effective_suffix}");
1799
1800    if out_packages.contains_key(&contextualized) || visiting.contains(&contextualized) {
1801        return Some(contextualized);
1802    }
1803    visiting.insert(contextualized.clone());
1804
1805    // Build the scope for P's children. This is ancestor_scope, overlaid
1806    // with P's own dependencies and its resolved peer map. Children see
1807    // their grandparents too — this mirrors pnpm's all-the-way-up peer
1808    // walk.
1809    //
1810    // We deliberately do NOT strip any existing peer-context suffix
1811    // off the tails we put into the scope. On the first pass the
1812    // values are plain (BFS output has no suffixes), so preserving
1813    // them is a no-op; on subsequent passes (see the fixed-point loop
1814    // in `apply_peer_contexts`) the input graph already carries
1815    // contextualized tails, and keeping them in scope is exactly how
1816    // nested peer suffixes propagate down to consumers — a package
1817    // that peers on `react-dom` and reaches it through a parent whose
1818    // `react-dom` entry is already `18.2.0(react@18.2.0)` will see
1819    // that nested tail in its own scope, and its own suffix will
1820    // serialize as `(react-dom@18.2.0(react@18.2.0))`. That's the
1821    // nested form pnpm writes.
1822    let mut child_scope = ancestor_scope.clone();
1823    for (name, tail) in &pkg.dependencies {
1824        child_scope.insert(name.clone(), peer_provider(graph, name, tail));
1825    }
1826    for (name, provider) in &peer_context {
1827        child_scope.insert(name.clone(), provider.clone());
1828    }
1829
1830    // Recurse into each child, rewriting its dependency map entry to
1831    // point at the contextualized dep_path's tail. A child whose visit
1832    // fails (orphaned / missing) keeps its own tail.
1833    //
1834    // For declared peer names, the peer context (filled from the
1835    // ancestor scope) is authoritative — we override whatever the BFS
1836    // peer walk auto-installed. Otherwise the snapshot suffix and the
1837    // actual wired `dependencies[peer]` could disagree, which made the
1838    // sibling symlink target inconsistent with the peer-context claim.
1839    // When the ancestor's version doesn't satisfy the declared range,
1840    // `detect_unmet_peers` will flag it as a warning after the pass.
1841    let peer_context_versions: FxHashMap<String, PeerProvider> =
1842        peer_context.iter().cloned().collect();
1843
1844    let mut new_dependencies: BTreeMap<String, String> = BTreeMap::new();
1845    let mut visited_dep_names: FxHashSet<String> = FxHashSet::default();
1846
1847    for (child_name, child_version_tail) in &pkg.dependencies {
1848        // If this child is a declared peer, its tail comes from the
1849        // peer context (which may be nested). Otherwise we use the
1850        // tail we already have — also possibly nested on a 2nd pass.
1851        let lookup_tail = match peer_context_versions.get(child_name) {
1852            Some(provider) => provider.target_tail.clone(),
1853            None => child_version_tail.clone(),
1854        };
1855        let child_canonical_dep_path = format!("{child_name}@{lookup_tail}");
1856        let child_new = visit_peer_context(
1857            &child_canonical_dep_path,
1858            graph,
1859            name_index,
1860            &child_scope,
1861            root_scope,
1862            out_packages,
1863            visiting,
1864            options,
1865        );
1866        let new_tail = match child_new {
1867            Some(new_dep_path) => new_dep_path
1868                .strip_prefix(&format!("{child_name}@"))
1869                .map(|s| s.to_string())
1870                .unwrap_or_else(|| lookup_tail.clone()),
1871            None => lookup_tail.clone(),
1872        };
1873        new_dependencies.insert(child_name.clone(), new_tail);
1874        visited_dep_names.insert(child_name.clone());
1875    }
1876
1877    // Peers that were satisfied purely from the ancestor scope may not
1878    // have been in `pkg.dependencies` at all (no auto-install needed).
1879    // Wire them as deps now so the linker creates the sibling symlink
1880    // and the lockfile snapshot records them.
1881    for (peer_name, provider) in &peer_context {
1882        if visited_dep_names.contains(peer_name) {
1883            continue;
1884        }
1885        let child_canonical_dep_path = format!("{peer_name}@{}", provider.target_tail);
1886        let child_new = visit_peer_context(
1887            &child_canonical_dep_path,
1888            graph,
1889            name_index,
1890            &child_scope,
1891            root_scope,
1892            out_packages,
1893            visiting,
1894            options,
1895        );
1896        if let Some(new_dep_path) = child_new {
1897            let new_tail = new_dep_path
1898                .strip_prefix(&format!("{peer_name}@"))
1899                .map(|s| s.to_string())
1900                .unwrap_or_else(|| provider.target_tail.clone());
1901            new_dependencies.insert(peer_name.clone(), new_tail);
1902        }
1903    }
1904
1905    visiting.remove(&contextualized);
1906    let new_optional_dependencies: BTreeMap<String, String> = pkg
1907        .optional_dependencies
1908        .keys()
1909        .filter_map(|name| {
1910            new_dependencies
1911                .get(name)
1912                .map(|tail| (name.clone(), tail.clone()))
1913        })
1914        .collect();
1915
1916    out_packages.insert(
1917        contextualized.clone(),
1918        LockedPackage {
1919            name: pkg.name.clone(),
1920            version: pkg.version.clone(),
1921            integrity: pkg.integrity.clone(),
1922            dependencies: new_dependencies,
1923            optional_dependencies: new_optional_dependencies,
1924            peer_dependencies: pkg.peer_dependencies.clone(),
1925            peer_dependencies_meta: pkg.peer_dependencies_meta.clone(),
1926            dep_path: contextualized.clone(),
1927            local_source: pkg.local_source.clone(),
1928            os: pkg.os.clone(),
1929            cpu: pkg.cpu.clone(),
1930            libc: pkg.libc.clone(),
1931            bundled_dependencies: pkg.bundled_dependencies.clone(),
1932            optional: pkg.optional,
1933            transitive_peer_dependencies: pkg.transitive_peer_dependencies.clone(),
1934            tarball_url: pkg.tarball_url.clone(),
1935            registry_git_hosted: pkg.registry_git_hosted,
1936            alias_of: pkg.alias_of.clone(),
1937            yarn_checksum: pkg.yarn_checksum.clone(),
1938            engines: pkg.engines.clone(),
1939            bin: pkg.bin.clone(),
1940            declared_dependencies: pkg.declared_dependencies.clone(),
1941            license: pkg.license.clone(),
1942            funding_url: pkg.funding_url.clone(),
1943            extra_meta: pkg.extra_meta.clone(),
1944        },
1945    );
1946    Some(contextualized)
1947}
1948
1949#[cfg(test)]
1950mod tests {
1951    use super::*;
1952    use aube_lockfile::{DepType, DirectDep, PeerDepMeta};
1953
1954    fn locked(name: &str, deps: &[(&str, &str)]) -> LockedPackage {
1955        LockedPackage {
1956            name: name.to_string(),
1957            version: "1.0.0".to_string(),
1958            dep_path: format!("{name}@1.0.0"),
1959            dependencies: deps
1960                .iter()
1961                .map(|(n, v)| ((*n).to_string(), (*v).to_string()))
1962                .collect(),
1963            ..Default::default()
1964        }
1965    }
1966
1967    /// `root -> app -> {plugin, sibling}` and `sibling -> theme`. `theme`
1968    /// is only ever a *cousin* of `plugin` (never an ancestor, the root,
1969    /// or one of plugin's own deps), so the single way to reach it from
1970    /// plugin's peer is the graph-wide scan.
1971    fn graph_with_cousin_peer() -> LockfileGraph {
1972        let mut g = LockfileGraph::default();
1973        g.importers.insert(
1974            ".".to_string(),
1975            vec![DirectDep {
1976                name: "app".to_string(),
1977                dep_path: "app@1.0.0".to_string(),
1978                dep_type: DepType::Production,
1979                specifier: Some("1.0.0".to_string()),
1980            }],
1981        );
1982        for p in [
1983            locked("app", &[("plugin", "1.0.0"), ("sibling", "1.0.0")]),
1984            locked("plugin", &[]),
1985            locked("sibling", &[("theme", "1.0.0")]),
1986            locked("theme", &[]),
1987        ] {
1988            g.packages.insert(p.dep_path.clone(), p);
1989        }
1990        g
1991    }
1992
1993    #[test]
1994    fn optional_peer_is_not_bound_via_graph_scan() {
1995        let mut g = graph_with_cousin_peer();
1996        let plugin = g.packages.get_mut("plugin@1.0.0").expect("plugin present");
1997        plugin
1998            .peer_dependencies
1999            .insert("theme".to_string(), "*".to_string());
2000        plugin
2001            .peer_dependencies_meta
2002            .insert("theme".to_string(), PeerDepMeta { optional: true });
2003
2004        let out = apply_peer_contexts(g, &PeerContextOptions::default()).expect("peer pass");
2005
2006        assert!(
2007            out.packages.contains_key("plugin@1.0.0"),
2008            "plugin keeps bare key"
2009        );
2010        assert!(
2011            !out.packages.contains_key("plugin@1.0.0(theme@1.0.0)"),
2012            "an optional peer reachable only via the graph scan must stay \
2013             unresolved so it surfaces under transitivePeerDependencies"
2014        );
2015    }
2016
2017    #[test]
2018    fn required_peer_still_binds_via_graph_scan() {
2019        // Same shape, but `theme` is a *required* peer (no meta entry):
2020        // the graph-wide scan still binds it, proving the narrowing above
2021        // is specific to optional peers and not a regression.
2022        let mut g = graph_with_cousin_peer();
2023        let plugin = g.packages.get_mut("plugin@1.0.0").expect("plugin present");
2024        plugin
2025            .peer_dependencies
2026            .insert("theme".to_string(), "*".to_string());
2027
2028        let out = apply_peer_contexts(g, &PeerContextOptions::default()).expect("peer pass");
2029
2030        assert!(
2031            out.packages.contains_key("plugin@1.0.0(theme@1.0.0)"),
2032            "a required peer should still resolve through the graph-wide scan"
2033        );
2034    }
2035
2036    #[test]
2037    fn linked_workspace_root_peer_uses_manifest_version_and_local_target() {
2038        let mut g = LockfileGraph::default();
2039        g.importers.insert(
2040            ".".to_string(),
2041            vec![DirectDep {
2042                name: "theme".to_string(),
2043                dep_path: "theme@link+0123456789abcdef".to_string(),
2044                dep_type: DepType::Production,
2045                specifier: Some("link:theme".to_string()),
2046            }],
2047        );
2048        g.importers.insert(
2049            "packages/app".to_string(),
2050            vec![DirectDep {
2051                name: "plugin".to_string(),
2052                dep_path: "plugin@1.0.0".to_string(),
2053                dep_type: DepType::Production,
2054                specifier: Some("1.0.0".to_string()),
2055            }],
2056        );
2057        g.packages.insert(
2058            "theme@link+0123456789abcdef".to_string(),
2059            LockedPackage {
2060                name: "theme".to_string(),
2061                version: "4.10.0".to_string(),
2062                dep_path: "theme@link+0123456789abcdef".to_string(),
2063                local_source: Some(LocalSource::Link("theme".into())),
2064                ..Default::default()
2065            },
2066        );
2067        let mut plugin = locked("plugin", &[]);
2068        plugin
2069            .peer_dependencies
2070            .insert("theme".to_string(), "^4.0.0".to_string());
2071        plugin
2072            .peer_dependencies_meta
2073            .insert("theme".to_string(), PeerDepMeta { optional: true });
2074        g.packages.insert(plugin.dep_path.clone(), plugin);
2075
2076        let out = apply_peer_contexts(g, &PeerContextOptions::default()).expect("peer pass");
2077
2078        let plugin = out
2079            .packages
2080            .get("plugin@1.0.0(theme@4.10.0)")
2081            .expect("linked root dependency should satisfy the peer at its manifest version");
2082        assert_eq!(
2083            plugin.dependencies.get("theme").map(String::as_str),
2084            Some("link+0123456789abcdef"),
2085            "the peer suffix uses the manifest version while the linker keeps the local target"
2086        );
2087    }
2088}