aube 1.38.0

Aube — a fast Node.js package manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{OnceLock, RwLock};

use aube_registry::client::RegistryClient;
use aube_registry::config::NpmConfig;
use miette::{Context, IntoDiagnostic, miette};

use super::{CatalogMap, config, install};

/// Process-wide snapshot of the top-level `--frozen-lockfile` /
/// `--no-frozen-lockfile` / `--prefer-frozen-lockfile` flags. Set once
/// by `async_main` before any command runs so downstream helpers
/// (`ensure_installed`, chained `install::run` calls from
/// `add`/`remove`/`update`/…) can pick them up without plumbing a
/// context struct through every command signature.
static GLOBAL_FROZEN: OnceLock<Option<install::FrozenOverride>> = OnceLock::new();
static GLOBAL_VIRTUAL_STORE: OnceLock<install::GlobalVirtualStoreFlags> = OnceLock::new();
static SKIP_AUTO_INSTALL_ON_PM_MISMATCH: AtomicBool = AtomicBool::new(false);

/// Process-wide registry override from the top-level `--registry=<url>`
/// flag. Applied in `make_client` (and any direct `NpmConfig::load`
/// caller that funnels through `load_npm_config`) so a single flag
/// covers every registry touch point in one invocation.
static REGISTRY_OVERRIDE: RwLock<Option<String>> = RwLock::new(None);

/// Process-wide CLI flag bag for `--fetch-timeout` / `--fetch-retries` /
/// `--fetch-retry-factor` / `--fetch-retry-mintimeout` /
/// `--fetch-retry-maxtimeout`. Threaded into `resolve_fetch_policy`'s
/// `ResolveCtx::cli` so any caller of `make_client` (install, add,
/// publish, audit, …) honors the global flags without each touching the
/// fetch wiring directly. Empty when no flags were set.
static FETCH_CLI_OVERRIDES: OnceLock<Vec<(String, String)>> = OnceLock::new();

#[derive(Copy, Clone, Debug, Default)]
pub(crate) struct GlobalOutputFlags {
    pub ndjson: bool,
    pub silent: bool,
}

static GLOBAL_OUTPUT: OnceLock<GlobalOutputFlags> = OnceLock::new();

tokio::task_local! {
    static EMBEDDER_INSTALL_OVERRIDES: install::EmbedderInstallOverrides;
}

/// Scope native storage paths to one embedded add/install invocation. Keeping
/// them as `PathBuf`s avoids routing filesystem identity through UTF-8 setting
/// strings while preserving task isolation between concurrent embedders.
pub(crate) async fn scope_embedder_install_overrides<F: std::future::Future>(
    overrides: install::EmbedderInstallOverrides,
    future: F,
) -> F::Output {
    EMBEDDER_INSTALL_OVERRIDES.scope(overrides, future).await
}

pub(crate) fn has_embedder_store_override() -> bool {
    EMBEDDER_INSTALL_OVERRIDES
        .try_with(|overrides| overrides.store_dir.is_some())
        .unwrap_or(false)
}

fn embedder_storage_path(
    cwd: &std::path::Path,
    select: impl FnOnce(&install::EmbedderInstallOverrides) -> Option<&std::path::PathBuf>,
) -> Option<std::path::PathBuf> {
    EMBEDDER_INSTALL_OVERRIDES
        .try_with(|overrides| select(overrides).cloned())
        .ok()
        .flatten()
        .map(|path| {
            if path.is_absolute() {
                path
            } else {
                cwd.join(path)
            }
        })
}

pub(crate) fn set_registry_override(url: Option<String>) {
    *REGISTRY_OVERRIDE.write().expect("registry lock poisoned") =
        url.map(|u| aube_registry::config::normalize_registry_url_pub(&u));
}

/// Record the `--fetch-*` global flag bag once per process. Idempotent
/// — second calls (e.g. from a unit test that re-runs `async_main`) are
/// silently ignored, matching the other `set_global_*` helpers.
pub(crate) fn set_fetch_cli_overrides(flags: Vec<(String, String)>) {
    let _ = FETCH_CLI_OVERRIDES.set(flags);
}

pub(crate) fn fetch_cli_overrides() -> &'static [(String, String)] {
    FETCH_CLI_OVERRIDES.get().map(Vec::as_slice).unwrap_or(&[])
}

pub(crate) fn set_skip_auto_install_on_package_manager_mismatch(skip: bool) {
    SKIP_AUTO_INSTALL_ON_PM_MISMATCH.store(skip, Ordering::Relaxed);
}

