diff --git a/crates/aube-lockfile/src/npm/layout.rs b/crates/aube-lockfile/src/npm/layout.rs index 1394b3976..721bf9c49 100644 --- a/crates/aube-lockfile/src/npm/layout.rs +++ b/crates/aube-lockfile/src/npm/layout.rs @@ -229,28 +229,15 @@ fn ancestor_resolution( AncestorHit::Miss } -/// Strip any `(peer@ver)` suffix from a dep_path tail, returning just -/// the version. Input `"18.2.0(prop-types@15.8.1)"` → `"18.2.0"`. +/// Strip any peer-context suffix from a dep_path tail, returning just +/// the version. Both the normal `(peer@ver)…` form and the capped +/// `()` form (pnpm's `createPeerDepGraphHash`) begin at the +/// first `(`, so cutting there handles either. Input +/// `"18.2.0(prop-types@15.8.1)"` → `"18.2.0"`. fn version_from_tail(tail: &str) -> &str { tail.split_once('(').map(|(v, _)| v).unwrap_or(tail) } -fn strip_hashed_peer_suffix(s: &str) -> &str { - const MARKER_LEN: usize = 11; // `_` + 10 hex chars - if s.len() < MARKER_LEN { - return s; - } - let tail = &s[s.len() - MARKER_LEN..]; - if !tail.starts_with('_') { - return s; - } - if tail[1..].chars().all(|c| c.is_ascii_hexdigit()) { - &s[..s.len() - MARKER_LEN] - } else { - s - } -} - /// Compute the canonical `name@version` key for a child declared in /// [`LockedPackage::dependencies`]. Tolerates both encodings seen in /// practice: the documented "tail only" form (`"1.0.0"`) used by @@ -258,7 +245,7 @@ fn strip_hashed_peer_suffix(s: &str) -> &str { /// currently emitted by [`parse`] above. Peer context suffixes are /// stripped in both branches. pub(crate) fn child_canonical_key(child_name: &str, value: &str) -> String { - let no_peer = strip_hashed_peer_suffix(version_from_tail(value)); + let no_peer = version_from_tail(value); let prefix = format!("{child_name}@"); if no_peer.starts_with(&prefix) { no_peer.to_string() @@ -271,7 +258,7 @@ pub(crate) fn child_canonical_key(child_name: &str, value: &str) -> String { /// of which encoding it was stored in. Used when writing out the /// `dependencies` field of a nested package entry. pub(crate) fn dep_value_as_version<'a>(child_name: &str, value: &'a str) -> &'a str { - let no_peer = strip_hashed_peer_suffix(version_from_tail(value)); + let no_peer = version_from_tail(value); let prefix = format!("{child_name}@"); if let Some(rest) = no_peer.strip_prefix(&prefix) { rest @@ -288,7 +275,7 @@ pub(crate) fn dep_value_as_version<'a>(child_name: &str, value: &'a str) -> &'a /// then miss the canonical map and silently drop the package from /// the written lockfile). pub(crate) fn canonical_key_from_dep_path(dep_path: &str) -> String { - let trimmed = strip_hashed_peer_suffix(version_from_tail(dep_path)); + let trimmed = version_from_tail(dep_path); let (name, version) = match trimmed.rfind('@') { Some(0) | None => return trimmed.to_string(), Some(idx) => (&trimmed[..idx], &trimmed[idx + 1..]), diff --git a/crates/aube-lockfile/src/npm/tests.rs b/crates/aube-lockfile/src/npm/tests.rs index e3f24de32..b02aa9376 100644 --- a/crates/aube-lockfile/src/npm/tests.rs +++ b/crates/aube-lockfile/src/npm/tests.rs @@ -823,12 +823,12 @@ fn test_write_npm_preserves_platform_optional_metadata() { } /// Regression: `canonical_key_from_dep_path` must strip the -/// `(peer@ver)` suffix *before* splitting on `@`. A naive +/// peer-context suffix *before* splitting on `@`. A naive /// `rfind('@')` lands inside the peer suffix and returns the /// input unchanged, which silently drops every peer-contextualized -/// root dep from the written lockfile. Hashed suffixes use the -/// same canonical identity; otherwise long peer suffixes drop -/// out of npm package-lock output. +/// root dep from the written lockfile. The capped hash form +/// `()` shares the same canonical identity and is +/// stripped the same way — it also begins at the first `(`. #[test] fn test_canonical_key_strips_peer_suffix() { assert_eq!(canonical_key_from_dep_path("foo@1.0.0"), "foo@1.0.0"); @@ -840,22 +840,21 @@ fn test_canonical_key_strips_peer_suffix() { canonical_key_from_dep_path("@scope/pkg@2.0.0(peer@1.0.0)"), "@scope/pkg@2.0.0" ); + // Capped suffix: a single parenthesized short hash (pnpm's + // `createPeerDepGraphHash`), stripped like any other `(…)` tail. + let hashed = "expo-router@4.0.22(94c00fd028a1b2c3d4e5f60718293a4b)"; + assert_eq!(canonical_key_from_dep_path(hashed), "expo-router@4.0.22"); assert_eq!( - canonical_key_from_dep_path("expo-router@4.0.22_94c00fd028"), + child_canonical_key("expo-router", "4.0.22(94c00fd028a1b2c3d4e5f60718293a4b)"), "expo-router@4.0.22" ); assert_eq!( - child_canonical_key("expo-router", "4.0.22_94c00fd028"), - "expo-router@4.0.22" - ); - assert_eq!( - dep_value_as_version("expo-router", "expo-router@4.0.22_94c00fd028"), + dep_value_as_version( + "expo-router", + "expo-router@4.0.22(94c00fd028a1b2c3d4e5f60718293a4b)" + ), "4.0.22" ); - assert_eq!( - canonical_key_from_dep_path("expo-router@4.0.22_94C00FD028"), - "expo-router@4.0.22" - ); } fn test_manifest() -> aube_manifest::PackageJson { diff --git a/crates/aube-resolver/src/builder.rs b/crates/aube-resolver/src/builder.rs index 60256bd2a..1acda5fb9 100644 --- a/crates/aube-resolver/src/builder.rs +++ b/crates/aube-resolver/src/builder.rs @@ -157,9 +157,11 @@ impl Resolver { self } - /// Configure pnpm's `peersSuffixMaxLength`. When the peer suffix on a - /// `dep_path` would exceed this many bytes, the post-pass replaces it - /// with `_<10-char-sha256-hex>`. Default 1000 (pnpm's default). + /// Configure pnpm's `peersSuffixMaxLength`. When the peer suffix body + /// on a `dep_path` would exceed this many bytes, the post-pass + /// replaces the whole suffix with a parenthesized short hash + /// `()` (pnpm's `createPeerDepGraphHash`). Default 1000 + /// (pnpm's default). pub fn with_peers_suffix_max_length(mut self, max_length: usize) -> Self { self.peers_suffix_max_length = max_length; self diff --git a/crates/aube-resolver/src/lib.rs b/crates/aube-resolver/src/lib.rs index 3a4d55f44..557fdfb05 100644 --- a/crates/aube-resolver/src/lib.rs +++ b/crates/aube-resolver/src/lib.rs @@ -62,7 +62,7 @@ use package_ext::{apply_package_extensions, package_selector_matches, pick_overr #[cfg(test)] use peer_context::{ apply_dedupe_peers_to_key, contains_canonical_back_ref, dedupe_peer_suffixes, - dedupe_peer_variants, hash_peer_suffix, + dedupe_peer_variants, effective_peer_suffix, is_hashed_peer_suffix, }; #[cfg(test)] use semver_util::{PickResult, pick_version, strip_alias_prefix}; @@ -177,11 +177,12 @@ pub struct Resolver { /// explicitly if they want the pnpm list; keeping the list in /// one place (`settings.toml`) avoids drift. git_shallow_hosts: Vec, - /// pnpm's `peersSuffixMaxLength`. When the peer-ID suffix on a - /// `dep_path` (the `(name@version)(…)` portion) would exceed this - /// many bytes, the post-pass replaces the whole suffix with - /// `_` where `` is the first 10 chars of SHA-256 of the - /// full suffix. Matches pnpm's lockfile format. Default 1000. + /// pnpm's `peersSuffixMaxLength`. When the peer-ID suffix body on a + /// `dep_path` (the `(name@version)(…)` portion without its outer + /// parens) would exceed this many bytes, the post-pass replaces the + /// whole suffix with a parenthesized short hash `()` — + /// the first 32 chars of SHA-256 of the body, matching pnpm's + /// `createPeerDepGraphHash` lockfile format. Default 1000. peers_suffix_max_length: usize, /// pnpm's `dedupe-peer-dependents`. When true (pnpm's default), /// the peer-context post-pass collapses multiple dep_path variants diff --git a/crates/aube-resolver/src/peer_context.rs b/crates/aube-resolver/src/peer_context.rs index ed737a25a..c12ea970d 100644 --- a/crates/aube-resolver/src/peer_context.rs +++ b/crates/aube-resolver/src/peer_context.rs @@ -290,8 +290,9 @@ pub struct PeerContextOptions { /// module for the owning implementation (intentionally crate- /// private; the public API here is the option flag itself). pub resolve_from_workspace_root: bool, - /// Byte cap on the peer-ID suffix after which the entire suffix - /// is hashed to `_<10-char-sha256-hex>`. pnpm's default is 1000. + /// Byte cap on the peer-ID suffix body after which the entire + /// suffix is replaced by a parenthesized short hash `()` + /// (pnpm's `createPeerDepGraphHash`). pnpm's default is 1000. pub peers_suffix_max_length: usize, } @@ -739,14 +740,6 @@ fn apply_peer_contexts_once( /// `(` / `)` / end-of-string)? Used by the peer-context pass to detect /// when a nested tail loops back to the current package so it can /// short-circuit the chain instead of growing the suffix forever. -/// If `s` ends with `_<10 lowercase hex>` (the marker written by -/// `hash_peer_suffix`), strip it and return the prefix. Otherwise -/// return `s` unchanged. -/// -/// Safe against false positives: `s` here is always a post-split -/// `name@version` base, and semver forbids `_` inside a version, so -/// an underscore 10 chars from the end of `name@version` can only be -/// our marker. /// Everything before the first `(` — i.e. the canonical `name@version` /// part of a dep-path with the peer-context suffix stripped. Returns /// the original string when no `(` is present. Borrowed; callers that @@ -777,41 +770,60 @@ fn scope_map_from_deps(deps: &[DirectDep]) -> FxHashMap { out } -fn strip_hashed_peer_suffix(s: &str) -> &str { - const MARKER_LEN: usize = 11; // `_` + 10 hex chars - if s.len() < MARKER_LEN { - return s; - } - let tail = &s[s.len() - MARKER_LEN..]; - if !tail.starts_with('_') { - return s; - } - if tail[1..] - .chars() - .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)) - { - &s[..s.len() - MARKER_LEN] - } else { - s - } +/// True when `s` is a single hashed peer suffix `(<32 lowercase hex>)` +/// as emitted by [`effective_peer_suffix`] once a suffix exceeds +/// `peersSuffixMaxLength`. The hashed form discards the textual peer +/// set, so the propagation pass recognizes such keys and leaves them +/// untouched (their per-peer contribution can't be recovered). A real +/// peer segment always contains `@`, so the all-hex check can't +/// false-positive on a `(name@version)` group. +pub(crate) fn is_hashed_peer_suffix(s: &str) -> bool { + let Some(inner) = s.strip_prefix('(').and_then(|x| x.strip_suffix(')')) else { + return false; + }; + inner.len() == 32 + && inner + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) } -/// Hash a peer-ID suffix with SHA-256 and return `_<10-char-hex>`. -/// Used by the peer-context pass when the raw suffix length exceeds -/// `peersSuffixMaxLength`. Matches pnpm's format so lockfile dep_path -/// keys stay portable. -pub(crate) fn hash_peer_suffix(suffix: &str) -> String { +/// pnpm's `createShortHash`: the lowercase SHA-256 hex digest of +/// `input`, truncated to its first 32 characters (16 bytes). +fn short_peer_hash(input: &str) -> String { use sha2::{Digest, Sha256}; - let digest = Sha256::digest(suffix.as_bytes()); - let mut out = String::with_capacity(11); - out.push('_'); - for byte in digest.iter().take(5) { + let digest = Sha256::digest(input.as_bytes()); + let mut out = String::with_capacity(32); + for byte in digest.iter().take(16) { use std::fmt::Write; let _ = write!(out, "{byte:02x}"); } out } +/// Final peer-context tail for an already-built `(name@version)…` +/// `suffix`, mirroring pnpm's `createPeerDepGraphHash`. pnpm derives +/// `dirName` by joining the sorted peer ids with `)(` — i.e. the suffix +/// without its outer parens — hashes it with `createShortHash` when it +/// exceeds `peersSuffixMaxLength`, and always re-wraps the result in a +/// single `(...)`. Keeping that shape means a capped suffix aube writes +/// into `pnpm-lock.yaml` is `()` — byte-compatible with +/// pnpm — never a bare `_` marker. +pub(crate) fn effective_peer_suffix(suffix: &str, max_length: usize) -> String { + // `dir_name` == pnpm's `dirName`: the suffix without the outer `(` + // and `)` that wrap the first and last peer segment. `suffix` is + // always a concatenation of `(…)` groups here, so stripping one + // byte off each end is safe; an empty suffix degrades to empty. + let dir_name = suffix + .strip_prefix('(') + .and_then(|s| s.strip_suffix(')')) + .unwrap_or(suffix); + if dir_name.len() > max_length { + format!("({})", short_peer_hash(dir_name)) + } else { + suffix.to_string() + } +} + pub(crate) fn contains_canonical_back_ref(value: &str, canonical: &str) -> bool { let bytes = value.as_bytes(); let target = canonical.as_bytes(); @@ -1122,7 +1134,7 @@ fn propagate_peer_suffixes_to_ancestors( // cumulative is identical to its self set the rewrite is a no-op // and we skip it. // - // Hashed-suffix keys (`name@version_<10hex>`, produced when a + // Hashed-suffix keys (`name@version()`, produced when a // package's own peer suffix exceeded `peersSuffixMaxLength`) are // left untouched. The hash form discards the textual peer set // by design — `outer_paren_segments` can't recover its @@ -1140,19 +1152,15 @@ fn propagate_peer_suffixes_to_ancestors( let Some(segments) = cumulative.get(key) else { continue; }; - let original_tail = canonical_tail(key); - let canonical = strip_hashed_peer_suffix(original_tail); - if canonical.len() != original_tail.len() { - // Original key already has the hashed marker. Skip — see - // comment above. + let canonical = canonical_tail(key); + if is_hashed_peer_suffix(&key[canonical.len()..]) { + // Original key already carries the hashed suffix `(…)` — see + // comment above. Its textual peer set is irrecoverable, so + // leave the key untouched. continue; } let suffix: String = segments.values().cloned().collect(); - let effective_suffix = if suffix.len() > options.peers_suffix_max_length { - hash_peer_suffix(&suffix) - } else { - suffix - }; + let effective_suffix = effective_peer_suffix(&suffix, options.peers_suffix_max_length); let new_key = format!("{canonical}{effective_suffix}"); if new_key != *key { rewrite.insert(key.clone(), new_key); @@ -1486,16 +1494,13 @@ fn visit_peer_context<'g>( // append the new suffix on top of the old and grow unboundedly // across iterations (classic mutual-peer-cycle blow-up). // - // Two suffix forms can be present from a prior pass: - // 1. `(name@version)(…)` — the normal nested peer suffix. Stripped - // by splitting on the first `(`. - // 2. `_<10-char-sha256-hex>` — the hashed form produced when the - // normal suffix exceeded `peersSuffixMaxLength`. Must also be - // stripped; otherwise each pass re-hashes the already-hashed - // key and appends another marker (exposed by the - // `peer_suffix_is_hashed_when_exceeding_cap` unit test). - let canonical_base = canonical_tail(input_dep_path); - let canonical_base = strip_hashed_peer_suffix(canonical_base).to_string(); + // Both suffix forms are parenthesized — the normal nested + // `(name@version)(…)` and the capped `()` that + // `effective_peer_suffix` emits past `peersSuffixMaxLength` — so + // splitting on the first `(` strips either one. Otherwise each + // pass would re-hash the already-hashed key and grow it (covered + // by the `peer_suffix_is_hashed_when_exceeding_cap` unit test). + let canonical_base = canonical_tail(input_dep_path).to_string(); // Compute peer context: walk declared peers, resolve from ancestors // (nearest wins — the scope is rebuilt as we recurse) or from the @@ -1656,15 +1661,11 @@ fn visit_peer_context<'g>( format!("({n}@{display_v})") }) .collect(); - // pnpm's `peersSuffixMaxLength`: when the built suffix exceeds the - // cap, replace the entire suffix with `_<10-char-sha256-hex>` so the - // lockfile key stays bounded. Matches pnpm's lockfile format, so - // lockfiles shared between aube and pnpm stay comparable. - let effective_suffix = if suffix.len() > options.peers_suffix_max_length { - hash_peer_suffix(&suffix) - } else { - suffix - }; + // pnpm's `peersSuffixMaxLength`: when the suffix body exceeds the + // cap, `effective_peer_suffix` replaces the whole suffix with a + // parenthesized short hash `()` so the lockfile key stays + // bounded and byte-compatible with pnpm's `createPeerDepGraphHash`. + let effective_suffix = effective_peer_suffix(&suffix, options.peers_suffix_max_length); let contextualized = format!("{canonical_base}{effective_suffix}"); if out_packages.contains_key(&contextualized) || visiting.contains(&contextualized) { diff --git a/crates/aube-resolver/src/tests.rs b/crates/aube-resolver/src/tests.rs index 32017e4b4..a09a4985e 100644 --- a/crates/aube-resolver/src/tests.rs +++ b/crates/aube-resolver/src/tests.rs @@ -3015,27 +3015,48 @@ async fn lockfile_reuse_handles_name_at_version_dep_form() { // ===== peersSuffixMaxLength ===== // -// Helpers exercised directly: `hash_peer_suffix` for the format -// invariant; `apply_peer_contexts` for the integration path that -// reads the cap and decides whether to swap the suffix. +// Helpers exercised directly: `effective_peer_suffix` for the pnpm +// format invariant; `apply_peer_contexts` for the integration path +// that reads the cap and decides whether to swap the suffix. #[test] -fn hash_peer_suffix_matches_expected_format() { - let out = hash_peer_suffix("(react@18.2.0)"); - // `_` prefix, 10 hex chars, nothing else. - assert!(out.starts_with('_'), "expected `_` prefix: {out:?}"); - assert_eq!(out.len(), 11, "expected `_` + 10 hex chars: {out:?}"); +fn effective_peer_suffix_hashes_to_pnpm_parenthesized_form() { + // Cap of 0 forces hashing of any non-empty body. pnpm's + // `createPeerDepGraphHash` wraps the short hash in a single + // `(...)`, never a bare `_` marker. + let out = effective_peer_suffix("(react@18.2.0)", 0); assert!( - out[1..] + out.starts_with('(') && out.ends_with(')'), + "parens: {out:?}" + ); + let inner = &out[1..out.len() - 1]; + // `createShortHash` = sha256 hex truncated to 32 chars. + assert_eq!(inner.len(), 32, "expected 32 hex chars: {out:?}"); + assert!( + inner .chars() .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()), - "expected lowercase hex after `_`: {out:?}" + "expected lowercase hex inside parens: {out:?}" + ); + // The hash input is the body (suffix without the outer parens), + // matching pnpm's `dirName = peers.join(')(')`. + assert_eq!( + out, + effective_peer_suffix("(react@18.2.0)", 0), + "stable output" ); - // Stable output — regression guard against accidental format changes. - assert_eq!(hash_peer_suffix("(react@18.2.0)"), out); + assert!(is_hashed_peer_suffix(&out), "must be recognized as hashed"); +} + +#[test] +fn effective_peer_suffix_is_identity_within_cap() { + // Within the cap the suffix is returned verbatim (the common case). + let suffix = "(react@18.2.0)(redux@4.0.5)"; + assert_eq!(effective_peer_suffix(suffix, 1000), suffix); + assert!(!is_hashed_peer_suffix(suffix), "real peers aren't hashed"); } -// Small cap forces the suffix to collapse to `_`. Uses the +// Small cap forces the suffix to collapse to `()`. Uses the // nested-peer fixture that already proves correct behavior at the // default cap — same fixture, different cap, different output. #[test] @@ -3091,8 +3112,8 @@ fn peer_suffix_is_hashed_when_exceeding_cap() { .expect("consumer@1.0.0 variant missing"); let suffix = consumer_key.strip_prefix("consumer@1.0.0").unwrap(); assert!( - suffix.starts_with('_') && suffix.len() == 11, - "expected hashed suffix _<10-hex>, got {suffix:?} from {consumer_key:?}" + is_hashed_peer_suffix(suffix), + "expected parenthesized hashed suffix (<32-hex>), got {suffix:?} from {consumer_key:?}" ); } diff --git a/crates/aube-settings/settings.toml b/crates/aube-settings/settings.toml index 89b91e35b..097f65821 100644 --- a/crates/aube-settings/settings.toml +++ b/crates/aube-settings/settings.toml @@ -1523,10 +1523,11 @@ type = "int" default = "1000" docs = """ Caps the length of the peer-ID suffix appended to a `dep_path` in the -lockfile (e.g. `react-dom@18.2.0(react@18.2.0)`). When the suffix would -exceed this many bytes, aube replaces it with `_` where `` is -a short SHA-256 digest of the full suffix — matching pnpm's format so -lockfiles stay portable. +lockfile (e.g. `react-dom@18.2.0(react@18.2.0)`). When the suffix body +would exceed this many bytes, aube replaces the whole suffix with a +parenthesized short hash `()` — the first 32 chars of the +SHA-256 of the suffix body — matching pnpm's `createPeerDepGraphHash` +so lockfiles stay portable. Mutual-peer cycles in large graphs can otherwise grow suffixes unboundedly across fixed-point iterations of the resolver. The default diff --git a/crates/aube/src/commands/install/fetch.rs b/crates/aube/src/commands/install/fetch.rs index 806526169..8f7420cbb 100644 --- a/crates/aube/src/commands/install/fetch.rs +++ b/crates/aube/src/commands/install/fetch.rs @@ -1062,8 +1062,25 @@ pub(super) fn remap_indices_to_contextualized( let mut out = BTreeMap::new(); for (dep_path, pkg) in &graph.packages { let canonical_key = pkg.spec_key(); + // The peer-context pass appends a `(peer@ver)` suffix (or a + // parenthesized `()` when it exceeds the cap) onto a + // package's canonical dep_path. Source-backed deps (git / + // remote tarball / file) are streamed from the resolver — and + // therefore keyed in `canonical_indices` — under their + // *source-coordinate* dep_path (`name@git+`), not their + // semver `spec_key()`. So once such a dep picks up a peer + // suffix, neither the contextualized `dep_path` (carries the + // suffix) nor `spec_key()` (semver, not the git coordinate) + // matches the streamed key, and the index would be silently + // dropped — later tripping `ERR_AUBE_MISSING_PACKAGE_INDEX` in + // the linker's global-virtual-store pass. Stripping the suffix + // recovers the exact canonical coordinate the index was stored + // under (the peer-context pass builds the key as + // `{canonical_base}{suffix}`, so this is its precise inverse). + let canonical_dep_path = strip_peer_context_suffix(dep_path); if let Some(idx) = canonical_indices .get(dep_path) + .or_else(|| canonical_indices.get(canonical_dep_path)) .or_else(|| canonical_indices.get(&canonical_key)) { out.insert(dep_path.clone(), idx.clone()); @@ -1072,6 +1089,21 @@ pub(super) fn remap_indices_to_contextualized( out } +/// Strip the peer-context suffix from a `dep_path`, recovering the +/// canonical dep_path the resolver streamed it under (and that +/// `canonical_indices` is keyed by). The peer-context pass in +/// `aube-resolver` appends either a parenthesized `(peer@ver)…` tail +/// or, when the suffix body exceeds the length cap, a single +/// parenthesized short hash `()` (pnpm's +/// `createPeerDepGraphHash`). Both forms begin at the first `(`, so +/// cutting there is the exact inverse and recovers the canonical +/// coordinate. A `dep_path` with no suffix is returned unchanged — a +/// bare `_` tail belongs to a `git+`/`url+`/`file+` source +/// coordinate and is never a peer marker, so it is preserved. +fn strip_peer_context_suffix(dep_path: &str) -> &str { + dep_path.split('(').next().unwrap_or(dep_path) +} + #[cfg(test)] mod tests { use super::lockfile_tarball_url_matches_metadata; @@ -1114,4 +1146,138 @@ mod tests { "http://localhost:4873/is-odd/-/is-odd-3.0.1.tgz", )); } + + #[test] + fn strip_peer_context_suffix_recovers_canonical_base() { + use super::strip_peer_context_suffix; + // Plain parenthesized peer suffix. + assert_eq!( + strip_peer_context_suffix("a@git+abc1234567890123(react@18.0.0)"), + "a@git+abc1234567890123" + ); + // Multiple / nested peer segments. + assert_eq!( + strip_peer_context_suffix("a@git+abc1234567890123(b@1.0.0)(c@2.0.0)"), + "a@git+abc1234567890123" + ); + // Hashed suffix `()` emitted past the length cap. + assert_eq!( + strip_peer_context_suffix("a@git+abc1234567890123(0123456789abcdef0123456789abcdef)"), + "a@git+abc1234567890123" + ); + // Scoped name keeps its leading `@scope/` intact. + assert_eq!( + strip_peer_context_suffix("@scope/a@git+abc1234567890123(b@1)"), + "@scope/a@git+abc1234567890123" + ); + // No suffix → unchanged. + assert_eq!(strip_peer_context_suffix("a@1.0.0"), "a@1.0.0"); + // A bare `_` tail belongs to the source coordinate, not a + // peer marker — only parenthesized suffixes are stripped, so it + // is preserved (the old bare-marker stripper would have wrongly + // truncated it). + assert_eq!( + strip_peer_context_suffix("a@git+abc1234567890123_0123456789"), + "a@git+abc1234567890123_0123456789" + ); + } + + fn one_file_index() -> aube_store::PackageIndex { + let mut index = aube_store::PackageIndex::default(); + index.insert( + "package.json".to_string(), + aube_store::StoredFile { + hex_hash: "deadbeef".to_string(), + store_path: std::path::PathBuf::from("/store/de/adbeef"), + executable: false, + size: Some(2), + }, + ); + index + } + + fn git_pkg(dep_path: &str) -> aube_lockfile::LockedPackage { + aube_lockfile::LockedPackage { + name: "left-pad".to_string(), + version: "5.0.0".to_string(), + dep_path: dep_path.to_string(), + local_source: Some(aube_lockfile::LocalSource::Git(aube_lockfile::GitSource { + url: "git+https://github.com/x/left-pad.git".to_string(), + committish: None, + resolved: "3c803342e33ad8281122334455667788".to_string(), + integrity: None, + subpath: None, + })), + ..Default::default() + } + } + + // Regression: a git dep that the peer-context pass tags with a + // `(peer@ver)` suffix must still resolve its streamed canonical + // index. Before the fix the contextualized dep_path missed both + // lookups (`dep_path` carries the suffix; `spec_key()` is the + // semver, not the git coordinate), so the linker's global-virtual- + // store pass tripped `ERR_AUBE_MISSING_PACKAGE_INDEX`. + #[test] + fn remap_recovers_git_dep_index_through_peer_suffix() { + let canonical = "left-pad@git+3c803342e33ad828"; + let contextualized = format!("{canonical}(ramda@0.30.1)"); + + let mut canonical_indices = std::collections::BTreeMap::new(); + canonical_indices.insert(canonical.to_string(), one_file_index()); + + let mut graph = aube_lockfile::LockfileGraph::default(); + graph + .packages + .insert(contextualized.clone(), git_pkg(&contextualized)); + + let out = super::remap_indices_to_contextualized(&canonical_indices, &graph); + assert!( + out.contains_key(&contextualized), + "git dep with peer suffix should recover its canonical index; got {:?}", + out.keys().collect::>() + ); + } + + // Same recovery for the hashed-suffix form the peer-context pass + // emits when the suffix body exceeds the length cap: a single + // parenthesized short hash `()`. + #[test] + fn remap_recovers_git_dep_index_through_hashed_peer_suffix() { + let canonical = "left-pad@git+3c803342e33ad828"; + let contextualized = format!("{canonical}(0123456789abcdef0123456789abcdef)"); + + let mut canonical_indices = std::collections::BTreeMap::new(); + canonical_indices.insert(canonical.to_string(), one_file_index()); + + let mut graph = aube_lockfile::LockfileGraph::default(); + graph + .packages + .insert(contextualized.clone(), git_pkg(&contextualized)); + + let out = super::remap_indices_to_contextualized(&canonical_indices, &graph); + assert!( + out.contains_key(&contextualized), + "git dep with hashed peer suffix should recover its canonical index; got {:?}", + out.keys().collect::>() + ); + } + + // A suffix-less git dep keyed identically in both maps still maps + // straight through (guards against the strip changing the happy path). + #[test] + fn remap_maps_suffixless_git_dep_directly() { + let canonical = "left-pad@git+3c803342e33ad828"; + + let mut canonical_indices = std::collections::BTreeMap::new(); + canonical_indices.insert(canonical.to_string(), one_file_index()); + + let mut graph = aube_lockfile::LockfileGraph::default(); + graph + .packages + .insert(canonical.to_string(), git_pkg(canonical)); + + let out = super::remap_indices_to_contextualized(&canonical_indices, &graph); + assert!(out.contains_key(canonical)); + } } diff --git a/docs/settings/index.md b/docs/settings/index.md index 34957139b..c3c64e5c0 100644 --- a/docs/settings/index.md +++ b/docs/settings/index.md @@ -1559,10 +1559,11 @@ Max length of the peer-ID suffix in lockfile dep_paths. - Workspace YAML keys: `peersSuffixMaxLength` Caps the length of the peer-ID suffix appended to a `dep_path` in the -lockfile (e.g. `react-dom@18.2.0(react@18.2.0)`). When the suffix would -exceed this many bytes, aube replaces it with `_` where `` is -a short SHA-256 digest of the full suffix — matching pnpm's format so -lockfiles stay portable. +lockfile (e.g. `react-dom@18.2.0(react@18.2.0)`). When the suffix body +would exceed this many bytes, aube replaces the whole suffix with a +parenthesized short hash `()` — the first 32 chars of the +SHA-256 of the suffix body — matching pnpm's `createPeerDepGraphHash` +so lockfiles stay portable. Mutual-peer cycles in large graphs can otherwise grow suffixes unboundedly across fixed-point iterations of the resolver. The default