Skip to main content

aube_resolver/
resolve.rs

1use crate::local_source::{
2    dep_path_for, is_non_registry_specifier, read_local_manifest, rebase_local, resolve_git_source,
3    resolve_remote_tarball, should_block_exotic_subdep,
4};
5use crate::package_ext::{apply_package_extensions, pick_override_spec};
6use crate::semver_util::{PickResult, pick_version, version_satisfies};
7use crate::{
8    Error, ExoticSubdepDetails, PeerContextOptions, ResolutionMode, ResolveTask, ResolvedPackage,
9    Resolver, apply_peer_contexts, catalog, error, hoist_auto_installed_peers,
10    is_deprecation_allowed, is_supported,
11};
12use aube_lockfile::{DepType, DirectDep, LocalSource, LockedPackage, LockfileGraph};
13use aube_manifest::PackageJson;
14use aube_registry::Packument;
15use rustc_hash::{FxHashMap, FxHashSet};
16use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
17use std::sync::Arc;
18
19impl Resolver {
20    /// Resolve all dependencies from a package.json.
21    ///
22    /// Uses batch-parallel BFS: each "wave" drains the queue, identifies
23    /// uncached package names, fetches their packuments concurrently, then
24    /// processes the entire batch before starting the next wave.
25    pub async fn resolve(
26        &mut self,
27        manifest: &PackageJson,
28        existing: Option<&LockfileGraph>,
29    ) -> Result<LockfileGraph, Error> {
30        self.resolve_workspace(
31            &[(".".to_string(), manifest.clone())],
32            existing,
33            &HashMap::new(),
34        )
35        .await
36    }
37
38    /// Resolve all dependencies for a workspace (multiple importers).
39    ///
40    /// `manifests` is a list of (importer_path, PackageJson) — e.g. (".", root), ("packages/app", app).
41    /// `workspace_packages` maps package name → version. Used both for
42    /// explicit `workspace:` protocol resolution and for yarn/npm/bun
43    /// style linkage where a bare semver range on a workspace-package
44    /// name resolves to the local copy when its version satisfies the
45    /// range.
46    pub async fn resolve_workspace(
47        &mut self,
48        manifests: &[(String, PackageJson)],
49        existing: Option<&LockfileGraph>,
50        workspace_packages: &HashMap<String, String>,
51    ) -> Result<LockfileGraph, Error> {
52        let resolve_start = std::time::Instant::now();
53        let mut packument_fetch_count = 0u32;
54        let mut packument_fetch_time = std::time::Duration::ZERO;
55        let mut lockfile_reuse_count = 0u32;
56        let mut resolved: BTreeMap<String, LockedPackage> = BTreeMap::new();
57        let mut resolved_versions: FxHashMap<String, Vec<String>> = FxHashMap::default();
58        let mut importers: BTreeMap<String, Vec<DirectDep>> = BTreeMap::new();
59        let mut queue: VecDeque<ResolveTask> = VecDeque::new();
60        let mut visited: FxHashSet<std::sync::Arc<str>> = FxHashSet::default();
61        // Round-tripped to the lockfile's top-level `time:` block so
62        // subsequent installs can reuse them for the cutoff computation.
63        // Populated opportunistically from whatever packuments we fetch:
64        // empty when the metadata omits `time` (corgi from npmjs.org in
65        // default mode), filled when it doesn't (Verdaccio, or the
66        // full-packument path taken for time-based resolution and
67        // `minimumReleaseAge`). This matches pnpm's `publishedAt` wiring.
68        let mut resolved_times: BTreeMap<String, String> = BTreeMap::new();
69        // Per-importer record of optionals the resolver intentionally
70        // dropped on this run — either filtered by os/cpu/libc or
71        // named in `pnpm.ignoredOptionalDependencies`. Round-tripped
72        // through the lockfile so drift detection on subsequent
73        // installs can distinguish "previously skipped" from "newly
74        // added by the user".
75        let mut skipped_optional_dependencies: BTreeMap<String, BTreeMap<String, String>> =
76            BTreeMap::new();
77        // Catalog picks gathered as the BFS rewrites `catalog:` task
78        // ranges. Outer key: catalog name. Inner: package name → spec.
79        // Resolved versions are filled in post-resolution by walking
80        // `resolved_versions` for the spec, since the picked version is
81        // an output the BFS doesn't know until version_satisfies fires.
82        let mut catalog_picks: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
83        let importer_declared_dep_names: BTreeMap<String, BTreeSet<String>> = manifests
84            .iter()
85            .map(|(importer_path, manifest)| {
86                let names = manifest
87                    .dependencies
88                    .keys()
89                    .chain(manifest.dev_dependencies.keys())
90                    .chain(manifest.optional_dependencies.keys())
91                    .cloned()
92                    .collect();
93                (importer_path.clone(), names)
94            })
95            .collect();
96        // ISO-8601 UTC cutoff string. npm's registry `time` map uses
97        // `Z`-suffixed UTC timestamps throughout, which sort
98        // lexicographically — so a raw `String` doubles as a
99        // comparable instant without pulling in a date library.
100        //
101        // Two independent features feed this cutoff:
102        //   - `minimum_release_age` (pnpm v11 default, supply-chain
103        //     mitigation): seeded *before* wave 0 so even direct deps
104        //     are filtered. The exclude list and strict-mode behavior
105        //     are scoped per-package by `pick_version` below.
106        //   - `resolution-mode=time-based`: derived from the max
107        //     publish time across direct deps once wave 0 finishes,
108        //     then constrains transitives only.
109        // When both are configured, the resolver carries both cutoffs
110        // and the picker takes the more restrictive (earlier) one.
111        let mut published_by: Option<String> =
112            self.minimum_release_age.as_ref().and_then(|m| m.cutoff());
113        if let Some(c) = published_by.as_deref() {
114            tracing::debug!("minimumReleaseAge cutoff: {}", c);
115        }
116
117        seed_direct_deps(
118            manifests,
119            &self.ignored_optional_dependencies,
120            &mut queue,
121            &mut importers,
122        );
123
124        // Pipelined resolver state. The resolver is strictly serial in
125        // its *processing* order (tasks are popped and version-picked
126        // in seed/BFS order, which is what keeps the output lockfile
127        // byte-deterministic across runs) but fetches run freely in
128        // the background via `in_flight`. When a popped task's
129        // packument isn't in the cache, the main loop waits inline on
130        // `in_flight.join_next()` — harvesting whatever other fetches
131        // happen to land in the meantime — until this task's
132        // packument is available. Because `ensure_fetch!` is called
133        // speculatively at every enqueue site, by the time a task is
134        // popped its packument is usually already cached, so the
135        // wait is short.
136        let shared_semaphore = Arc::new(tokio::sync::Semaphore::new(
137            self.packument_network_concurrency.unwrap_or(64),
138        ));
139        // Time-based mode and `minimumReleaseAge` both need the
140        // packument's `time:` map. The abbreviated (corgi) response
141        // omits `time` by default, so we normally fall back to the
142        // full packument. `registry-supports-time-field=true` flips
143        // that: the user is asserting the configured registry ships
144        // `time` in corgi too (Verdaccio 5.15.1+, JSR, etc.), so the
145        // cheaper abbreviated path stays on the hot path and we save
146        // one full-packument fetch per distinct package.
147        let needs_time = (self.resolution_mode == ResolutionMode::TimeBased
148            || self.minimum_release_age.is_some()
149            || self.dependency_policy.trust_policy == crate::TrustPolicy::NoDowngrade)
150            && !self.registry_supports_time_field;
151        // Gate for the corgi-shortcircuit at L219-235: when the only
152        // reason we need `time` is `minimumReleaseAge` AND the
153        // packument's top-level `modified` predates the cutoff, every
154        // version is old enough so we can skip the full-packument
155        // fetch. trustPolicy=NoDowngrade adds a second time requirement
156        // (per-version compare), so the shortcircuit must NOT fire when
157        // it's on — otherwise the trust check falls through to a
158        // spurious TrustCheckMissingTime on every version.
159        let minimum_release_age_only = self.resolution_mode != ResolutionMode::TimeBased
160            && self.minimum_release_age.is_some()
161            && self.dependency_policy.trust_policy != crate::TrustPolicy::NoDowngrade;
162        // In-flight packument fetches. The spawned task returns the
163        // `(name, packument)` tuple so `join_next` gives us back the
164        // identity of whichever fetch landed next without a side
165        // table lookup.
166        #[allow(clippy::type_complexity)]
167        let mut in_flight: tokio::task::JoinSet<Result<(String, Packument), Error>> =
168            tokio::task::JoinSet::new();
169        // Names whose fetch has been spawned but not yet harvested.
170        // Dedupes spawn calls when multiple tasks discover the same
171        // transitive before any of them has been processed.
172        let mut in_flight_names: FxHashSet<String> = FxHashSet::default();
173        // TimeBased wave-0 gate: the publish-time cutoff is derived
174        // from the direct deps' resolved versions, so transitives
175        // that reach the version-pick step before all directs have
176        // completed must wait. Populated only when
177        // `cutoff_pending == true` (TimeBased mode); `Highest` mode
178        // leaves these at their defaults and the gate is a no-op.
179        let mut direct_deps_pending: usize = queue.len();
180        let mut cutoff_pending = self.resolution_mode == ResolutionMode::TimeBased;
181        let mut deferred_transitives: Vec<ResolveTask> = Vec::new();
182
183        // Set of names present in the existing lockfile. Used as a
184        // prefetch gate: names the lockfile already covers will hit
185        // the lockfile-reuse path and don't need their packuments
186        // fetched, so prefetching them is wasted tokio-spawn
187        // overhead. Load-bearing for `aube add` and
188        // frozen-lockfile-install scenarios where most tasks go
189        // through lockfile-reuse.
190        //
191        // This is strictly a *prefetch* gate, not a correctness
192        // gate: a task that fails sibling dedupe AND lockfile reuse
193        // (because its range doesn't match any of the lockfile's
194        // versions for that name) still needs a fresh fetch, and
195        // the wait-for-fetch loop below calls `ensure_fetch!`
196        // without consulting `existing_names`.
197        // Borrow names from `existing` instead of cloning. The set
198        // lives only inside `Resolver::resolve` and the prior
199        // lockfile graph outlives it. Skips 5000 String allocations
200        // on a 5000-pkg lockfile at resolve-entry.
201        let existing_names: FxHashSet<&str> = existing
202            .map(|g| g.packages.values().map(|p| p.name.as_str()).collect())
203            .unwrap_or_default();
204
205        // Spawn a packument fetch into `in_flight` if one isn't
206        // already running for `name` and the packument isn't
207        // already cached. Gated *only* on in-flight + cache —
208        // callers that want to skip prefetching names already
209        // covered by the lockfile check `existing_names` explicitly
210        // before invoking the macro.
211        macro_rules! ensure_fetch {
212            ($name:expr) => {{
213                let name: &str = $name;
214                if !in_flight_names.contains(name) && !self.cache.contains_key(name) {
215                    let name_owned = name.to_string();
216                    in_flight_names.insert(name_owned.clone());
217                    let client = self.client.clone();
218                    let cache_dir = self.packument_cache_dir.clone();
219                    let full_cache_dir = self.packument_full_cache_dir.clone();
220                    let cutoff = published_by.clone();
221                    let sem = shared_semaphore.clone();
222                    in_flight.spawn(async move {
223                        let _permit = sem
224                            .acquire_owned()
225                            .await
226                            .map_err(|e| Error::Registry(name_owned.clone(), e.to_string()))?;
227                        let packument = if needs_time {
228                            if minimum_release_age_only
229                                && let (Some(dir), Some(cutoff)) =
230                                    (cache_dir.as_ref(), cutoff.as_deref())
231                                && full_cache_dir.is_some()
232                            {
233                                let packument = client
234                                    .fetch_packument_cached(&name_owned, dir)
235                                    .await
236                                    .map_err(|e| {
237                                        Error::Registry(name_owned.clone(), e.to_string())
238                                    })?;
239                                if packument.modified.as_deref().is_some_and(|modified| {
240                                    modified_allows_short_circuit(modified, cutoff)
241                                }) {
242                                    return Ok::<_, Error>((name_owned, packument));
243                                }
244                            }
245                            match full_cache_dir.as_ref() {
246                                Some(dir) => {
247                                    client
248                                        .fetch_packument_with_time_cached(&name_owned, dir)
249                                        .await
250                                }
251                                None => client.fetch_packument(&name_owned).await,
252                            }
253                        } else if let Some(ref dir) = cache_dir {
254                            client.fetch_packument_cached(&name_owned, dir).await
255                        } else {
256                            client.fetch_packument(&name_owned).await
257                        }
258                        .map_err(|e| Error::Registry(name_owned.clone(), e.to_string()))?;
259                        Ok::<_, Error>((name_owned, packument))
260                    });
261                }
262            }};
263        }
264
265        // Decrement the pending-directs counter when a root task
266        // reaches a terminal state. Used by the TimeBased cutoff
267        // trigger at the top of the outer loop.
268        macro_rules! note_root_done {
269            () => {
270                if direct_deps_pending > 0 {
271                    direct_deps_pending -= 1;
272                }
273            };
274        }
275
276        // `(name, range)` is safe to speculatively prefetch against
277        // the registry when:
278        //
279        //   - The range isn't a protocol we rewrite in preprocessing
280        //     (`workspace:` / `catalog:` / `npm:` alias) — for those
281        //     we don't know the real package name yet, so fetching
282        //     the raw task name is either useless (preprocessing
283        //     won't go through the registry at all) or wrong (we'd
284        //     fetch the alias key instead of the real package).
285        //   - The range isn't a `file:` / `link:` / `git:` /
286        //     remote-tarball spec (covered by
287        //     `is_non_registry_specifier`).
288        //   - The name isn't in the overrides map — an override can
289        //     rewrite the range into any of the above, and we can't
290        //     cheaply tell whether it will, so be conservative.
291        //
292        // Called both from the upfront prefetch loop over seeded
293        // root deps *and* from the three transitive-enqueue sites
294        // inside the version-pick body, where the same class of
295        // unsafe specs can arrive via a published package's
296        // `dependencies` / `optionalDependencies` / `peerDependencies`
297        // maps (real-world case: a package whose dependency entry
298        // is an npm alias).
299        macro_rules! prefetchable {
300            ($name:expr, $range:expr) => {{
301                let r: &str = $range;
302                let n: &str = $name;
303                // A bare semver range that matches a workspace package
304                // will resolve to the workspace without ever reading
305                // the packument, so prefetching would just be a
306                // speculative 404 on e.g. an unpublished monorepo
307                // package.
308                let workspace_hit = workspace_packages
309                    .get(n)
310                    .is_some_and(|ws_v| version_satisfies(ws_v, r));
311                !aube_util::pkg::is_workspace_spec(r)
312                    && !aube_util::pkg::is_catalog_spec(r)
313                    && !aube_util::pkg::is_npm_spec(r)
314                    && !aube_util::pkg::is_jsr_spec(r)
315                    && !is_non_registry_specifier(r)
316                    && !self.overrides.contains_key(n)
317                    && !workspace_hit
318            }};
319        }
320
321        // Fire prefetches for every seeded root dep up front, so
322        // their packuments are already in flight by the time the
323        // first task is popped. Skip lockfile-covered names —
324        // they'll hit the lockfile-reuse path and never need their
325        // packuments — and anything `prefetchable!` rejects.
326        for task in queue.iter() {
327            if !prefetchable!(task.name.as_str(), task.range.as_str()) {
328                continue;
329            }
330            if existing_names.contains(task.name.as_str()) {
331                continue;
332            }
333            ensure_fetch!(&task.name);
334        }
335
336        'outer: loop {
337            // TimeBased cutoff trigger. Fires the first time
338            // `direct_deps_pending` hits zero with the cutoff still
339            // pending — at which point every direct dep has been
340            // version-picked (or terminated in preprocessing),
341            // `resolved_times` holds their publish times, and we can
342            // derive the max to seed `published_by` for the
343            // transitives we deferred.
344            if cutoff_pending && direct_deps_pending == 0 {
345                let direct_dep_paths: FxHashSet<&String> = importers
346                    .values()
347                    .flat_map(|deps| deps.iter().map(|d| &d.dep_path))
348                    .collect();
349                let mut max_time: Option<&String> = None;
350                for (dep_path, t) in resolved_times.iter() {
351                    if !direct_dep_paths.contains(dep_path) {
352                        continue;
353                    }
354                    if max_time.map(|m| t > m).unwrap_or(true) {
355                        max_time = Some(t);
356                    }
357                }
358                if let Some(existing_graph) = existing {
359                    for (dep_path, t) in &existing_graph.times {
360                        if !direct_dep_paths.contains(dep_path) {
361                            continue;
362                        }
363                        if max_time.map(|m| t > m).unwrap_or(true) {
364                            max_time = Some(t);
365                        }
366                    }
367                }
368                if let Some(m) = max_time {
369                    tracing::debug!("time-based resolution cutoff: {}", m);
370                    published_by = Some(match published_by.take() {
371                        Some(existing) if existing.as_str() < m.as_str() => existing,
372                        _ => m.clone(),
373                    });
374                }
375                cutoff_pending = false;
376                queue.extend(deferred_transitives.drain(..));
377            }
378
379            let Some(mut task) = queue.pop_front() else {
380                if !deferred_transitives.is_empty() {
381                    return Err(Error::Registry(
382                        "(resolver)".to_string(),
383                        format!(
384                            "{} transitives still deferred when resolve completed",
385                            deferred_transitives.len()
386                        ),
387                    ));
388                }
389                break 'outer;
390            };
391
392            // Body of the former per-task preprocessing loop.
393            // The old wave-based code split this into a
394            // preprocessing pass and a post-fetch version-pick
395            // pass with a fetch barrier between them. Here both
396            // passes run inline for a single task: preprocess →
397            // sibling dedupe → lockfile reuse → wait on this
398            // task's packument → version-pick → enqueue
399            // transitives. The bare block keeps the original
400            // indentation so the diff stays readable against the
401            // prior shape; `continue` inside it still continues
402            // the 'outer loop because a bare block is not itself
403            // a loop.
404            {
405                // Apply bare-name overrides + npm-alias rewrites in a
406                // small fixed-point loop. Two interleavings need to
407                // work simultaneously:
408                //   1. The override *value* is itself a `npm:` alias
409                //      (e.g. `"foo": "npm:bar@^2"`). The first override
410                //      pass rewrites `task.range`; the alias pass then
411                //      rewrites `task.name` to `bar`.
412                //   2. The user's *declared dep* is an `npm:` alias
413                //      (e.g. `"foo": "npm:bar@^1"`) and the override
414                //      targets the real package (`"overrides":
415                //      {"bar": "2.0.0"}`). The first override pass
416                //      misses (`task.name` is still `foo`), the alias
417                //      pass rewrites `task.name = "bar"`, and the
418                //      second override pass catches it.
419                // A two-iteration cap is enough — after one alias
420                // rewrite the name is canonical, and an override that
421                // points at a third package is itself constrained by
422                // the same rule, so there's no infinite chain.
423                //
424                // We deliberately don't touch `original_specifier`,
425                // since the lockfile/importer record should still
426                // reflect what the user wrote in package.json —
427                // overrides are a graph-shaping rule, not a rewrite of
428                // the user's declared deps.
429                // Catalog protocol: rewrite `catalog:` and
430                // `catalog:<name>` to the workspace catalog's actual
431                // range *before* the override loop, so overrides can
432                // still target a catalog dep by bare name. The original
433                // `catalog:...` text stays in `original_specifier` so
434                // the lockfile importer keeps the catalog reference and
435                // drift detection works.
436                if let Some((catalog_name, real_range)) =
437                    self.resolve_catalog_spec(&task.name, &task.range)?
438                {
439                    tracing::trace!("catalog: {} {} -> {}", task.name, task.range, real_range);
440                    catalog_picks
441                        .entry(catalog_name)
442                        .or_default()
443                        .insert(task.name.clone(), real_range.clone());
444                    task.range = real_range;
445                }
446
447                for _ in 0..2 {
448                    let mut changed = false;
449                    if let Some(override_spec) = pick_override_spec(
450                        &self.override_rules,
451                        &task.name,
452                        &task.range,
453                        &task.ancestors,
454                    ) {
455                        // pnpm's removal marker: an override value of
456                        // `"-"` drops the dep edge entirely. Skip before
457                        // catalog/alias rewrites so `-` never reaches
458                        // the registry resolver. The dropped edge never
459                        // gets written to the parent's `.dependencies`
460                        // map (that write happens downstream) and, for
461                        // direct deps, never gets pushed into the
462                        // importer's direct-dep list.
463                        if override_spec == "-" {
464                            tracing::trace!("override: {}@{} -> dropped", task.name, task.range,);
465                            if task.is_root {
466                                note_root_done!();
467                            }
468                            continue 'outer;
469                        }
470                        // An override may itself point at a catalog
471                        // entry (e.g. `"overrides": {"foo": "catalog:"}`).
472                        // The catalog pre-pass above already ran against
473                        // the original range, so resolve the indirection
474                        // here before assigning — otherwise `catalog:`
475                        // leaks through to the registry resolver.
476                        // Stash the catalog pick in a local so we only
477                        // record it if the override actually moves
478                        // `task.range`.
479                        let (effective_spec, pending_pick) =
480                            match self.resolve_catalog_spec(&task.name, &override_spec)? {
481                                Some((catalog_name, real_range)) => {
482                                    (real_range.clone(), Some((catalog_name, real_range)))
483                                }
484                                None => (override_spec, None),
485                            };
486                        if task.range != effective_spec {
487                            if let Some((catalog_name, real_range)) = pending_pick {
488                                catalog_picks
489                                    .entry(catalog_name)
490                                    .or_default()
491                                    .insert(task.name.clone(), real_range);
492                            }
493                            tracing::trace!(
494                                "override: {}@{} -> {}",
495                                task.name,
496                                task.range,
497                                effective_spec
498                            );
499                            task.range = effective_spec;
500                            // If the override replaced the spec with a
501                            // bare range (not itself an `npm:` / `jsr:`
502                            // alias), it's targeting `task.name` —
503                            // implicitly undoing any prior alias
504                            // rewrite. Without this, an override that
505                            // fires after a catalog-aliased entry
506                            // (e.g. catalog `js-yaml:
507                            // npm:@zkochan/js-yaml@0.0.11`, override
508                            // `js-yaml@<3.14.2: ^3.14.2`) would keep
509                            // `task.real_name = @zkochan/js-yaml` and
510                            // try to fetch `^3.14.2` from a packument
511                            // that only carries `0.0.x`. If the
512                            // override's value is itself an alias, the
513                            // alias pass below picks up the new target
514                            // on the next loop iteration.
515                            if task.real_name.is_some()
516                                && !task.range.starts_with("npm:")
517                                && !task.range.starts_with("jsr:")
518                            {
519                                task.real_name = None;
520                            }
521                            changed = true;
522                        }
523                    }
524                    if let Some(rest) = task.range.strip_prefix("npm:")
525                        && let Some(at_idx) = rest.rfind('@')
526                    {
527                        let real_name = rest[..at_idx].to_string();
528                        let real_range = rest[at_idx + 1..].to_string();
529                        // Keep `task.name` as the user-facing alias
530                        // (the key the package.json used) and stash
531                        // the registry name on `real_name` so every
532                        // identity-facing site — dep_path formation,
533                        // direct-dep records, parent wiring — sees
534                        // the alias, while only packument/tarball
535                        // fetch sites (via `task.registry_name()`)
536                        // hit the real package. Overwriting
537                        // `task.name` here would collapse
538                        // `node_modules/h3-v2/` to `node_modules/h3/`
539                        // and any `require("h3-v2")` would break.
540                        if task.real_name.as_deref() != Some(real_name.as_str())
541                            || real_range != task.range
542                        {
543                            tracing::trace!(
544                                "npm alias: {} -> {}@{}",
545                                task.name,
546                                real_name,
547                                real_range
548                            );
549                            task.real_name = Some(real_name);
550                            task.range = real_range;
551                            changed = true;
552                        }
553                    }
554                    // `jsr:<range>` and `jsr:<@scope/name>[@<range>]` both
555                    // land here. JSR's npm-compat endpoint serves every
556                    // package under `@jsr/<scope>__<name>`, but the
557                    // user-facing dependency name stays the JSR name (or
558                    // explicit alias) from package.json. Keep `task.name`
559                    // unchanged for dep_path/importer/link identity and
560                    // stash the npm-compat name in `real_name`, matching
561                    // the npm-alias path above. Only registry IO should
562                    // see `@jsr/...`.
563                    if let Some(rest) = task.range.strip_prefix("jsr:") {
564                        let (jsr_name_raw, jsr_range) = if let Some(body) = rest.strip_prefix('@') {
565                            match body.rfind('@') {
566                                Some(rel_at) => {
567                                    // Indices are relative to `body`; add 1 for
568                                    // the `@` we just stripped so we can slice
569                                    // against the original `rest`.
570                                    let at_idx = rel_at + 1;
571                                    (rest[..at_idx].to_string(), rest[at_idx + 1..].to_string())
572                                }
573                                None => (rest.to_string(), "latest".to_string()),
574                            }
575                        } else {
576                            // Bare range form — the manifest key carries the
577                            // JSR name (e.g. `"@std/collections": "jsr:^1"`).
578                            (task.name.clone(), rest.to_string())
579                        };
580                        match aube_registry::jsr::jsr_to_npm_name(&jsr_name_raw) {
581                            Some(npm_name) => {
582                                if task.real_name.as_deref() != Some(npm_name.as_str())
583                                    || jsr_range != task.range
584                                {
585                                    tracing::trace!(
586                                        "jsr: {} -> {}@{}",
587                                        task.name,
588                                        npm_name,
589                                        jsr_range,
590                                    );
591                                    task.real_name = Some(npm_name);
592                                    task.range = jsr_range;
593                                    changed = true;
594                                }
595                            }
596                            None => {
597                                return Err(Error::Registry(
598                                    task.name.clone(),
599                                    format!(
600                                        "invalid jsr: spec `{}` — expected `jsr:@scope/name[@range]`",
601                                        task.range,
602                                    ),
603                                ));
604                            }
605                        }
606                    }
607                    if !changed {
608                        break;
609                    }
610                }
611
612                // Handle file: / link: / git: protocols — the dep points
613                // at a path on disk or a remote git repo rather than a
614                // registry package. Only valid on root deps; a nested
615                // package.json that declares its own `file:` dep silently
616                // falls through to the normal resolver path and fails
617                // loudly there.
618                if is_non_registry_specifier(&task.range) {
619                    if should_block_exotic_subdep(
620                        &task,
621                        &resolved,
622                        self.dependency_policy.block_exotic_subdeps,
623                    ) {
624                        return Err(Error::BlockedExoticSubdep(Box::new(ExoticSubdepDetails {
625                            name: task.name.clone(),
626                            spec: task.range.clone(),
627                            parent: task
628                                .parent
629                                .clone()
630                                .unwrap_or_else(|| "<unknown>".to_string()),
631                            ancestors: task.ancestors.clone(),
632                            importer: task.importer.clone(),
633                        })));
634                    }
635                    let importer_root = if task.importer == "." {
636                        self.project_root.clone()
637                    } else {
638                        self.project_root.join(&task.importer)
639                    };
640                    let Some(raw_local) = LocalSource::parse(&task.range, &importer_root) else {
641                        return Err(Error::Registry(
642                            task.name.clone(),
643                            format!("unparseable local specifier: {}", task.range),
644                        ));
645                    };
646                    // For git sources we have to talk to the remote
647                    // right now so the resolver can (a) pin the
648                    // committish to a full SHA for the lockfile and
649                    // (b) read the cloned repo's `package.json` for
650                    // transitive deps. `resolve_git_source` does the
651                    // `ls-remote` + shallow clone dance and returns a
652                    // `LocalSource::Git` with `resolved` populated,
653                    // plus the manifest tuple the rest of the branch
654                    // already expects.
655                    if !task.is_root
656                        && !matches!(
657                            raw_local,
658                            LocalSource::Git(_) | LocalSource::RemoteTarball(_)
659                        )
660                    {
661                        return Err(Error::Registry(
662                            task.name.clone(),
663                            format!(
664                                "transitive local specifier {} cannot be resolved without the parent package source root",
665                                task.range
666                            ),
667                        ));
668                    }
669                    let (local, real_version, target_deps) = if let LocalSource::Git(ref g) =
670                        raw_local
671                    {
672                        let shallow = aube_store::git_host_in_list(&g.url, &self.git_shallow_hosts);
673                        let (resolved_local, version, deps) =
674                            resolve_git_source(&task.name, g, shallow)
675                                .await
676                                .map_err(|e| {
677                                    Error::Registry(
678                                        task.name.clone(),
679                                        format!("git resolve {}: {e}", task.range),
680                                    )
681                                })?;
682                        (resolved_local, version, deps)
683                    } else if let LocalSource::RemoteTarball(ref t) = raw_local {
684                        let (resolved_local, version, deps) =
685                            resolve_remote_tarball(&task.name, t, self.client.as_ref())
686                                .await
687                                .map_err(|e| {
688                                    Error::Registry(
689                                        task.name.clone(),
690                                        format!("remote tarball {}: {e}", task.range),
691                                    )
692                                })?;
693                        (resolved_local, version, deps)
694                    } else {
695                        // Rewrite the path to be relative to the
696                        // project root so every downstream consumer
697                        // can resolve it with a single
698                        // `project_root.join(rel)`.
699                        let local = rebase_local(&raw_local, &importer_root, &self.project_root);
700                        let (_target_name, version, deps) =
701                            read_local_manifest(&raw_local, &importer_root).unwrap_or_else(|_| {
702                                (task.name.clone(), "0.0.0".to_string(), BTreeMap::new())
703                            });
704                        (local, version, deps)
705                    };
706                    let dep_path = local.dep_path(&task.name);
707                    let linked_name = task.name.clone();
708
709                    if task.is_root
710                        && let Some(deps) = importers.get_mut(&task.importer)
711                    {
712                        deps.push(DirectDep {
713                            name: task.name.clone(),
714                            dep_path: dep_path.clone(),
715                            dep_type: task.dep_type,
716                            specifier: task.original_specifier.clone(),
717                        });
718                    }
719
720                    // Wire parent -> this exotic transitive. Without
721                    // this, the parent snapshot's `dependencies` map
722                    // omits the git/url/file subdep entirely, so the
723                    // linker never creates the sibling symlink inside
724                    // the parent's node_modules and the package fails
725                    // to resolve at runtime. The value is the dep_path
726                    // tail (e.g. `git+<hash>`) so the linker can
727                    // reconstruct the full dep_path by concatenating
728                    // `{name}@{value}` — matching the key format used
729                    // when inserting the resolved package below.
730                    if let Some(ref parent_dp) = task.parent
731                        && let Some(parent_pkg) = resolved.get_mut(parent_dp)
732                    {
733                        // `local.dep_path(name)` always returns
734                        // `{name}@{tail}`; if that invariant ever
735                        // breaks we'd silently store a malformed dep
736                        // value that the pnpm writer would emit as-is.
737                        let name_prefix = format!("{}@", task.name);
738                        debug_assert!(
739                            dep_path.starts_with(&name_prefix),
740                            "local.dep_path returned {dep_path:?} without expected prefix {name_prefix:?}"
741                        );
742                        let dep_tail = dep_path
743                            .strip_prefix(&name_prefix)
744                            .unwrap_or(&dep_path)
745                            .to_string();
746                        parent_pkg
747                            .dependencies
748                            .insert(task.name.clone(), dep_tail.clone());
749                        if task.dep_type == DepType::Optional {
750                            parent_pkg
751                                .optional_dependencies
752                                .insert(task.name.clone(), dep_tail);
753                        }
754                    }
755
756                    if visited.insert(std::sync::Arc::from(dep_path.as_str())) {
757                        resolved.insert(
758                            dep_path.clone(),
759                            LockedPackage {
760                                name: linked_name.clone(),
761                                version: real_version.clone(),
762                                dep_path: dep_path.clone(),
763                                local_source: Some(local.clone()),
764                                ..Default::default()
765                            },
766                        );
767                        if let Some(ref tx) = self.resolved_tx {
768                            let _ = tx.send(ResolvedPackage {
769                                dep_path: dep_path.clone(),
770                                name: linked_name.clone(),
771                                version: real_version.clone(),
772                                integrity: None,
773                                tarball_url: None,
774                                // local_source deps aren't aliased —
775                                // `file:`/`link:` specifiers go
776                                // through the local-source branch,
777                                // not the `npm:` rewrite.
778                                alias_of: None,
779                                local_source: Some(local.clone()),
780                                // Local `file:`/`link:` packages never
781                                // carry npm-style platform constraints
782                                // — they're whatever the user points
783                                // at, so the fetch coordinator treats
784                                // them as unconstrained (always fetch).
785                                os: aube_lockfile::PlatformList::new(),
786                                cpu: aube_lockfile::PlatformList::new(),
787                                libc: aube_lockfile::PlatformList::new(),
788                                deprecated: None,
789                            });
790                        }
791                        // Enqueue transitive deps of the local package
792                        // (directories + tarballs only — `link:` deps
793                        // are fully the target's responsibility).
794                        if !matches!(local, LocalSource::Link(_)) {
795                            let mut child_ancestors = task.ancestors.clone();
796                            child_ancestors.push((linked_name.clone(), real_version.clone()));
797                            for (child_name, child_range) in target_deps {
798                                queue.push_back(ResolveTask::transitive(
799                                    child_name,
800                                    child_range,
801                                    DepType::Production,
802                                    dep_path.clone(),
803                                    task.importer.clone(),
804                                    child_ancestors.clone(),
805                                ));
806                            }
807                        }
808                    }
809                    if task.is_root {
810                        note_root_done!();
811                    }
812                    continue;
813                }
814
815                // Handle workspace linkage. Two cases resolve to the
816                // workspace package rather than the registry:
817                //   1. Explicit `workspace:` protocol (pnpm/yarn-berry
818                //      style). The range after the prefix is accepted
819                //      unconditionally — the user asserted this should
820                //      link.
821                //   2. Bare semver range whose name matches a workspace
822                //      package whose version satisfies the range. This
823                //      is the yarn-v1 / npm / bun default: siblings pin
824                //      each other with normal version strings and
825                //      expect the workspace to win over the registry.
826                //      A workspace is typically either unpublished or
827                //      is itself the source of truth for its name, so
828                //      preferring the local copy matches every other
829                //      mainstream pm.
830                if let Some(ws_version) = workspace_packages.get(&task.name)
831                    && (match task.range.strip_prefix("workspace:") {
832                        // workspace:*, workspace:^, workspace:~
833                        // bind to whatever local workspace version is.
834                        // These are pnpm's "don't pin me, just track
835                        // local" sigils. Match them before range check.
836                        Some("" | "*" | "^" | "~") => true,
837                        // workspace:<range> like workspace:^2.0.0 or
838                        // workspace:1.x. Must still satisfy local
839                        // version. Before this fix, any workspace:
840                        // prefix short-circuited. Consumer could pin
841                        // workspace:^2 against local 1.0.0 and aube
842                        // would silently link the wrong version.
843                        // pnpm errors here with no-matching-version.
844                        Some(rest) => version_satisfies(ws_version, rest),
845                        // Bare semver (no workspace: prefix) path.
846                        // Linker walks up to workspace yarn-v1 style.
847                        // Special case `*` and `""` (bare catch-all)
848                        // to always match the workspace copy, even
849                        // when the ws version is a prerelease like
850                        // `0.0.0-0` which semver strict rules would
851                        // otherwise exclude. Placeholder versions
852                        // are common in fresh changesets-managed
853                        // workspaces and would silently fall through
854                        // to registry resolution otherwise, picking
855                        // up a stale published build instead of the
856                        // local source.
857                        None if task.range.is_empty() || task.range == "*" => true,
858                        None => version_satisfies(ws_version, &task.range),
859                    })
860                {
861                    let dep_path = dep_path_for(&task.name, ws_version);
862                    if task.is_root
863                        && let Some(deps) = importers.get_mut(&task.importer)
864                    {
865                        deps.push(DirectDep {
866                            name: task.name.clone(),
867                            dep_path: dep_path.clone(),
868                            dep_type: task.dep_type,
869                            specifier: task.original_specifier.clone(),
870                        });
871                    }
872                    if let Some(ref parent_dp) = task.parent
873                        && let Some(parent_pkg) = resolved.get_mut(parent_dp)
874                    {
875                        parent_pkg
876                            .dependencies
877                            .insert(task.name.clone(), ws_version.clone());
878                        if task.dep_type == DepType::Optional {
879                            parent_pkg
880                                .optional_dependencies
881                                .insert(task.name.clone(), ws_version.clone());
882                        }
883                    }
884                    if task.is_root {
885                        note_root_done!();
886                    }
887                    continue;
888                }
889
890                // Sibling dedupe. If another task for this same name
891                // has already settled on a version that satisfies
892                // this task's range, wire up to that resolution and
893                // short-circuit. In the old wave code this check
894                // lived in the post-fetch loop as `existing_match`;
895                // in the pipelined loop we run it up front so
896                // dedupable tasks never block on a fetch or a
897                // lockfile scan.
898                if let Some(matched_ver) = resolved_versions.get(&task.name).and_then(|versions| {
899                    versions
900                        .iter()
901                        .find(|v| version_satisfies(v, &task.range))
902                        .cloned()
903                }) {
904                    let dep_path = dep_path_for(&task.name, &matched_ver);
905                    if task.is_root
906                        && let Some(deps) = importers.get_mut(&task.importer)
907                    {
908                        deps.push(DirectDep {
909                            name: task.name.clone(),
910                            dep_path: dep_path.clone(),
911                            dep_type: task.dep_type,
912                            specifier: task.original_specifier.clone(),
913                        });
914                    }
915                    if let Some(ref parent_dp) = task.parent
916                        && let Some(parent_pkg) = resolved.get_mut(parent_dp)
917                    {
918                        parent_pkg
919                            .dependencies
920                            .insert(task.name.clone(), matched_ver.clone());
921                        if task.dep_type == DepType::Optional {
922                            parent_pkg
923                                .optional_dependencies
924                                .insert(task.name.clone(), matched_ver);
925                        }
926                    }
927                    if task.is_root {
928                        note_root_done!();
929                    }
930                    continue;
931                }
932
933                // Lockfile reuse. Runs unconditionally after sibling
934                // dedupe fails — the old code gated this behind a
935                // `cache.contains_key` check, but in the pipelined
936                // loop the cache is populated incrementally and the
937                // gate was a false optimization.
938                {
939                    if let Some(locked_pkg) = existing.and_then(|g| {
940                        g.packages.values().find(|p| {
941                            p.name == task.name && version_satisfies(&p.version, &task.range)
942                        })
943                    }) {
944                        // Drop optional deps whose platform constraints
945                        // don't match the active host / supported set.
946                        // This is the path that handles frozen/lockfile
947                        // installs on a different machine than the one
948                        // that wrote the lockfile.
949                        if task.dep_type == DepType::Optional
950                            && !is_supported(
951                                &locked_pkg.os,
952                                &locked_pkg.cpu,
953                                &locked_pkg.libc,
954                                &self.supported_architectures,
955                            )
956                        {
957                            tracing::debug!(
958                                "skipping optional dep {}@{}: platform mismatch",
959                                task.name,
960                                locked_pkg.version
961                            );
962                            if task.is_root
963                                && let Some(spec) = task.original_specifier.as_ref()
964                            {
965                                skipped_optional_dependencies
966                                    .entry(task.importer.clone())
967                                    .or_default()
968                                    .insert(task.name.clone(), spec.clone());
969                            }
970                            if task.is_root {
971                                note_root_done!();
972                            }
973                            continue;
974                        }
975                        let version = locked_pkg.version.clone();
976                        let dep_path = dep_path_for(&task.name, &version);
977
978                        if task.is_root
979                            && let Some(deps) = importers.get_mut(&task.importer)
980                        {
981                            deps.push(DirectDep {
982                                name: task.name.clone(),
983                                dep_path: dep_path.clone(),
984                                dep_type: task.dep_type,
985                                specifier: task.original_specifier.clone(),
986                            });
987                        }
988                        if let Some(ref parent_dp) = task.parent
989                            && let Some(parent_pkg) = resolved.get_mut(parent_dp)
990                        {
991                            parent_pkg
992                                .dependencies
993                                .insert(task.name.clone(), version.clone());
994                            if task.dep_type == DepType::Optional {
995                                parent_pkg
996                                    .optional_dependencies
997                                    .insert(task.name.clone(), version.clone());
998                            }
999                        }
1000                        if visited.insert(std::sync::Arc::from(dep_path.as_str())) {
1001                            resolved_versions
1002                                .entry(task.name.clone())
1003                                .or_default()
1004                                .push(version.clone());
1005
1006                            // Carry any round-tripped publish time
1007                            // forward so (a) the cutoff computation at
1008                            // the end of wave 0 can see reused directs
1009                            // alongside freshly-resolved ones and
1010                            // (b) the next lockfile write preserves the
1011                            // existing `time:` entry even when this
1012                            // install reuses the locked version without
1013                            // re-fetching a packument.
1014                            if self.should_record_times()
1015                                && let Some(g) = existing
1016                                && let Some(t) = g.times.get(&dep_path)
1017                            {
1018                                resolved_times.insert(dep_path.clone(), t.clone());
1019                            }
1020
1021                            if let Some(ref tx) = self.resolved_tx {
1022                                let _ = tx.send(ResolvedPackage {
1023                                    dep_path: dep_path.clone(),
1024                                    name: task.name.clone(),
1025                                    version: version.clone(),
1026                                    integrity: locked_pkg.integrity.clone(),
1027                                    tarball_url: locked_pkg.tarball_url.clone(),
1028                                    // Carry the alias identity
1029                                    // through the reuse path — the
1030                                    // existing `locked_pkg` already
1031                                    // records it if the lockfile held
1032                                    // an aliased entry, so the
1033                                    // streaming fetch still hits the
1034                                    // real registry name.
1035                                    alias_of: locked_pkg.alias_of.clone(),
1036                                    local_source: locked_pkg.local_source.clone(),
1037                                    os: locked_pkg.os.clone(),
1038                                    cpu: locked_pkg.cpu.clone(),
1039                                    libc: locked_pkg.libc.clone(),
1040                                    // Lockfile reuse skips the packument
1041                                    // fetch, so we have no deprecation
1042                                    // message to forward here. The
1043                                    // `aube deprecations` command re-queries
1044                                    // packuments live for the
1045                                    // after-the-fact view.
1046                                    deprecated: None,
1047                                });
1048                            }
1049
1050                            // Carry declared peer deps forward from the
1051                            // existing lockfile so subsequent peer-context
1052                            // computation sees them without a re-fetch.
1053                            resolved.insert(
1054                                dep_path.clone(),
1055                                LockedPackage {
1056                                    name: task.name.clone(),
1057                                    version: version.clone(),
1058                                    integrity: locked_pkg.integrity.clone(),
1059                                    dependencies: BTreeMap::new(),
1060                                    optional_dependencies: BTreeMap::new(),
1061                                    peer_dependencies: locked_pkg.peer_dependencies.clone(),
1062                                    peer_dependencies_meta: locked_pkg
1063                                        .peer_dependencies_meta
1064                                        .clone(),
1065                                    dep_path: dep_path.clone(),
1066                                    local_source: locked_pkg.local_source.clone(),
1067                                    os: locked_pkg.os.clone(),
1068                                    cpu: locked_pkg.cpu.clone(),
1069                                    libc: locked_pkg.libc.clone(),
1070                                    bundled_dependencies: locked_pkg.bundled_dependencies.clone(),
1071                                    optional: locked_pkg.optional,
1072                                    transitive_peer_dependencies: locked_pkg
1073                                        .transitive_peer_dependencies
1074                                        .clone(),
1075                                    tarball_url: locked_pkg.tarball_url.clone(),
1076                                    alias_of: locked_pkg.alias_of.clone(),
1077                                    yarn_checksum: locked_pkg.yarn_checksum.clone(),
1078                                    engines: locked_pkg.engines.clone(),
1079                                    bin: locked_pkg.bin.clone(),
1080                                    declared_dependencies: locked_pkg.declared_dependencies.clone(),
1081                                    license: locked_pkg.license.clone(),
1082                                    funding_url: locked_pkg.funding_url.clone(),
1083                                    extra_meta: locked_pkg.extra_meta.clone(),
1084                                },
1085                            );
1086
1087                            // Enqueue transitive deps from the locked package.
1088                            // Strip any peer-context suffix off the version
1089                            // before treating it as a semver range — a
1090                            // locked `"18.2.0(react@18.2.0)"` tail should
1091                            // match against packuments as just `18.2.0`.
1092                            // Also strip a leading `name@` if present:
1093                            // bun/yarn parsers store transitive deps in
1094                            // `name@version` (full dep_path) form, while
1095                            // pnpm stores bare versions. Without the
1096                            // strip, a yarn/bun-locked `is-odd` would
1097                            // emit a transitive task for is-number with
1098                            // range `"is-number@6.0.0"`, which doesn't
1099                            // parse as semver and fails resolution.
1100                            // The lockfile already omitted bundled dep
1101                            // edges on write, so iterating
1102                            // `locked_pkg.dependencies` naturally skips them.
1103                            let mut child_ancestors = task.ancestors.clone();
1104                            child_ancestors.push((task.name.clone(), version.clone()));
1105                            for (dep_name, dep_version) in &locked_pkg.dependencies {
1106                                let prefix = format!("{dep_name}@");
1107                                let stripped =
1108                                    dep_version.strip_prefix(&prefix).unwrap_or(dep_version);
1109                                let canonical_version =
1110                                    stripped.split('(').next().unwrap_or(stripped).to_string();
1111                                let dep_type =
1112                                    if locked_pkg.optional_dependencies.contains_key(dep_name) {
1113                                        DepType::Optional
1114                                    } else {
1115                                        DepType::Production
1116                                    };
1117                                queue.push_back(ResolveTask::transitive(
1118                                    dep_name.clone(),
1119                                    canonical_version,
1120                                    dep_type,
1121                                    dep_path.clone(),
1122                                    task.importer.clone(),
1123                                    child_ancestors.clone(),
1124                                ));
1125                            }
1126                        }
1127                        lockfile_reuse_count += 1;
1128                        if task.is_root {
1129                            note_root_done!();
1130                        }
1131                        continue;
1132                    }
1133                }
1134
1135                // Packument not in cache. Spawn its fetch if one
1136                // isn't already running, then wait for packument
1137                // fetches to land until this task's packument is
1138                // available. Other fetches that happen to complete
1139                // while we're waiting get cached opportunistically,
1140                // which is exactly what lets the pipeline overlap
1141                // network and CPU: by the time a later task is
1142                // popped its packument is usually already sitting
1143                // in the cache because it landed while an earlier
1144                // task was being waited on.
1145                let wait_start = std::time::Instant::now();
1146                // Cache is keyed by the *registry* name — for aliased
1147                // tasks `task.name` is the user-facing alias (e.g.
1148                // `h3-v2`), which would never hit. `registry_name()`
1149                // returns the alias-resolved target (`h3`) on
1150                // aliased tasks and `task.name` otherwise.
1151                let fetch_name = task.registry_name().to_string();
1152                while !self.cache.contains_key(&fetch_name) {
1153                    ensure_fetch!(&fetch_name);
1154                    match in_flight.join_next().await {
1155                        Some(Ok(Ok((name, packument)))) => {
1156                            in_flight_names.remove(&name);
1157                            self.cache.insert(name, packument);
1158                            packument_fetch_count += 1;
1159                        }
1160                        Some(Ok(Err(e))) => return Err(e),
1161                        Some(Err(join_err)) => {
1162                            return Err(Error::Registry(
1163                                "(join)".to_string(),
1164                                join_err.to_string(),
1165                            ));
1166                        }
1167                        None => {
1168                            // ensure_fetch! guarantees something is
1169                            // in flight if the cache still doesn't
1170                            // hold this name, so a None here means
1171                            // the spawn failed silently. Surface it.
1172                            return Err(Error::Registry(
1173                                fetch_name.clone(),
1174                                "packument fetch disappeared before completing".to_string(),
1175                            ));
1176                        }
1177                    }
1178                }
1179                packument_fetch_time += wait_start.elapsed();
1180
1181                // TimeBased wave-0 gate. Transitives that reach
1182                // the version-pick step while the cutoff is still
1183                // unknown must wait until the direct deps have
1184                // been picked and the cutoff has been derived;
1185                // otherwise they'd pick against a `None` cutoff
1186                // and miss the filter. In `Highest` mode (the
1187                // default), `cutoff_pending` starts false and this
1188                // is a no-op.
1189                if cutoff_pending && !task.is_root {
1190                    deferred_transitives.push(task);
1191                    continue;
1192                }
1193
1194                // Version-pick + transitive enqueue. Was a separate
1195                // sub-loop over `processed_batch` in the old wave
1196                // code; here it's inline as the tail of the per-task
1197                // pipeline now that we know the packument is in
1198                // cache. `registry_name()` is the cache key for
1199                // aliased tasks (cache is populated under the real
1200                // registry name), so use the same accessor here.
1201                let packument = self.cache.get(task.registry_name()).ok_or_else(|| {
1202                    Error::Registry(
1203                        task.registry_name().to_string(),
1204                        "packument not in cache".to_string(),
1205                    )
1206                })?;
1207
1208                // Find locked version
1209                let locked_version = existing.and_then(|g| {
1210                    g.packages
1211                        .values()
1212                        .find(|p| p.name == task.name && version_satisfies(&p.version, &task.range))
1213                        .map(|p| p.version.as_str())
1214                });
1215
1216                // Direct deps in time-based mode pick the lowest
1217                // satisfying version; everything else (transitives,
1218                // and all picks in Highest mode) picks highest.
1219                let pick_lowest = self.resolution_mode == ResolutionMode::TimeBased && task.is_root;
1220                // Apply the cutoff unless this package is on the
1221                // minimumReleaseAge exclude list. The exclude list only
1222                // suppresses the *minimumReleaseAge* leg, not the
1223                // time-based-mode leg — but since we collapse both
1224                // into the same `published_by` string at this point,
1225                // we have to skip the cutoff entirely for excluded
1226                // names. Acceptable: time-based mode and exclude
1227                // lists aren't expected to coexist in the wild.
1228                let cutoff_for_pkg = match self.minimum_release_age.as_ref() {
1229                    Some(mra) if mra.exclude.contains(&task.name) => None,
1230                    _ => published_by.as_deref(),
1231                };
1232                // Strict semantics in two cases:
1233                //   - `minimumReleaseAgeStrict=true` (the user opted in
1234                //     to hard failures), or
1235                //   - the cutoff comes from `--resolution-mode=time-based`
1236                //     alone, with no `minimumReleaseAge` configured. The
1237                //     time-based cutoff is intended as a hard wall — if
1238                //     no version fits, the *correct* fix is for the user
1239                //     to update the lockfile, not for the resolver to
1240                //     silently pick a different version.
1241                let strict = match self.minimum_release_age.as_ref() {
1242                    Some(m) => m.strict,
1243                    None => true,
1244                };
1245                let pick = pick_version(
1246                    packument,
1247                    &task.range,
1248                    locked_version,
1249                    pick_lowest,
1250                    cutoff_for_pkg,
1251                    strict,
1252                );
1253                let picked_ref = match pick {
1254                    PickResult::Found(meta) => meta,
1255                    // Only surface `AgeGate` when the cutoff actually
1256                    // came from `minimumReleaseAge`. When it came from
1257                    // `--resolution-mode=time-based` alone, the user
1258                    // never opted into the supply-chain age gate, so
1259                    // the failure should report as a plain no-match
1260                    // instead of a misleading "older than 0 minutes".
1261                    PickResult::AgeGated => match self.minimum_release_age.as_ref() {
1262                        Some(mra) => {
1263                            return Err(Error::AgeGate(Box::new(error::build_age_gate(
1264                                &task,
1265                                packument,
1266                                mra.minutes,
1267                            ))));
1268                        }
1269                        None => {
1270                            return Err(Error::NoMatch(Box::new(error::build_no_match(
1271                                &task, packument,
1272                            ))));
1273                        }
1274                    },
1275                    PickResult::NoMatch => {
1276                        return Err(Error::NoMatch(Box::new(error::build_no_match(
1277                            &task, packument,
1278                        ))));
1279                    }
1280                };
1281                // Trust-policy enforcement runs *before* any other
1282                // post-pick processing (mirrors pnpm's placement
1283                // immediately after `pickPackage`). Skip when policy is
1284                // off so the off-by-default case is a single enum
1285                // compare. The check needs the live packument's `time`
1286                // map and all version metadata, both of which are still
1287                // in scope here from L1191.
1288                if self.dependency_policy.trust_policy == crate::TrustPolicy::NoDowngrade {
1289                    crate::trust::check_no_downgrade(
1290                        packument,
1291                        &picked_ref.version,
1292                        picked_ref,
1293                        &self.dependency_policy.trust_policy_exclude,
1294                        self.dependency_policy.trust_policy_ignore_after,
1295                    )
1296                    .map_err(|e| match e {
1297                        crate::trust::TrustCheckError::Downgrade(d) => {
1298                            Error::TrustDowngrade(Box::new(d))
1299                        }
1300                        crate::trust::TrustCheckError::MissingTime(d) => {
1301                            Error::TrustCheckMissingTime(Box::new(d))
1302                        }
1303                    })?;
1304                }
1305
1306                // Clone the picked metadata into an owned value so we can
1307                // both run the `readPackage` hook (which needs a
1308                // disjoint `&mut self` borrow) and, later, mutate the
1309                // resolver's own caches without holding a borrow into
1310                // `self.cache`. Also grab the publish-time entry now,
1311                // for the same reason.
1312                let mut picked_owned = picked_ref.clone();
1313                let picked_publish_time = packument.time.get(&picked_ref.version).cloned();
1314                // Skip the readPackage hook entirely for a `(name, version)`
1315                // pair we've already fully processed via a prior task. The
1316                // mutated dep maps only drive the transitive enqueue below,
1317                // and that block is short-circuited by the `visited` guard
1318                // later in this iteration — so running the hook here would
1319                // just burn an IPC round-trip whose result is discarded.
1320                let prehook_dep_path = dep_path_for(&task.name, &picked_ref.version);
1321                let already_visited = visited.contains(prehook_dep_path.as_str());
1322
1323                if !already_visited {
1324                    apply_package_extensions(
1325                        &mut picked_owned,
1326                        &self.dependency_policy.package_extensions,
1327                    );
1328                }
1329
1330                // readPackage hook. Runs at most once per version-picked
1331                // package, before transitive enqueue. We honor edits to
1332                // the four dep maps and warn on (then discard) edits to
1333                // name/version/dist/platform/`hasInstallScript` — pnpm
1334                // tolerates readPackage returning a hollowed-out
1335                // object, so we restore those fields from the original
1336                // packument entry after the call.
1337                if !already_visited && let Some(hook) = self.read_package_hook.as_mut() {
1338                    let before_name = picked_owned.name.clone();
1339                    let before_version = picked_owned.version.clone();
1340                    let before_dist = picked_owned.dist.clone();
1341                    let before_os = picked_owned.os.clone();
1342                    let before_cpu = picked_owned.cpu.clone();
1343                    let before_libc = picked_owned.libc.clone();
1344                    let before_bundled = picked_owned.bundled_dependencies.clone();
1345                    let before_has_install_script = picked_owned.has_install_script;
1346                    let before_deprecated = picked_owned.deprecated.clone();
1347                    let input = picked_owned.clone();
1348                    let mut after = hook.read_package(input).await.map_err(|e| {
1349                        Error::Registry(before_name.clone(), format!("readPackage hook: {e}"))
1350                    })?;
1351                    if after.name != before_name || after.version != before_version {
1352                        tracing::warn!(
1353                            "[pnpmfile] readPackage rewrote {}@{} identity to {}@{}; \
1354                             aube ignores identity edits",
1355                            before_name,
1356                            before_version,
1357                            after.name,
1358                            after.version,
1359                        );
1360                    }
1361                    after.name = before_name;
1362                    after.version = before_version;
1363                    after.dist = before_dist;
1364                    after.os = before_os;
1365                    after.cpu = before_cpu;
1366                    after.libc = before_libc;
1367                    after.bundled_dependencies = before_bundled;
1368                    after.has_install_script = before_has_install_script;
1369                    after.deprecated = before_deprecated;
1370                    picked_owned = after;
1371                }
1372                let version_meta = &picked_owned;
1373
1374                // Optional deps that don't match the host platform get
1375                // silently dropped — pnpm parity. Required deps with a
1376                // bad platform still get installed; the warning matches
1377                // pnpm's `packageIsInstallable` behavior.
1378                let platform_ok = is_supported(
1379                    &version_meta.os,
1380                    &version_meta.cpu,
1381                    &version_meta.libc,
1382                    &self.supported_architectures,
1383                );
1384                if !platform_ok {
1385                    if task.dep_type == DepType::Optional {
1386                        tracing::debug!(
1387                            "skipping optional dep {}@{}: unsupported platform (os={:?} cpu={:?} libc={:?})",
1388                            task.name,
1389                            version_meta.version,
1390                            version_meta.os,
1391                            version_meta.cpu,
1392                            version_meta.libc
1393                        );
1394                        if task.is_root
1395                            && let Some(spec) = task.original_specifier.as_ref()
1396                        {
1397                            skipped_optional_dependencies
1398                                .entry(task.importer.clone())
1399                                .or_default()
1400                                .insert(task.name.clone(), spec.clone());
1401                        }
1402                        if task.is_root {
1403                            note_root_done!();
1404                        }
1405                        continue;
1406                    }
1407                    tracing::warn!(
1408                        "required dep {}@{} declares unsupported platform (os={:?} cpu={:?} libc={:?}); installing anyway",
1409                        task.name,
1410                        version_meta.version,
1411                        version_meta.os,
1412                        version_meta.cpu,
1413                        version_meta.libc
1414                    );
1415                }
1416
1417                let version = version_meta.version.clone();
1418                let dep_path = dep_path_for(&task.name, &version);
1419
1420                // Record publish time for the cutoff / `time:` block
1421                // whenever the packument carries one — matches pnpm,
1422                // which populates `publishedAt` opportunistically via
1423                // `meta.time?.[version]` regardless of resolution mode.
1424                // Corgi packuments from npmjs.org omit `time`, so in
1425                // Highest mode this is usually a no-op; Verdaccio
1426                // (v5.15.1+) and full-packument fetches do include it,
1427                // and then we round-trip it into the lockfile just like
1428                // pnpm does.
1429                if self.should_record_times()
1430                    && let Some(t) = picked_publish_time.as_ref()
1431                {
1432                    resolved_times.insert(dep_path.clone(), t.clone());
1433                }
1434
1435                // Record root dep
1436                if task.is_root
1437                    && let Some(deps) = importers.get_mut(&task.importer)
1438                {
1439                    deps.push(DirectDep {
1440                        name: task.name.clone(),
1441                        dep_path: dep_path.clone(),
1442                        dep_type: task.dep_type,
1443                        specifier: task.original_specifier.clone(),
1444                    });
1445                }
1446
1447                // Wire parent
1448                if let Some(ref parent_dp) = task.parent
1449                    && let Some(parent_pkg) = resolved.get_mut(parent_dp)
1450                {
1451                    parent_pkg
1452                        .dependencies
1453                        .insert(task.name.clone(), version.clone());
1454                    if task.dep_type == DepType::Optional {
1455                        parent_pkg
1456                            .optional_dependencies
1457                            .insert(task.name.clone(), version.clone());
1458                    }
1459                }
1460
1461                // Skip if already fully processed this exact version
1462                if visited.contains(dep_path.as_str()) {
1463                    if task.is_root {
1464                        note_root_done!();
1465                    }
1466                    continue;
1467                }
1468                visited.insert(std::sync::Arc::from(dep_path.as_str()));
1469
1470                tracing::trace!("resolved {}@{}", task.name, version);
1471
1472                // Forward a deprecation message to the install command,
1473                // subject to `allowedDeprecatedVersions` suppression.
1474                // User-facing rendering is the CLI's job — doing it here
1475                // would fire per resolved version with no way for the
1476                // caller to batch or filter direct-vs-transitive.
1477                let deprecated_msg: Option<Arc<str>> =
1478                    version_meta.deprecated.as_deref().and_then(|msg| {
1479                        let suppressed = is_deprecation_allowed(
1480                            &task.name,
1481                            &version,
1482                            &self.dependency_policy.allowed_deprecated_versions,
1483                        );
1484                        (!suppressed).then(|| Arc::<str>::from(msg))
1485                    });
1486
1487                // Track this version
1488                resolved_versions
1489                    .entry(task.name.clone())
1490                    .or_default()
1491                    .push(version.clone());
1492
1493                let integrity = version_meta.dist.as_ref().and_then(|d| d.integrity.clone());
1494                // Always stash the registry tarball URL on the locked
1495                // package. pnpm / yarn writers gate emission on
1496                // `lockfile_include_tarball_url` (so the pnpm
1497                // round-trip stays byte-identical for projects that
1498                // opted out); the npm writer emits `resolved:` on
1499                // every package entry unconditionally, which is what
1500                // npm itself writes. Carrying the URL on every
1501                // LockedPackage lets both policies work without a
1502                // second packument fetch at write time.
1503                let tarball_url = version_meta.dist.as_ref().map(|d| d.tarball.clone());
1504
1505                // Stream this resolved package for early tarball fetching.
1506                // `alias_of` mirrors what the LockedPackage below
1507                // will carry — the streaming fetch consumer in
1508                // install.rs uses it to derive the real tarball URL
1509                // for aliased packages where `name` alone (`h3-v2`)
1510                // would 404.
1511                if let Some(ref tx) = self.resolved_tx {
1512                    let _ = tx.send(ResolvedPackage {
1513                        dep_path: dep_path.clone(),
1514                        name: task.name.clone(),
1515                        version: version.clone(),
1516                        integrity: integrity.clone(),
1517                        tarball_url: tarball_url.clone(),
1518                        alias_of: task.real_name.clone(),
1519                        local_source: None,
1520                        os: version_meta.os.iter().cloned().collect(),
1521                        cpu: version_meta.cpu.iter().cloned().collect(),
1522                        libc: version_meta.libc.iter().cloned().collect(),
1523                        deprecated: deprecated_msg.clone(),
1524                    });
1525                }
1526
1527                // Capture the declared peer deps now so the post-pass can
1528                // compute each consumer's peer context without re-reading
1529                // the packument.
1530                let peer_deps = version_meta.peer_dependencies.clone();
1531                let peer_meta: BTreeMap<String, aube_lockfile::PeerDepMeta> = version_meta
1532                    .peer_dependencies_meta
1533                    .iter()
1534                    .map(|(k, v)| {
1535                        (
1536                            k.clone(),
1537                            aube_lockfile::PeerDepMeta {
1538                                optional: v.optional,
1539                            },
1540                        )
1541                    })
1542                    .collect();
1543                // `bundledDependencies` names are shipped inside the
1544                // tarball itself and must not be resolved from the
1545                // registry. If we did enqueue them, we'd fetch a
1546                // (possibly different) version and plant a sibling
1547                // symlink inside `.aube/<parent>@ver/node_modules/`
1548                // that would shadow the bundled copy during Node's
1549                // directory walk. Compute the skip set once here and
1550                // store the names on the LockedPackage so restore
1551                // (from lockfile, skipping this code path) also
1552                // knows to avoid the sibling symlinks — see the
1553                // `.dependencies` write-through downstream.
1554                let bundled_names: FxHashSet<String> = version_meta
1555                    .bundled_dependencies
1556                    .as_ref()
1557                    .map(|b| {
1558                        b.names(&version_meta.dependencies)
1559                            .into_iter()
1560                            .map(String::from)
1561                            .collect()
1562                    })
1563                    .unwrap_or_default();
1564
1565                resolved.insert(
1566                    dep_path.clone(),
1567                    LockedPackage {
1568                        name: task.name.clone(),
1569                        version: version.clone(),
1570                        integrity,
1571                        dependencies: BTreeMap::new(),
1572                        optional_dependencies: BTreeMap::new(),
1573                        peer_dependencies: peer_deps,
1574                        peer_dependencies_meta: peer_meta,
1575                        dep_path: dep_path.clone(),
1576                        local_source: None,
1577                        os: version_meta.os.iter().cloned().collect(),
1578                        cpu: version_meta.cpu.iter().cloned().collect(),
1579                        libc: version_meta.libc.iter().cloned().collect(),
1580                        bundled_dependencies: {
1581                            let mut v: Vec<String> = bundled_names.iter().cloned().collect();
1582                            v.sort();
1583                            v
1584                        },
1585                        tarball_url,
1586                        // `name` is the alias for npm-aliased tasks
1587                        // (`"h3-v2": "npm:h3@..."` → name = "h3-v2"),
1588                        // so stash the real registry name here. The
1589                        // lockfile writer + installer consult
1590                        // `alias_of` whenever they need to hit the
1591                        // registry, matching how the npm-lockfile
1592                        // reader populates this field.
1593                        alias_of: task.real_name.clone(),
1594                        yarn_checksum: None,
1595                        engines: version_meta.engines.clone(),
1596                        // Rehydrate a string-form bin (`"bin": "cli.js"`)
1597                        // into `{<package_name>: "cli.js"}` — registry
1598                        // packuments leave the name off, expecting
1599                        // consumers to default it to the package name.
1600                        // Doing it here keeps bun's per-entry meta
1601                        // byte-identical to bun's own output without
1602                        // pushing the fixup into every writer.
1603                        bin: {
1604                            let mut m = version_meta.bin.clone();
1605                            if let Some(path) = m.remove("") {
1606                                // String-form `bin` in a packument
1607                                // (`"bin": "cli.js"`) is implicitly
1608                                // named after the real registry
1609                                // package — not the alias. For an
1610                                // aliased dep (`"h3-v2": "npm:h3@…"`)
1611                                // the bun writer must emit the bin
1612                                // under `h3`, not `h3-v2`, or the
1613                                // map drifts against bun's own
1614                                // output (and the shim install path
1615                                // creates the wrong binary name).
1616                                let bin_name =
1617                                    task.real_name.as_deref().unwrap_or(&task.name).to_string();
1618                                m.insert(bin_name, path);
1619                            }
1620                            m
1621                        },
1622                        // Declared ranges straight from the packument's
1623                        // `dependencies` / `optionalDependencies`. Fed
1624                        // back out by npm / yarn / bun writers so
1625                        // nested package entries keep the original
1626                        // specifiers instead of collapsing to pins.
1627                        declared_dependencies: {
1628                            let mut m = version_meta.dependencies.clone();
1629                            for (k, v) in &version_meta.optional_dependencies {
1630                                m.insert(k.clone(), v.clone());
1631                            }
1632                            m
1633                        },
1634                        license: version_meta.license.clone(),
1635                        funding_url: version_meta.funding_url.clone(),
1636                        optional: false,
1637                        transitive_peer_dependencies: Vec::new(),
1638                        extra_meta: BTreeMap::new(),
1639                    },
1640                );
1641
1642                // Enqueue transitive deps. Kick off a background
1643                // packument fetch the instant we discover the dep
1644                // name — so by the time the task is popped off the
1645                // queue below, its packument is usually already in
1646                // flight (and often already in cache). This is where
1647                // the pipeline overlaps fetches with CPU work without
1648                // any explicit wave barrier.
1649                //
1650                // Compute the child ancestor chain once — the same
1651                // frame (this package's name + resolved version)
1652                // applies to every dep / optionalDep / peer we enqueue
1653                // below.
1654                let mut child_ancestors = task.ancestors.clone();
1655                child_ancestors.push((task.name.clone(), version.clone()));
1656
1657                for (dep_name, dep_range) in &version_meta.dependencies {
1658                    if bundled_names.contains(dep_name) {
1659                        continue;
1660                    }
1661                    if self.dependency_policy.block_exotic_subdeps
1662                        && is_non_registry_specifier(dep_range)
1663                    {
1664                        return Err(Error::Registry(
1665                            dep_name.clone(),
1666                            format!(
1667                                "uses exotic specifier \"{dep_range}\" which is blocked \
1668                                 by blockExoticSubdeps (declared by {})",
1669                                task.name
1670                            ),
1671                        ));
1672                    }
1673                    if !existing_names.contains(dep_name.as_str())
1674                        && prefetchable!(dep_name.as_str(), dep_range.as_str())
1675                    {
1676                        ensure_fetch!(dep_name);
1677                    }
1678                    queue.push_back(ResolveTask::transitive(
1679                        dep_name.clone(),
1680                        dep_range.clone(),
1681                        DepType::Production,
1682                        dep_path.clone(),
1683                        task.importer.clone(),
1684                        child_ancestors.clone(),
1685                    ));
1686                }
1687
1688                for (dep_name, dep_range) in &version_meta.optional_dependencies {
1689                    if bundled_names.contains(dep_name) {
1690                        continue;
1691                    }
1692                    if self.ignored_optional_dependencies.contains(dep_name) {
1693                        continue;
1694                    }
1695                    if self.dependency_policy.block_exotic_subdeps
1696                        && is_non_registry_specifier(dep_range)
1697                    {
1698                        tracing::warn!(
1699                            "skipping optional dependency {dep_name} of {} — \
1700                             exotic specifier \"{dep_range}\" blocked by blockExoticSubdeps",
1701                            task.name
1702                        );
1703                        continue;
1704                    }
1705                    if !existing_names.contains(dep_name.as_str())
1706                        && prefetchable!(dep_name.as_str(), dep_range.as_str())
1707                    {
1708                        ensure_fetch!(dep_name);
1709                    }
1710                    queue.push_back(ResolveTask::transitive(
1711                        dep_name.clone(),
1712                        dep_range.clone(),
1713                        DepType::Optional,
1714                        dep_path.clone(),
1715                        task.importer.clone(),
1716                        child_ancestors.clone(),
1717                    ));
1718                }
1719
1720                // Peer dependencies: enqueue only required peers that
1721                // are truly missing from the importer/root scope. The
1722                // post-pass below (`apply_peer_contexts`) computes
1723                // which version each consumer sees, via ancestor
1724                // scope, and assigns peer-suffixed dep_paths.
1725                //
1726                // pnpm's `auto-install-peers=true` fills in missing
1727                // required peers, but it does not install optional peer
1728                // alternatives that the user did not ask for, and it
1729                // does not install a second compatible peer when the
1730                // importer already declares that peer name at an
1731                // incompatible version. In the latter case pnpm keeps
1732                // the user's direct dependency and reports an unmet
1733                // peer warning.
1734                //
1735                // When `auto-install-peers=false`, we skip enqueueing
1736                // peers entirely. Users are on the hook for adding
1737                // them to `package.json` themselves. Unmet peers still
1738                // surface as warnings via `detect_unmet_peers` after
1739                // resolve — in fact more so, since nothing gets
1740                // auto-installed.
1741                //
1742                // Skip peers that are already declared as regular or
1743                // optional deps of the same package — those already have a
1744                // task queued via the loops above, and duplicating would
1745                // just burn a queue slot.
1746                if self.auto_install_peers {
1747                    for (dep_name, dep_range) in &version_meta.peer_dependencies {
1748                        let peer_optional = version_meta
1749                            .peer_dependencies_meta
1750                            .get(dep_name)
1751                            .map(|m| m.optional)
1752                            .unwrap_or(false);
1753                        // Optional peers are opt-in integrations, not
1754                        // auto-install candidates. Users who need one must
1755                        // declare it in their own manifest so the normal dep
1756                        // loops above resolve it explicitly.
1757                        if peer_optional {
1758                            continue;
1759                        }
1760                        let importer_declares_peer = importer_declared_dep_names
1761                            .get(&task.importer)
1762                            .is_some_and(|names| names.contains(dep_name));
1763                        let root_declares_peer = self.resolve_peers_from_workspace_root
1764                            && task.importer != "."
1765                            && importer_declared_dep_names
1766                                .get(".")
1767                                .is_some_and(|names| names.contains(dep_name));
1768                        let peer_dep_is_ancestor =
1769                            task.ancestors.iter().any(|(name, _)| name == dep_name);
1770                        if importer_declares_peer || root_declares_peer || peer_dep_is_ancestor {
1771                            continue;
1772                        }
1773                        if version_meta.dependencies.contains_key(dep_name)
1774                            || version_meta.optional_dependencies.contains_key(dep_name)
1775                            || bundled_names.contains(dep_name)
1776                        {
1777                            continue;
1778                        }
1779                        if self.dependency_policy.block_exotic_subdeps
1780                            && is_non_registry_specifier(dep_range)
1781                        {
1782                            tracing::warn!(
1783                                "skipping peer dependency {dep_name} of {} — \
1784                                 exotic specifier \"{dep_range}\" blocked \
1785                                 by blockExoticSubdeps",
1786                                task.name
1787                            );
1788                            continue;
1789                        }
1790                        if !existing_names.contains(dep_name.as_str())
1791                            && prefetchable!(dep_name.as_str(), dep_range.as_str())
1792                        {
1793                            ensure_fetch!(dep_name);
1794                        }
1795                        queue.push_back(ResolveTask::transitive(
1796                            dep_name.clone(),
1797                            dep_range.clone(),
1798                            DepType::Production,
1799                            dep_path.clone(),
1800                            task.importer.clone(),
1801                            child_ancestors.clone(),
1802                        ));
1803                    }
1804                }
1805
1806                // Root task just completed its full version-pick
1807                // path. Decrement the pending-directs counter so
1808                // the TimeBased cutoff trigger at the top of the
1809                // outer loop can fire once wave 0 is resolved.
1810                if task.is_root {
1811                    note_root_done!();
1812                }
1813            }
1814        }
1815
1816        // Drain any remaining in-flight fetches so their tasks get
1817        // cleanly joined. Normally the main loop has harvested every
1818        // spawned fetch by the time the queue drains, but a few may
1819        // still be pending if the resolver short-circuited via
1820        // sibling dedupe or lockfile reuse after ensure_fetch! had
1821        // already spawned them.
1822        while in_flight.join_next().await.is_some() {}
1823
1824        let resolve_elapsed = resolve_start.elapsed();
1825        tracing::debug!(
1826            "resolver: {:.1?} total, {} packuments fetched ({:.1?} wall), {} reused from lockfile, {} packages resolved",
1827            resolve_elapsed,
1828            packument_fetch_count,
1829            packument_fetch_time,
1830            lockfile_reuse_count,
1831            resolved.len()
1832        );
1833
1834        let resolved_catalogs =
1835            catalog::materialize_catalog_picks(catalog_picks, &resolved_versions);
1836
1837        let canonical = LockfileGraph {
1838            importers,
1839            packages: resolved,
1840            settings: aube_lockfile::LockfileSettings {
1841                auto_install_peers: self.auto_install_peers,
1842                exclude_links_from_lockfile: self.exclude_links_from_lockfile,
1843                // Tarball-URL recording is a lockfile-writer concern; the
1844                // resolver never populates URLs itself. Install flips this
1845                // on after the graph is built when the setting is active.
1846                lockfile_include_tarball_url: false,
1847            },
1848            // Stamp the resolver's overrides into the output graph so the
1849            // lockfile writer can round-trip them and the next install's
1850            // drift check can compare them against the manifest.
1851            overrides: self.overrides.clone(),
1852            ignored_optional_dependencies: self.ignored_optional_dependencies.clone(),
1853            times: resolved_times,
1854            skipped_optional_dependencies,
1855            catalogs: resolved_catalogs,
1856            // Resolver output is format-agnostic; the bun writer layer
1857            // defaults `configVersion` to 1 when emitting a fresh
1858            // lockfile.
1859            bun_config_version: None,
1860            // Fresh resolves don't carry over unknown blocks; the
1861            // install-side merge (`overlay_metadata_from`) copies
1862            // them back from the prior lockfile when round-tripping.
1863            patched_dependencies: BTreeMap::new(),
1864            trusted_dependencies: Vec::new(),
1865            extra_fields: BTreeMap::new(),
1866            workspace_extra_fields: BTreeMap::new(),
1867        };
1868
1869        // Second pass: hoist every auto-installed peer to its importer's
1870        // direct deps so pnpm-style `node_modules/<peer>` top-level
1871        // symlinks get created and the lockfile's `importers.` section
1872        // lists them the way pnpm does with `auto-install-peers=true`.
1873        // Skipped entirely when the setting is off — matches pnpm, which
1874        // leaves the importer's `dependencies` untouched in that mode.
1875        let hoisted = if self.auto_install_peers {
1876            hoist_auto_installed_peers(canonical)
1877        } else {
1878            canonical
1879        };
1880
1881        // Third pass: compute peer-context suffixes for every reachable
1882        // package. See `apply_peer_contexts` for the details.
1883        let peer_options = PeerContextOptions {
1884            dedupe_peer_dependents: self.dedupe_peer_dependents,
1885            dedupe_peers: self.dedupe_peers,
1886            resolve_from_workspace_root: self.resolve_peers_from_workspace_root,
1887            peers_suffix_max_length: self.peers_suffix_max_length,
1888        };
1889        let contextualized = apply_peer_contexts(hoisted, &peer_options);
1890        tracing::debug!(
1891            "peer-context pass produced {} contextualized packages",
1892            contextualized.packages.len()
1893        );
1894        Ok(contextualized)
1895    }
1896}
1897
1898pub(crate) fn modified_allows_short_circuit(modified: &str, cutoff: &str) -> bool {
1899    modified.ends_with('Z') && modified <= cutoff
1900}
1901
1902/// Seed the BFS queue with direct deps from every importer manifest.
1903///
1904/// When a package is declared in more than one section
1905/// (`dependencies` + `devDependencies`, etc.) we keep only the
1906/// highest-priority entry — `dependencies` > `devDependencies` >
1907/// `optionalDependencies` — matching pnpm, which silently drops
1908/// the lower-priority duplicates on resolve. Without this the
1909/// same name gets pushed into the importer's `DirectDep` list
1910/// twice (once per section), and the linker's parallel step 2
1911/// races to create the same `node_modules/<name>` symlink from
1912/// two tasks, producing an `EEXIST` on the loser.
1913fn seed_direct_deps(
1914    manifests: &[(String, PackageJson)],
1915    ignored_optional_dependencies: &BTreeSet<String>,
1916    queue: &mut VecDeque<ResolveTask>,
1917    importers: &mut BTreeMap<String, Vec<DirectDep>>,
1918) {
1919    for (importer_path, manifest) in manifests {
1920        importers.insert(importer_path.clone(), Vec::new());
1921
1922        for (name, range) in &manifest.dependencies {
1923            queue.push_back(ResolveTask::root(
1924                name.clone(),
1925                range.clone(),
1926                DepType::Production,
1927                importer_path.clone(),
1928            ));
1929        }
1930        for (name, range) in &manifest.dev_dependencies {
1931            if manifest.dependencies.contains_key(name) {
1932                continue;
1933            }
1934            queue.push_back(ResolveTask::root(
1935                name.clone(),
1936                range.clone(),
1937                DepType::Dev,
1938                importer_path.clone(),
1939            ));
1940        }
1941        for (name, range) in &manifest.optional_dependencies {
1942            if ignored_optional_dependencies.contains(name) {
1943                tracing::debug!(
1944                    "ignoring optional dependency {name} (pnpm.ignoredOptionalDependencies)"
1945                );
1946                continue;
1947            }
1948            if manifest.dependencies.contains_key(name)
1949                || manifest.dev_dependencies.contains_key(name)
1950            {
1951                continue;
1952            }
1953            queue.push_back(ResolveTask::root(
1954                name.clone(),
1955                range.clone(),
1956                DepType::Optional,
1957                importer_path.clone(),
1958            ));
1959        }
1960    }
1961}