pub(crate) fn skip_auto_install_on_package_manager_mismatch() -> bool {
    SKIP_AUTO_INSTALL_ON_PM_MISMATCH.load(Ordering::Relaxed)
}

pub(crate) fn registry_override() -> Option<String> {
    REGISTRY_OVERRIDE
        .read()
        .expect("registry lock poisoned")
        .clone()
}

/// Load an `NpmConfig` for `dir` and then apply the process-wide
/// `--registry` override, if any. Use this from any command that
/// needs config but wants the CLI flag to win.
pub(crate) fn load_npm_config(dir: &std::path::Path) -> NpmConfig {
    let mut config = NpmConfig::load(dir);
    if let Some(url) = registry_override() {
        config.registry = url;
    }
    config
}

/// Record the global frozen-lockfile override snapshot. Called once per
/// process from `async_main`.
pub(crate) fn set_global_frozen_override(flags: Option<install::FrozenOverride>) {
    let _ = GLOBAL_FROZEN.set(flags);
}

pub(crate) fn set_global_virtual_store_flags(flags: install::GlobalVirtualStoreFlags) {
    let _ = GLOBAL_VIRTUAL_STORE.set(flags);
}

pub(crate) fn set_global_output_flags(flags: GlobalOutputFlags) {
    let _ = GLOBAL_OUTPUT.set(flags);
}

/// Read the recorded global frozen-lockfile override snapshot, or
/// `None` if none was set — e.g. in unit tests that bypass `async_main`.
pub(crate) fn global_frozen_override() -> Option<install::FrozenOverride> {
    GLOBAL_FROZEN.get().copied().unwrap_or_default()
}

pub(crate) fn global_virtual_store_flags() -> install::GlobalVirtualStoreFlags {
    GLOBAL_VIRTUAL_STORE.get().copied().unwrap_or_default()
}

pub(crate) fn global_output_flags() -> GlobalOutputFlags {
    GLOBAL_OUTPUT.get().copied().unwrap_or_default()
}

/// Owned bundle of the file-source slices that feed a
/// [`aube_settings::ResolveCtx`]: managed config, project + user `.npmrc`,
/// and project + user `~/.config/aube/config.toml`. Construct once with
/// `FileSources::load`, borrow into a `ResolveCtx` via `FileSources::ctx`.
#[derive(Clone)]
pub(crate) struct FileSources {
    pub managed_aube_config: Vec<(String, String)>,
    pub user_npmrc: Vec<(String, String)>,
    pub project_npmrc: Vec<(String, String)>,
    pub user_aube_config: Vec<(String, String)>,
    pub project_aube_config: Vec<(String, String)>,
}

impl FileSources {
    pub(crate) fn load(cwd: &Path) -> Self {
        let npmrc = aube_registry::config::load_npmrc_entries_split(cwd);
        Self {
            managed_aube_config: config::load_managed_aube_config_entries(),
            user_npmrc: npmrc.user,
            project_npmrc: npmrc.project,
            user_aube_config: config::load_user_aube_config_entries(),
            project_aube_config: config::load_project_aube_config_entries(cwd),
        }
    }

    pub(crate) fn extend_project_sources(&mut self, cwd: &Path) {
        let npmrc = aube_registry::config::load_npmrc_entries_split(cwd);
        self.project_npmrc.extend(npmrc.project);
        self.project_aube_config
            .extend(config::load_project_aube_config_entries(cwd));
    }

    pub(crate) fn ctx<'a>(
        &'a self,
        workspace_yaml: &'a std::collections::BTreeMap<String, yaml_serde::Value>,
        env: &'a [(String, String)],
        cli: &'a [(String, String)],
    ) -> aube_settings::ResolveCtx<'a> {
        aube_settings::ResolveCtx {
            managed_aube_config: &self.managed_aube_config,
            project_aube_config: &self.project_aube_config,
            project_npmrc: &self.project_npmrc,
            user_aube_config: &self.user_aube_config,
            user_npmrc: &self.user_npmrc,
            workspace_yaml,
            env,
            cli,
            embedder_defaults: aube_settings::embedder_defaults(),
        }
    }
}

/// Compute the `FrozenMode` a chained install (`add`, `remove`,
/// `update`, `ensure_installed`, …) should use, taking into account
/// the process-wide global `--frozen-lockfile` flags and falling back
/// to the given default when none was set on the command line.
pub(crate) fn chained_frozen_mode(default: install::FrozenMode) -> install::FrozenMode {
    match global_frozen_override() {
        Some(ovr) => install::FrozenMode::from_override(Some(ovr), None),
        None => default,
    }
}

pub(crate) fn ensure_registry_auth_for_package(
    client: &RegistryClient,
    registry_url: &str,
    package_name: &str,
) -> miette::Result<()> {
    if client.has_resolved_auth_for_package(registry_url, package_name) {
        Ok(())
    } else {
        let login_cmd = aube_util::cmd("login");
        let login_hint = package_name
            .split_once('/')
            .map(|(scope, _)| scope)
            .filter(|scope| scope.starts_with('@'))
            .map(|scope| format!("{login_cmd} --registry {registry_url} --scope {scope}"))
            .unwrap_or_else(|| format!("{login_cmd} --registry {registry_url}"));
        Err(miette!(
            "no auth token for {registry_url} package {package_name}. Run `{login_hint}` first."
        ))
    }
}

/// Open the global content-addressable store, honoring a `storeDir`
/// override from `.npmrc` or `pnpm-workspace.yaml` in `cwd`. Falls
/// back to the aube-owned default under `$XDG_DATA_HOME/aube/store/`
/// (see [`aube_store::dirs::store_dir`] for exact resolution).
///
/// The store's cache dir — packument caches, and the global virtual
/// store unless `globalVirtualStoreDir` moves it — comes from
/// [`resolved_cache_dir`], so `cacheDir` and `storeDir` can be pointed
/// at the same volume without touching `XDG_CACHE_HOME`.
///
/// Path interpretation matches pnpm: a leading `~` expands to the
/// user's home directory; relative paths are resolved against `cwd`
/// (so each project sees a consistent store regardless of where the
/// command was invoked from). The CAS schema suffix `v1/files` is
/// appended to the user-supplied path so the on-disk layout is stable
/// across versions of aube and never collides with a pnpm store rooted
/// at the same path.
pub(crate) fn open_store(cwd: &std::path::Path) -> miette::Result<aube_store::Store> {
    with_settings_ctx(cwd, |ctx| open_store_with_ctx(cwd, ctx))
}

/// Open the content store using an already-resolved invocation context.
/// Embedded installs use this so their per-call overrides are not lost by a
/// second file/environment-only settings load.
pub(crate) fn open_store_with_ctx(
    cwd: &std::path::Path,
    ctx: &aube_settings::ResolveCtx<'_>,
) -> miette::Result<aube_store::Store> {
    let root = match resolved_store_dir_with_ctx(cwd, ctx) {
        Some(custom) => custom.join("v1").join("files"),
        None => aube_store::dirs::store_dir()
            .ok_or(aube_store::Error::NoHome)
            .into_diagnostic()
            .wrap_err("failed to open store")?,
    };
    Ok(
        aube_store::Store::with_dirs(root, resolved_cache_dir_with_ctx(cwd, ctx))
            .with_virtual_store_dir(global_virtual_store_dir_with_ctx(cwd, ctx)),
    )
}

/// Resolve the configured `storeDir` for `cwd`, returning `None` if
/// no override is set or the value can't be parsed. Walks `.npmrc`
/// and `pnpm-workspace.yaml` via `aube_settings::resolved::store_dir`,
/// then expands `~` and makes relative paths absolute against `cwd`.
/// The returned path is the user-facing store root *without* the
/// `v3/files` schema suffix — callers append it where needed (see
/// [`open_store`]).
pub(crate) fn resolved_store_dir(cwd: &std::path::Path) -> Option<std::path::PathBuf> {
    with_settings_ctx(cwd, |ctx| resolved_store_dir_with_ctx(cwd, ctx))
}

pub(crate) fn resolved_store_dir_with_ctx(
    cwd: &std::path::Path,
    ctx: &aube_settings::ResolveCtx<'_>,
) -> Option<std::path::PathBuf> {
    if let Some(path) = embedder_storage_path(cwd, |overrides| overrides.store_dir.as_ref()) {
        return Some(path);
    }
    let raw = aube_settings::resolved::store_dir(ctx)?;
    expand_setting_path(&raw, cwd)
}

/// Expand a path-typed setting value. `~` -> home dir, relative ->
/// absolute against `cwd`. Returns None if the value begins with `~`
/// but no home env var is set, caller then falls back to a platform
/// default. On Unix reads HOME. On Windows reads HOME first (for
/// POSIX-compat toolchains that set it) then USERPROFILE (native
/// Windows default). Old code only checked HOME, Windows users got
/// silent None back for any `~/...` settings like `storeDir: ~/store`,
/// and the caller fell through to the platform default, so custom
/// store paths never took effect on Windows.
pub(crate) fn expand_setting_path(raw: &str, cwd: &std::path::Path) -> Option<std::path::PathBuf> {
    let expanded = if let Some(rest) = raw.strip_prefix("~/") {
        std::path::PathBuf::from(home_dir_os()?).join(rest)
    } else if raw == "~" {
        std::path::PathBuf::from(home_dir_os()?)
    } else {
        std::path::PathBuf::from(raw)
    };
    Some(if expanded.is_absolute() {
        expanded
    } else {
        cwd.join(expanded)
    })
}

fn home_dir_os() -> Option<std::ffi::OsString> {
    aube_util::env::home_dir().map(|p| p.into_os_string())
}

/// Build a file-only `ResolveCtx` for `cwd` and call `f` with it.
/// Handles the temporary ownership of npmrc/workspace/env data so
/// callers don't need to import `yaml_serde`.
pub(crate) fn with_settings_ctx<T>(
    cwd: &std::path::Path,
    f: impl FnOnce(&aube_settings::ResolveCtx<'_>) -> T,
) -> T {
    with_settings_ctx_and_cli(cwd, &[], f)
}

pub(crate) fn with_settings_ctx_and_cli<T>(
    cwd: &std::path::Path,
    cli: &[(String, String)],
    f: impl FnOnce(&aube_settings::ResolveCtx<'_>) -> T,
) -> T {
    let files = FileSources::load(cwd);
    let raw_workspace = aube_manifest::workspace::load_raw(cwd).unwrap_or_default();
    // `process_env()` returns a `&'static` borrow of the once-captured
    // env. Avoids cloning ~200-500 String pairs every time a command
    // builds a ResolveCtx (the typical path hits this 5+ times per
    // `aube run`).
    let env = aube_settings::values::process_env();
    let ctx = files.ctx(&raw_workspace, env, cli);
    f(&ctx)
}

/// Build a registry client configured from .npmrc files in the project directory.
///
/// Also resolves the `fetch*` settings (timeout + retries + backoff)
/// from the full settings precedence chain and threads the resulting
/// [`aube_registry::config::FetchPolicy`] into
/// the client. The CLI bag comes from [`fetch_cli_overrides`], which
/// `async_main` populates from the global `--fetch-timeout`,
/// `--fetch-retries`, and `--fetch-retry-{factor,mintimeout,maxtimeout}`
/// flags before any command runs.
pub(crate) fn make_client(cwd: &std::path::Path) -> aube_registry::client::RegistryClient {
    let config = load_npm_config(cwd);
    tracing::debug!("registry: {}", config.registry);
    for (scope, url) in &config.scoped_registries {
        tracing::debug!("scoped registry: {scope} -> {url}");
    }
    let policy = resolve_fetch_policy(cwd);
    aube_registry::client::RegistryClient::from_config_with_policy(config, policy)
}

/// Run the pnpmfile `preResolution` hook before the resolver walks
/// the graph. Builds a context snapshot (lockfile dir, store dir,
/// existing lockfile, registry map) from the same sources the rest
/// of the install pipeline consumes, so install and update see an
/// identical hook contract. `paths` is the (`global`, `local`) order
/// produced by [`crate::pnpmfile::ordered_paths`]; passing the whole
/// slice keeps the global-first-then-local contract in one place
/// instead of duplicating it at every install/update call site.
pub(crate) async fn run_pnpmfile_pre_resolution(
    paths: &[std::path::PathBuf],
    cwd: &std::path::Path,
    existing: Option<&aube_lockfile::LockfileGraph>,
) -> miette::Result<()> {
    if paths.is_empty() {
        return Ok(());
    }
    let config = load_npm_config(cwd);
    let mut registries = std::collections::BTreeMap::new();
    registries.insert("default".to_string(), config.registry);
    for (scope, url) in config.scoped_registries {
        registries.insert(scope, url);
    }
    // Honor `storeDir` from `.npmrc` / `pnpm-workspace.yaml` so the
    // hook's `storeDir` field matches the path `open_store` operates
    // on. Both branches return the user-facing root (without the
    // `v1/files` CAS schema suffix) so a hook reading `storeDir`
    // doesn't see different depths depending on whether the user set
    // an override; the platform default's CAS path lives at
    // `<root>/v1/files`, so we strip those two segments.
    let store_dir = resolved_store_dir(cwd).or_else(|| {
        aube_store::dirs::store_dir()
            .and_then(|p| p.parent()?.parent().map(std::path::Path::to_path_buf))
    });
    let ctx = crate::pnpmfile::PreResolutionContext::from_existing(
        cwd,
        store_dir.as_deref(),
        existing,
        registries,
    );
    crate::pnpmfile::run_pre_resolution_chain(paths, cwd, &ctx)
        .await
        .wrap_err("pnpmfile preResolution hook failed")
}

/// Build the standard resolver used by add/remove/update/dedupe/audit.
/// Internally routes through install's `configure_resolver` so every
/// setting `aube install` plumbs — `supportedArchitectures`,
/// `resolutionMode`, `minimumReleaseAge`, `autoInstallPeers`,
/// `dedupePeerDependents`, overrides, `ignoredOptionalDependencies`,
/// peer suffix length, git shallow hosts, network concurrency — lands
/// here too. Skipping this caused `aube update` to rewrite the
/// lockfile against host-only `supportedArchitectures` (collapsing
/// platform-variant optional deps like `@biomejs/biome-*` /
/// `@rollup/rollup-linux-*`) and to drop `time:` entries for direct
/// deps reused from the lockfile (the resolver only records times
/// when `resolutionMode=time-based` / `minimumReleaseAge` is on /
/// `trustPolicy=no-downgrade`, and none of those were threaded
/// through here).
///
/// Reads `.npmrc` + workspace yaml once via `with_settings_ctx`,
/// detects the existing lockfile kind so the platform-widening
/// behaves identically to the install that wrote that lockfile, and
/// passes `minimum_release_age_override = None` since these commands
/// don't expose `--minimum-release-age` today.
pub(crate) fn build_resolver(
    cwd: &std::path::Path,
    manifest: &aube_manifest::PackageJson,
    catalogs: CatalogMap,
) -> aube_resolver::Resolver {
    let (ws_config, raw_workspace) = aube_manifest::workspace::load_both(cwd).unwrap_or_default();
    let files = FileSources::load(cwd);
    let env = aube_settings::values::process_env();
    let ctx = files.ctx(&raw_workspace, env, &[]);
    // `aube update` and friends always rewrite a lockfile, so pick a
    // target kind. Detect the existing format to match install's
    // cross-platform widening rules — native package-manager lockfiles
    // that record per-package platform metadata keep optional natives for
    // every platform, while formats without that metadata stay host-only.
    let target_lockfile_kind = Some(
        aube_lockfile::detect_existing_lockfile_kind(cwd)
            .unwrap_or(aube_lockfile::LockfileKind::Aube),
    );
    install::configure_resolver(
        aube_resolver::Resolver::new(std::sync::Arc::new(make_client(cwd))),
        cwd,
        manifest,
        install::ResolverConfigInputs {
            settings_ctx: &ctx,
            workspace_config: &ws_config,
            workspace_catalogs: &catalogs,
            minimum_release_age_override: None,
            target_lockfile_kind,
            dependency_policy: None,
            // Update / add / dedupe / audit deliberately skip the
            // full-packument disk cache install populates: the cache's
            // freshness window can outlive a registry dist-tag bump,
            // and these commands need to observe `latest` exactly as
            // it stands right now (pnpm_update.bats simulates this by
            // mutating `dist-tags` between commands). The abbreviated
            // cache stays on either way.
            cache_full_packuments: false,
            ignore_scripts: false,
        },
        None,
    )
}

/// Resolve [`aube_registry::config::FetchPolicy`] from the same
/// sources the rest of the CLI consumes settings from. Kept separate
/// from [`make_client`] so tests and ad-hoc callers (publish,
/// deprecate, etc) can opt in without duplicating the ctx-building
/// boilerplate.
pub(crate) fn resolve_fetch_policy(cwd: &std::path::Path) -> aube_registry::config::FetchPolicy {
    let files = FileSources::load(cwd);
    let workspace_yaml = aube_manifest::workspace::load_both(cwd)
        .map(|(_, raw)| raw)
        .unwrap_or_default();
    let env = aube_settings::values::process_env();
    let ctx = files.ctx(&workspace_yaml, env, fetch_cli_overrides());
    aube_registry::config::FetchPolicy::from_ctx(&ctx)
}

/// Resolve the `cacheDir` setting for `cwd`. When set (via
/// `AUBE_CACHE_DIR` / `npm_config_cache_dir`, or `cache-dir` in
/// `.npmrc` / `aube-config.toml`), expands it and returns that path.
/// Otherwise falls back to the platform cache dir:
/// `$XDG_CACHE_HOME/aube` when `XDG_CACHE_HOME` is set,
/// `%LOCALAPPDATA%\aube` on Windows, else `~/.cache/aube`.
///
/// `cacheDir` has no default baked into the generated accessor (see the
/// exclusion list in `aube-settings/build.rs`) precisely so this
/// function can tell "not configured" from "configured to the literal
/// default path": every platform fallback above is a *base* directory
/// that aube appends its own name to, so routing them through the
/// settings accessor would lose the subdirectory.
///
/// The packument caches and — unless [`global_virtual_store_dir`]
/// overrides it — the global virtual store hang off this path, so a
/// user who moves the cache to another volume moves them together.
pub(crate) fn resolved_cache_dir(cwd: &std::path::Path) -> std::path::PathBuf {
    with_settings_ctx(cwd, |ctx| resolved_cache_dir_with_ctx(cwd, ctx))
}

pub(crate) fn resolved_cache_dir_with_ctx(
    cwd: &std::path::Path,
    ctx: &aube_settings::ResolveCtx<'_>,
) -> std::path::PathBuf {
    if let Some(path) = embedder_storage_path(cwd, |overrides| overrides.cache_dir.as_ref()) {
        return path;
    }
    let platform_default =
        || aube_store::dirs::cache_dir().unwrap_or_else(|| std::env::temp_dir().join("aube"));
    match aube_settings::resolved::cache_dir(ctx) {
        Some(raw) => expand_setting_path(&raw, cwd).unwrap_or_else(platform_default),
        None => platform_default(),
    }
}

/// Absolute path of the global virtual store — the shared tree of
/// materialized packages that project `node_modules/.aube/<dep_path>`
/// entries symlink into.
///
/// `globalVirtualStoreDir` wins when set and is used verbatim (no
/// `virtual-store` suffix); otherwise the store lands under the
/// resolved [`resolved_cache_dir`]. The dedicated setting exists
/// because this tree — unlike the rest of the cache — has to sit on
/// the same volume as `storeDir` to be hardlinkable, which is not
/// necessarily where the packument caches belong.
///
/// Every read-side caller (layout detection, mode-change reset) must
/// resolve it the same way the install write path does, otherwise a
/// relocated store makes them look at an empty directory and silently
/// re-materialize.
pub(crate) fn global_virtual_store_dir(cwd: &std::path::Path) -> std::path::PathBuf {
    with_settings_ctx(cwd, |ctx| global_virtual_store_dir_with_ctx(cwd, ctx))
}

pub(crate) fn global_virtual_store_dir_with_ctx(
    cwd: &std::path::Path,
    ctx: &aube_settings::ResolveCtx<'_>,
) -> std::path::PathBuf {
    aube_settings::resolved::global_virtual_store_dir(ctx)
        .and_then(|raw| expand_setting_path(&raw, cwd))
        .unwrap_or_else(|| {
            resolved_cache_dir_with_ctx(cwd, ctx).join(aube_store::VIRTUAL_STORE_SUBDIR)
        })
}

/// Resolve the `virtualStoreDirMaxLength` setting, falling back to the
/// platform default (`DEFAULT_VIRTUAL_STORE_DIR_MAX_LENGTH`, which is
/// 120 on Linux/macOS and will become 60 on Windows once Windows
/// support lands). Every call site that encodes `dep_path`s into
/// `.aube/<name>` filenames — install, list, why, patch, rebuild,
/// engines check — must resolve the same cap, otherwise the long-path
/// truncate-and-hash branch of `dep_path_to_filename` produces
/// different filenames for read-side and write-side callers and
/// silently misses packages.
pub(crate) fn resolve_virtual_store_dir_max_length(ctx: &aube_settings::ResolveCtx<'_>) -> usize {
    aube_settings::resolved::virtual_store_dir_max_length(ctx)
        .map(|v| v as usize)
        .unwrap_or(aube_lockfile::dep_path_filename::DEFAULT_VIRTUAL_STORE_DIR_MAX_LENGTH)
}

/// Load `.npmrc` + `pnpm-workspace.yaml` for `cwd` and resolve the
/// effective `virtualStoreDirMaxLength` in one call. Convenience for
/// post-install commands (list, why, patch) that don't build a
/// `ResolveCtx` for any other reason.
pub(crate) fn resolve_virtual_store_dir_max_length_for_cwd(cwd: &std::path::Path) -> usize {
    with_settings_ctx(cwd, resolve_virtual_store_dir_max_length)
}

/// Project-level `node_modules` directory name (pnpm's `modulesDir`
/// setting). Defaults to `"node_modules"` — users who change it are
/// responsible for setting `NODE_PATH` themselves since Node's own
/// resolver still looks for a literal `node_modules/`.
///
/// Every command that touches the top-level project directory (bin,
/// root, prune, clean, link, unlink, run, exec, etc.) reads this so
/// it lands on the same path the install wrote to. Commands that
/// already build a `ResolveCtx` for other settings should call
/// `aube_settings::resolved::modules_dir(&ctx)` directly instead of
/// this shortcut.
pub(crate) fn resolve_modules_dir_name_for_cwd(cwd: &std::path::Path) -> String {
    with_settings_ctx(cwd, aube_settings::resolved::modules_dir)
}

/// Convenience: `<cwd>/<modulesDir>` as a `PathBuf`. Matches the
/// `project_dir.join("node_modules")` pattern that every command used
/// before `modulesDir` was wired; prefer this over the raw literal
/// so a workspace-level override flows through automatically.
pub(crate) fn project_modules_dir(cwd: &std::path::Path) -> std::path::PathBuf {
    cwd.join(resolve_modules_dir_name_for_cwd(cwd))
}

/// Resolve the absolute path of the per-project virtual store
/// (pnpm's `virtualStoreDir`). When the user explicitly sets the value
/// in `.npmrc`, `pnpm-workspace.yaml`, or the environment, expand it
/// (relative paths resolve against `project_dir`, `~` expands to
/// `$HOME`) and return it. Otherwise derive from `modulesDir`:
/// `<project_dir>/<modulesDir>/.aube`. This matches pnpm, where the
/// documented default is `<modulesDir>/.pnpm` — a user who overrides
/// `modulesDir` alone keeps a coherent layout without having to set
/// both.
///
/// Every site that touches `.aube/<dep_path>/` — linker, install state
/// sidecar, `patch`, `rebuild`, `list --long`, `why`, `prune`, `clean`,
/// etc. — must resolve through this helper so a workspace-level
/// override lands at the same path the install wrote to.
pub(crate) fn resolve_virtual_store_dir(
    ctx: &aube_settings::ResolveCtx<'_>,
    project_dir: &std::path::Path,
) -> std::path::PathBuf {
    let default_from_modules_dir = || {
        let modules_dir = aube_settings::resolved::modules_dir(ctx);
        // Virtual-store leaf from the active embedder's name: `.<name>`.
        // Standalone aube → `.aube`.
        let leaf = format!(".{}", aube_util::embedder().name);
        project_dir.join(modules_dir).join(leaf)
    };
    let has_explicit_npmrc = [
        ctx.project_aube_config,
        ctx.project_npmrc,
        ctx.user_aube_config,
        ctx.user_npmrc,
    ]
    .iter()
    .any(|entries| {
        entries
            .iter()
            .any(|(k, _)| k == "virtualStoreDir" || k == "virtual-store-dir")
    });
    let has_explicit_yaml = ctx.workspace_yaml.contains_key("virtualStoreDir");
    // Mirrors the `sources.env` list in settings.toml (`virtualStoreDir`).
    // Keep all three aliases here — dropping `AUBE_VIRTUAL_STORE_DIR`
    // silently routes through the default branch even though
    // `aube_settings::resolved::virtual_store_dir` honors the env value.
    let has_explicit_env = ctx.env.iter().any(|(k, _)| {
        k == "npm_config_virtual_store_dir"
            || k == "NPM_CONFIG_VIRTUAL_STORE_DIR"
            || k == "AUBE_VIRTUAL_STORE_DIR"
    });
    if !(has_explicit_npmrc || has_explicit_yaml || has_explicit_env) {
        return default_from_modules_dir();
    }
    let raw = aube_settings::resolved::virtual_store_dir(ctx);
    expand_setting_path(&raw, project_dir).unwrap_or_else(default_from_modules_dir)
}

/// Load `.npmrc` + `pnpm-workspace.yaml` for `cwd` and resolve the
/// effective virtual-store path in one call. Convenience for
/// post-install commands (`patch`, `list --long`, `why`, `clean`,
/// `unlink`) that don't build a `ResolveCtx` for any other reason.
pub(crate) fn resolve_virtual_store_dir_for_cwd(cwd: &std::path::Path) -> std::path::PathBuf {
    with_settings_ctx(cwd, |ctx| resolve_virtual_store_dir(ctx, cwd))
}

/// Disk cache directory for packument metadata. Falls back to a tmp dir if
/// the user cache dir can't be resolved (rare).
pub(crate) fn packument_cache_dir() -> std::path::PathBuf {
    let cwd = crate::dirs::cwd().unwrap_or_else(|_| std::env::current_dir().unwrap_or_default());
    packument_cache_dir_for_cwd(&cwd)
}

/// Disk cache directory for packument metadata resolved against an explicit
/// project directory. Embedders must use this form instead of logical cwd.
pub(crate) fn packument_cache_dir_for_cwd(cwd: &std::path::Path) -> std::path::PathBuf {
    resolved_cache_dir(cwd).join("packuments-v1")
}

/// Disk cache directory for *full* (non-corgi) packument JSON used by
/// human-facing commands like `aube view`. Separate from the corgi cache
/// because the shapes differ.
pub(crate) fn packument_full_cache_dir() -> std::path::PathBuf {
    let cwd = crate::dirs::cwd().unwrap_or_else(|_| std::env::current_dir().unwrap_or_default());
    resolved_cache_dir(&cwd).join("packuments-full-v1")
}

/// [`packument_full_cache_dir`] against an explicit project dir instead of
/// the process-global logical cwd — for embed-safe paths like
/// `add_to_project`, which must not consult the host process's cwd.
pub(crate) fn packument_full_cache_dir_for_cwd(cwd: &std::path::Path) -> std::path::PathBuf {
    resolved_cache_dir(cwd).join("packuments-full-v1")
}

#[cfg(test)]
mod resolve_virtual_store_dir_tests {
    use super::resolve_virtual_store_dir;
    use aube_settings::ResolveCtx;
    use std::collections::BTreeMap;
    use std::path::PathBuf;

    fn ctx_with_env<'a>(
        env: &'a [(String, String)],
        ws: &'a BTreeMap<String, yaml_serde::Value>,
    ) -> ResolveCtx<'a> {
        ResolveCtx {
            managed_aube_config: &[],
            project_aube_config: &[],
            project_npmrc: &[],
            user_aube_config: &[],
            user_npmrc: &[],
            workspace_yaml: ws,
            env,
            cli: &[],
            embedder_defaults: &[],
        }
    }

    #[test]
    fn default_when_no_explicit_override() {
        let env = vec![];
        let ws = BTreeMap::new();
        let ctx = ctx_with_env(&env, &ws);
        let project = PathBuf::from("/proj");
        assert_eq!(
            resolve_virtual_store_dir(&ctx, &project),
            PathBuf::from("/proj/node_modules/.aube"),
        );
    }

    #[test]
    fn aube_env_var_relocates_virtual_store() {
        // Regression guard: AUBE_VIRTUAL_STORE_DIR is declared in
        // settings.toml's `sources.env` for `virtualStoreDir`. Without
        // it in the explicit-detection list, a user setting only
        // AUBE_VIRTUAL_STORE_DIR (and not the npm_config_* aliases)
        // would silently fall through to the default path.
        let env = vec![("AUBE_VIRTUAL_STORE_DIR".into(), ".aube".into())];
        let ws = BTreeMap::new();
        let ctx = ctx_with_env(&env, &ws);
        let project = PathBuf::from("/proj");
        assert_eq!(
            resolve_virtual_store_dir(&ctx, &project),
            PathBuf::from("/proj/.aube"),
        );
    }

    #[test]
    fn npm_config_env_var_relocates_virtual_store() {
        let env = vec![("npm_config_virtual_store_dir".into(), ".vstore".into())];
        let ws = BTreeMap::new();
        let ctx = ctx_with_env(&env, &ws);
        let project = PathBuf::from("/proj");
        assert_eq!(
            resolve_virtual_store_dir(&ctx, &project),
            PathBuf::from("/proj/.vstore"),
        );
    }
}

#[cfg(test)]
mod package_manager_mismatch_tests {
    use super::skip_auto_install_on_package_manager_mismatch;

    #[test]
    fn skip_auto_install_defaults_off() {
        assert!(!skip_auto_install_on_package_manager_mismatch());
    }
}