Skip to content

fix(resolving-local-resolver): install local file: tarball dependencies - #13409

Merged
zkochan merged 9 commits into
mainfrom
fix-13379
Jul 27, 2026
Merged

zkochan merged 9 commits into
mainfrom
fix-13379

Conversation

@zkochan

@zkochan zkochan commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

Summary

A file:*.tgz dependency installed as a no-op: pnpm install exited 0, wrote no packages: / snapshots: entry, and left node_modules/<name> as a dangling symlink into a virtual-store directory that was never created.

The name, version, and dependencies of a local tarball live only inside the archive's own package.json. The local resolver's file: branch returned manifest: None, so build_pkg_id_with_patch_hash had no name to prefix and emitted the bare file:<path> as the dep path. That parses as no lockfile key, and build_packages_and_snapshots dropped the node with a silent continue — while the importer entry, which takes a different file:-prefixed path, was still written.

The resolver now reads the archive during resolution, the way the tarball resolver already does for remote tarballs and the git resolver for git deps. pacquet-tarball grows read_local_tarball_metadata, which hashes the file and reads its bundled package.json in one pass, replacing the resolver's hash-only read — so it costs no extra file read. Nothing is written to the store: the install pass addresses a file: tarball's store-index row by its <name>@file:<path> dep path, not by the <name>@<version> a resolve-time extraction could key, so such a row would never be read.

With the name in scope the dep path becomes <name>@file:<path>, both lockfile blocks are emitted, the tarball's own dependencies are walked (they were dropped entirely before), and the install summary prints the version instead of the raw specifier. Verified against pnpm 11 on the issue's fixture and on a tarball with a registry dependency — the lockfiles are byte-identical.

Reading the manifest means its name now flows into the dep path and into a node_modules/<name> directory, so the shapes that used to fail silently are refused the way pnpm refuses them:

bundled package.json error
not valid JSON ERR_PNPM_TARBALL_EXTRACT
valid JSON, no usable name ({}, [1,2], null, {"name":""}, version-only) ERR_PNPM_MISSING_PACKAGE_NAME
name that isn't a valid npm name (evil@name, ../escape, node_modules) ERR_PNPM_INVALID_DEPENDENCY_NAME

Each was verified against pnpm 11 first. The evil@name case mattered most: it produced the dep path evil@name@file:<path>, which parses back out as the unrelated package evil and links a dangling symlink — reachable only because this PR is what first puts an archive-controlled name into the dep path.

An archive carrying no package.json at all stays tolerated, since pnpm installs that one by synthesizing a name from the alias.

pnpm 11 already handles file: tarballs correctly — it reads the manifest from the fetch, and resolves and fetches together — so this needs no TypeScript counterpart.

Closes #13379.

On the silent continue

The issue suggests hardening build_packages_and_snapshots to error rather than drop an unparsable dep path. I drafted that and pulled it back out: it is only correct once pacquet grows pnpm's getManifestFromResponse fallback. A tarball carrying no package.json at all still has no name to key a row by, and pnpm installs that case — synthesizing { name: <alias>, version: '0.0.0' } — where the hardening alone would fail closed. Both halves are tracked together in #13410.

Squash Commit Body

A `file:*.tgz` dependency's name, version, and dependencies live only in
the archive's own `package.json`. The local resolver left `manifest`
unset for the tarball branch, so `build_pkg_id_with_patch_hash` had no
name to prefix and emitted the bare `file:<path>` as the dep path. That
parses as no lockfile key, and `build_packages_and_snapshots` dropped it
with a silent `continue` — the install reported success while writing no
`packages:` / `snapshots:` row and linking a dangling symlink into a
virtual-store directory that was never created.

Read the archive during resolution, as the tarball resolver already does
for remote tarballs and the git resolver for git deps: `pacquet-tarball`
grows `read_local_tarball_metadata`, which hashes the file and reads its
bundled `package.json` in one pass, replacing the resolver's hash-only
read. Nothing is written to the store — the install pass addresses a
`file:` tarball's store-index row by its `<name>@file:<path>` dep path,
not by the `<name>@<version>` a resolve-time extraction could key, so
such a row would never be read.

With the name in scope the dep path becomes `<name>@file:<path>`, both
lockfile blocks are emitted, the tarball's own dependencies are walked
(they were dropped entirely before), and the install summary prints the
version instead of the raw specifier. The lockfile is byte-identical to
pnpm 11's for the same manifest.

The manifest is borrowed out of the decompressed archive buffer rather
than read through the tar entry, so an entry header can't size an
allocation; the offset/size arithmetic both call sites need is extracted
into `tar_entry_payload`.

Reading the manifest puts its `name` into the dep path and into a
`node_modules/<name>` directory, so the shapes that used to fail
silently are refused the way pnpm refuses them: a `package.json` that
isn't valid JSON raises `ERR_PNPM_TARBALL_EXTRACT`, one that names no
package raises `ERR_PNPM_MISSING_PACKAGE_NAME`, and one whose name isn't
a valid npm name raises `ERR_PNPM_INVALID_DEPENDENCY_NAME`. Degrading to
"no manifest" is right for the extraction path, whose consumers re-read
from disk, but here the manifest is the package's only source of
identity, so clearing it reproduces the bug above.

An archive with no `package.json` at all stays tolerated, matching pnpm,
which synthesizes a name from the alias. Telling that apart from a
nameless manifest needs more than a `None`, so the reader reports
whether a root `package.json` was present.

pnpm 11 already handles `file:` tarballs correctly (it reads the manifest
from the fetch, and resolves and fetches together), so this needs no
TypeScript counterpart.

Closes pnpm/pnpm#13379.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

Written by an agent (Claude Code, claude-opus-5).

zkochan added 2 commits July 27, 2026 00:52
…olve time

A `file:*.tgz` dependency's name, version, and dependencies live only in
the archive's own `package.json`. The local resolver left `manifest`
unset for the tarball branch, so `build_pkg_id_with_patch_hash` had no
name to prefix and emitted the bare `file:<path>` as the dep path. That
parses as no lockfile key, and `build_packages_and_snapshots` dropped it
with a silent `continue` — the install reported success while writing no
`packages:` / `snapshots:` row and linking a dangling symlink into a
virtual-store directory that was never created.

Read the archive during resolution, as the tarball resolver already does
for remote tarballs and the git resolver for git deps: `pacquet-tarball`
grows `read_local_tarball_metadata`, which hashes the file and reads its
bundled `package.json` in one pass, replacing the resolver's
hash-only read. Nothing is written to the store — the install pass
addresses a `file:` tarball's store-index row by its `<name>@file:<path>`
dep path, not by the `<name>@<version>` a resolve-time extraction could
key, so such a row would never be read.

With the name in scope the dep path becomes `<name>@file:<path>`, both
lockfile blocks are emitted, the tarball's own dependencies are walked
(they were dropped entirely before), and the install summary prints the
version instead of the raw specifier. The lockfile is byte-identical to
pnpm 11's for the same manifest.

Harden the drop site too: `build_packages_and_snapshots` now errors on a
dep path that keys no row instead of skipping it, so the next resolver
gap surfaces at its source rather than as an install that exits 0 over a
broken `node_modules`. `link:` deps are exempt — pnpm writes no row for
one either.

pnpm 11 already handles `file:` tarballs correctly (it reads the manifest
from the fetch, and resolves and fetches together), so this needs no
TypeScript counterpart.

Closes #13379.
Copilot AI review requested due to automatic review settings July 26, 2026 22:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Local file:*.tgz dependencies now expose verified integrity and bundled manifest metadata during resolution. The resolver records this data, validates package names, and CLI tests cover lockfile entries, extraction, frozen reinstalls, and bundled dependencies.

Changes

Local tarball installation

Layer / File(s) Summary
Tarball metadata extraction
pnpm/crates/tarball/src/lib.rs, pnpm/crates/tarball/src/tests.rs, pnpm/crates/testing-utils/src/fixtures.rs
Adds local tarball metadata reading, checked tar-entry slicing, bundled-manifest errors, fixtures, and metadata tests.
Local resolver integration
pnpm/crates/resolving-local-resolver/...
The file: resolver consumes tarball metadata, validates bundled names, returns manifests, and maps tarball failures to resolver errors.
Installation and release coverage
pnpm/crates/cli/tests/local_tarball_dependency.rs, .changeset/local-tarball-dependency-install.md
End-to-end tests verify lockfile recording, virtual-store extraction, frozen reinstalls, and bundled dependency linking; release metadata records the patch fix.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant LocalResolver
  participant TarballMetadata
  participant LockfileInstaller
  CLI->>LocalResolver: resolve local file tarball
  LocalResolver->>TarballMetadata: read_local_tarball_metadata(path)
  TarballMetadata-->>LocalResolver: integrity and bundled manifest
  LocalResolver-->>LockfileInstaller: local resolve result
  LockfileInstaller->>LockfileInstaller: record packages and snapshots
  LockfileInstaller->>LockfileInstaller: extract and link virtual-store package
Loading

Possibly related issues

  • pnpm/pnpm#13379 — The changes directly implement the reported local file:*.tgz installation fix.
  • pnpm/pnpm#13410 — This relates to local tarballs without bundled manifests and lockfile handling.

Possibly related PRs

  • pnpm/pnpm#13327 — Both changes modify bundled package.json parsing in pnpm/crates/tarball/src/lib.rs.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-13379

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix local file: tarball resolution by reading manifest + hardening lockfile conversion

🐞 Bug fix 🧪 Tests ✨ Enhancement 🕐 40+ Minutes

Grey Divider

AI Description

• Read package.json from local file:*.tgz during resolution to key lockfile entries correctly.
• Fail fast when a dependency path cannot become a packages:/snapshots: key (except link:).
• Add end-to-end and unit tests covering local tarball installs and dependency walking.
Diagram

graph TD
  A["CLI install"] --> B["Local resolver"] --> C["read_local_tarball_metadata"] --> D["Local .tgz"] --> C --> E["Dependencies graph"] --> F["Lockfile builder"] --> G["pnpm-lock.yaml"] --> H["Install/linking"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Defer manifest read until install phase
  • ➕ Avoids additional tarball parsing during resolution
  • ➕ Could reuse install-time extraction logic directly
  • ➖ Lockfile is produced before install; resolver would still lack name/version for dep-path keying
  • ➖ Would require redesigning lockfile build pipeline or storing unresolved placeholders
2. Extract tarball to a temp/store location during resolution
  • ➕ Manifest read becomes a byproduct of extraction
  • ➕ Could potentially speed later install if reuse were possible
  • ➖ PR notes store-index rows for file: tarballs are addressed by @file:, so resolve-time writes may not be reused
  • ➖ More I/O and cleanup complexity; higher risk of mismatching install behavior
3. Change dep-path scheme to allow bare `file:` lockfile keys
  • ➕ Would avoid needing the tarball manifest for lockfile key validity
  • ➕ Could simplify handling of tarballs without parseable manifests
  • ➖ Breaking change to lockfile key format and downstream assumptions
  • ➖ Would ripple through parsing/serialization and compatibility with pnpm conventions

Recommendation: The chosen approach—reading the bundled manifest and integrity from the local tarball during resolution—is the best fit for the existing pipeline (lockfile generation precedes install) and aligns local-tarball behavior with remote tarball/git resolution. The additional hardening in lockfile conversion is also appropriate: it surfaces resolver gaps immediately instead of producing a “successful” install with broken node_modules.

Files changed (11) +328 / -45

Enhancement (2) +90 / -1
lib.rsAdd 'read_local_tarball_metadata' to parse local tarball manifest +82/-0

Add 'read_local_tarball_metadata' to parse local tarball manifest

• Introduces 'LocalTarballMetadata' and 'read_local_tarball_metadata', which reads local tarball bytes once, computes sha512 integrity, decompresses, and extracts a normalized root 'package.json'. Parsing failures degrade to 'None' (debug-logged) to match extraction conventions.

pnpm/crates/tarball/src/lib.rs

fixtures.rsExpose reusable tarball builders for tests +8/-1

Expose reusable tarball builders for tests

• Refactors 'minimal_tarball' to delegate to a new 'tarball_with_manifest' helper that writes arbitrary JSON as 'package/package.json', enabling targeted fixture creation across crates.

pnpm/crates/testing-utils/src/fixtures.rs

Bug fix (2) +47 / -29
dependencies_graph_to_lockfile.rsError on unparsable dep paths when building packages/snapshots +27/-4

Error on unparsable dep paths when building packages/snapshots

• Replaces a silent skip on 'dep_path' → 'PackageKey' parse failure with a structured error, preventing incomplete lockfiles. Keeps 'link:' dependencies exempt since pnpm does not emit 'packages:'/'snapshots:' entries for them.

pnpm/crates/package-manager/src/dependencies_graph_to_lockfile.rs

local_resolver.rsRead local tarball integrity + bundled manifest at resolve time +20/-25

Read local tarball integrity + bundled manifest at resolve time

• Replaces the resolver’s previous integrity-only read with 'read_local_tarball_metadata', returning both integrity and an optional manifest. Maps missing tarballs to the existing linked-pkg-not-found error code and adds an explicit 'ReadTarball' error variant for other failures.

pnpm/crates/resolving-local-resolver/src/local_resolver.rs

Tests (4) +184 / -12
local_tarball_dependency.rsAdd end-to-end tests for local tarball install behavior +128/-0

Add end-to-end tests for local tarball install behavior

• Introduces CLI-level tests that create local tarballs on the fly, install them, and assert lockfile keying ('<name>@file:<path>'), virtual-store extraction, and frozen-lockfile reproducibility. Adds coverage for walking a tarball’s own dependencies.

pnpm/crates/cli/tests/local_tarball_dependency.rs

tests.rsAdjust test to expect structured dep-path parse failure +8/-3

Adjust test to expect structured dep-path parse failure

• Updates the existing malformed-path test to assert the new 'UnparsableDepPath' error shape and clarifies why the conversion must fail rather than drop entries.

pnpm/crates/package-manager/src/dependencies_graph_to_lockfile/tests.rs

resolve.rsExtend resolver tests to assert bundled manifest presence for tarballs +13/-8

Extend resolver tests to assert bundled manifest presence for tarballs

• Updates tarball fixture generation to use shared testing utilities and adds assertions that tarball resolution populates 'manifest' with correct name/version, preventing bare 'file:<path>' dep paths.

pnpm/crates/resolving-local-resolver/tests/resolve.rs

tests.rsTest local tarball metadata reading and not-found error propagation +35/-1

Test local tarball metadata reading and not-found error propagation

• Adds tests verifying integrity + manifest extraction from a known tarball and ensuring a missing tarball reports an 'ErrorKind::NotFound' via 'TarballError::ReadLocalTarball' (required by resolver error mapping).

pnpm/crates/tarball/src/tests.rs

Documentation (1) +5 / -0
local-tarball-dependency-install.mdDocument fix for local 'file:*.tgz' installs +5/-0

Document fix for local 'file:*.tgz' installs

• Adds a changeset noting that local tarball dependencies are now recorded in 'packages:'/'snapshots:' and extracted/linked correctly. References the upstream issue for traceability.

.changeset/local-tarball-dependency-install.md

Other (2) +2 / -3
Cargo.lockUpdate workspace lockfile for dependency changes +1/-1

Update workspace lockfile for dependency changes

• Reflects crate dependency adjustments (notably adding 'pacquet-tarball' and removing 'ssri' from one crate’s dependency set).

Cargo.lock

Cargo.tomlSwitch local resolver deps from 'ssri'/'tokio' to 'pacquet-tarball' +1/-2

Switch local resolver deps from 'ssri'/'tokio' to 'pacquet-tarball'

• Adds a direct dependency on 'pacquet-tarball' to reuse tarball metadata reading. Removes 'ssri' and the resolver’s prior tokio fs/io usage tied to integrity-only hashing.

pnpm/crates/resolving-local-resolver/Cargo.toml

@greptile-apps

greptile-apps Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains, and the previous documentation concern has been addressed by retaining only non-obvious architectural and test rationale.

Reviews (6): Last reviewed commit: "fix(resolving-local-resolver): reject an..." | Re-trigger Greptile

@github-actions

github-actions Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     10.6±0.35ms    35.5 MB/sec    1.00     10.6±0.18ms    35.5 MB/sec
packument/parse                1.04     38.5±2.64µs  1724.8 MB/sec    1.00     36.8±0.73µs  1802.0 MB/sec
tarball/download_dependency    1.02      2.8±0.16ms  1551.8 KB/sec    1.00      2.7±0.10ms  1586.4 KB/sec

@qodo-code-review

qodo-code-review Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (2) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 32 rules

Grey Divider


Action required

1. Tarball name not validated ✓ Resolved 🐞 Bug ⛨ Security
Description
bundled_package_name() only rejects empty names, so a tarball with an invalid npm name (e.g.
"evil@name") can be accepted and later used to prefix IDs (<name>@file:...), producing strings
that downstream parsers split on the first @ and can’t parse into lockfile keys. This can
reintroduce resolution/lockfile failures (or silent drops, depending on the downstream caller)
despite the new manifest read.
Code

pnpm/crates/resolving-local-resolver/src/local_resolver.rs[R350-352]

+fn bundled_package_name(manifest: Option<&serde_json::Value>) -> Option<&str> {
+    manifest?.get("name")?.as_str().filter(|name| !name.is_empty())
+}
Relevance

⭐⭐ Medium

Hardening is often accepted, but early npm-name validation was rejected (PR13353); no direct
local-tarball precedent found.

PR-#13353
PR-#13059
PR-#12864

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The resolver currently accepts any non-empty name from the bundled tarball manifest, but
downstream code prefixes IDs with that manifest name; lockfile-related parsing uses @ as a
structural delimiter, so invalid names with additional @ characters (or other invalid forms
rejected by pnpm’s validator) can break parsing and keying.

pnpm/crates/resolving-local-resolver/src/local_resolver.rs[218-231]
pnpm/crates/resolving-local-resolver/src/local_resolver.rs[350-356]
pnpm/crates/resolving-parse-wanted-dependency/src/validate_npm_package_name.rs[31-59]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[3243-3264]
pnpm/crates/lockfile/src/pkg_name_suffix.rs[48-77]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The local resolver treats any non-empty manifest `name` as usable (`bundled_package_name`), but pacquet later prefixes IDs with that name; invalid npm names containing `@` (not as a scope marker), whitespace, etc. can create dep paths / lockfile keys that downstream parsing splits incorrectly, recreating “unparseable key” failure modes.

## Issue Context
- The tarball’s manifest name is now consumed during resolution and becomes part of the package identity.
- The repo already has an npm-name validator (`is_valid_old_npm_package_name`) that mirrors pnpm’s JS behavior.

## Fix
1. Update `bundled_package_name()` to validate the string with `pacquet_resolving_parse_wanted_dependency::is_valid_old_npm_package_name` (or equivalent validation) instead of only checking `!is_empty()`.
2. When `has_manifest_entry == true` and the bundled name is missing *or invalid*, fail resolution with an explicit error (prefer `ERR_PNPM_INVALID_PACKAGE_NAME`; alternatively reuse `ERR_PNPM_MISSING_PACKAGE_NAME` if you must preserve the existing code path).
3. Add/extend a regression test that writes a tarball with a bundled manifest name like `"evil@name"` (or leading/trailing whitespace) and asserts the resolver fails early (before lockfile build).

## Fix Focus Areas
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[132-144]
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[218-227]
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[350-353]
- pnpm/crates/resolving-local-resolver/tests/resolve.rs[214-249]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Unrelated dead_upstream test change 📘 Rule violation ⚙ Maintainability ⭐ New
Description
This PR is scoped as a local file:*.tgz install bug fix, but it also changes pnpr’s
unreachable_upstream_maps_to_service_unavailable test setup to use http://127.0.0.1:0. This
violates the scope discipline rule for bug-fix PRs and should be split out or explicitly justified
as required for this fix/test stability.
Code

pnpr/crates/pnpr/tests/server.rs[R1686-1692]

+    // Port 0 is never a listening port, so connecting to it is refused
+    // outright — exercising the `is_connect()` branch of the status
+    // mapping without depending on DNS. Probing for a free ephemeral
+    // port instead would race: the suite's mockito servers bind ephemeral
+    // ports throughout the run and can claim the probed one before the
+    // request goes out, turning the refusal into a success.
+    let dead_upstream = "http://127.0.0.1:0".to_string();
Relevance

⭐⭐⭐ High

Team enforces scope discipline; unrelated lockfile churn was fixed in PR #11450; scope-discipline
guidance in PR #12522.

PR-#11450
PR-#12522

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The checklist requires bug-fix changes to avoid unrelated refactors/changes outside the bug’s scope.
The modified pnpr test block changes behavior (targeting port 0) but is not part of the local
tarball resolver fix described by the PR.

Rule 2255067: Bug fix changes must not include unrelated refactors or reformatting
pnpr/crates/pnpr/tests/server.rs[1686-1692]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A pnpr test setup change (`dead_upstream` now uses port 0) is included in a bug-fix PR whose stated scope is local `file:*.tgz` dependency installation.

## Issue Context
Bug-fix PRs must avoid unrelated changes; if this pnpr test modification is necessary (e.g., to prevent newly introduced CI flakes), it should either be moved to a dedicated PR or explicitly justified as required for this PR.

## Fix Focus Areas
- pnpr/crates/pnpr/tests/server.rs[1686-1692]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Non-object manifest bypasses error 🐞 Bug ≡ Correctness
Description
read_bundled_manifest() only maps JSON *parse* failures to TarballError::ParseBundledManifest;
if the bundled package.json is valid JSON but not a JSON object (e.g. null, string, array),
normalize_bundled_manifest() returns None and the resolver can fall back to the raw
file:<path> id again. This can recreate the “no lockfile key parseable” path for local tarballs
instead of failing fast with ERR_PNPM_TARBALL_EXTRACT.
Code

pnpm/crates/tarball/src/lib.rs[R2769-2773]

+    let Some(payload) = payload else { return Ok(None) };
+    let parsed = parse_manifest_bytes(payload).map_err(|source| {
+        TarballError::ParseBundledManifest { tarball: tarball_path.to_string(), source }
+    })?;
+    Ok(normalize_bundled_manifest(&parsed))
Relevance

⭐⭐⭐ High

Repo trend: don’t swallow manifest/parse anomalies; prefer fail-fast correctness hardening in
tarball/manifest paths.

PR-#13404
PR-#13059

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The resolve-time manifest reader normalizes non-object JSON to None, and the dep-id prefixing
logic explicitly returns the raw id when the manifest has no name, which is the same failure mode
this PR is trying to prevent for local file: tarballs.

pnpm/crates/tarball/src/lib.rs[2731-2773]
pnpm/crates/tarball/src/lib.rs[527-556]
pnpm/crates/package-manifest/src/lib.rs[852-867]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[3243-3259]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`read_bundled_manifest()` treats a present-but-non-object `package.json` as `None` (same as “missing manifest”), which can drop the package identity used to prefix `file:` tarball ids.

## Issue Context
`parse_manifest_bytes()` returns any `serde_json::Value` (not necessarily an object). `normalize_bundled_manifest()` returns `None` when the parsed value isn’t an object, so `read_bundled_manifest()` currently can’t distinguish “missing `package.json`” from “invalid shape `package.json`”. Downstream, when the manifest has no `name`, `build_pkg_id_with_patch_hash()` returns the raw id unchanged.

## Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2769-2773]
- pnpm/crates/tarball/src/lib.rs[2736-2742]
- pnpm/crates/tarball/src/tests.rs[1354-1376]

## Suggested change
1. After parsing `payload`, require the manifest to be a JSON object for the resolve-time path; if it’s not an object, return an error with the same diagnostic code as `ParseBundledManifest` (either reuse `ParseBundledManifest` via a new error variant that doesn’t require `serde_json::Error`, or add a dedicated `InvalidBundledManifestShape` that maps to `ERR_PNPM_TARBALL_EXTRACT`).
2. Add a unit test that writes `package/package.json` as e.g. `null` or `"oops"` and asserts `read_local_tarball_metadata()` fails with the expected tarball error.

This preserves the intended behavior of tolerating *absence* of `package.json`, while rejecting a present-but-invalid manifest that would otherwise lose identity.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Manifest parse error hidden ✓ Resolved 🐞 Bug ☼ Reliability
Description
read_bundled_manifest() swallows JSON parse errors for the tarball’s package.json and returns
None, even when the entry exists. For local file: tarballs this drops the only available
name/version source that the resolver uses to prefix the dep path (<name>@file:<path>) for
lockfile keying, obscuring the root cause.
Code

pnpm/crates/tarball/src/lib.rs[R2735-2737]

+        drop(components);
+        let bytes = tar_entry_payload(tar_data, &entry)?;
+        manifest = match parse_manifest_bytes(bytes) {
Relevance

⭐⭐⭐ High

Team has accepted preserving/propagating manifest read/parse errors instead of silently swallowing
them.

PR-#13404

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The tarball helper explicitly degrades an unparsable package.json to None, while the local
resolver tests state the bundled manifest is what enables the <name>@ prefix used for lockfile key
parsing.

pnpm/crates/tarball/src/lib.rs[2710-2747]
pnpm/crates/resolving-local-resolver/tests/resolve.rs[245-252]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`read_bundled_manifest()` currently treats an invalid `package.json` inside a tarball as a best-effort condition and clears the manifest to `None`. For local `file:` tarballs, that manifest is the only source of the package identity used to build `<name>@file:<path>` lockfile keys; silently dropping it makes failures harder to diagnose and can break resolution/lockfile output.

### Issue Context
- The resolver/test suite documents that the bundled manifest is required to prefix the dep path so a lockfile key can be parsed.
- The manifest parse failure is a strong signal of a corrupted/invalid tarball input and should surface as a clear error at resolution time.

### Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2710-2748]
- pnpm/crates/resolving-local-resolver/tests/resolve.rs[245-252]

### Suggested fix
- In `read_bundled_manifest()`, if a root `package.json` entry is found but `parse_manifest_bytes(...)` fails, return an error (new `TarballError` variant or reuse an appropriate existing one) that includes context (e.g., `file:` URL/path) instead of returning `None`.
- Keep `None` only for the “no root package.json entry found” case (if that is intended to be tolerated), but prefer a targeted diagnostic if local tarballs are expected to always contain it.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (2)
5. Historical comment in module header ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A newly added test file comment/doc comment describes pre-fix broken behavior using historical
phrasing (e.g., “before”, “without the name…”) instead of documenting the current behavior/contract
and intent of the test. This violates the requirement to avoid historical implementation commentary
in source comments.
Code

pnpm/crates/cli/tests/local_tarball_dependency.rs[R4-10]

+//! A `file:` tarball's name, version, and integrity live inside the
+//! archive, not in its specifier. pacquet builds the lockfile before the
+//! install pass, so the local resolver reads them during resolution —
+//! the same reason the remote-tarball resolver downloads at resolve time
+//! (see `tarball_url_dependency.rs`). Without the name the dep path
+//! stays the bare `file:<path>`, which keys no `packages:` / `snapshots:`
+//! entry, and the install exits 0 over a dangling symlink.
Relevance

⭐⭐⭐ High

Repo often accepts rewriting test comments to avoid “before/used to” historical phrasing and focus
on current intent.

PR-#13246
PR-#13138
PR-#13297

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 772199 requires comments to describe current behavior and intent and forbids
referencing past behavior/implementations. In pnpm/crates/cli/tests/local_tarball_dependency.rs, the
header comment explains an old failure mode (“Without the name… install exits 0 over a dangling
symlink”), and a doc comment uses explicit temporal language (“so before it was read at resolve
time…”), both of which are framed as historical context rather than the present-day contract the
test is asserting.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/cli/tests/local_tarball_dependency.rs[4-10]
pnpm/crates/cli/tests/local_tarball_dependency.rs[84-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Rewrite the newly added comment(s) in the test file to describe the current behavior, contract, and intent being tested, without using historical/temporal phrasing about what happened before a fix.

## Issue Context
PR Compliance ID 772199 forbids source comments that reference past behavior/implementations (e.g., “before”, “used to”, “without X it would…”). If historical background is needed, it belongs in the PR description or commit history; in-code comments should only explain what the code/test asserts now and why it exists.

## Fix Focus Areas
- pnpm/crates/cli/tests/local_tarball_dependency.rs[4-10]
- pnpm/crates/cli/tests/local_tarball_dependency.rs[84-86]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Unbounded tarball inflate read ✓ Resolved 🐞 Bug ⛨ Security
Description
read_local_tarball_metadata() inflates the entire local .tgz into an in-memory tar buffer and
read_bundled_manifest() then reads package.json with an unbounded read_to_end, so a crafted
repo-controlled file: tarball (gzip bomb or huge package.json) can exhaust memory/CPU during
*resolution* before install-time extraction. This is new resolve-time work and can turn `pnpm
install` (or any lockfile-building flow) into a denial-of-service when run on an untrusted
repository.
Code

pnpm/crates/tarball/src/lib.rs[R2676-2723]

+pub async fn read_local_tarball_metadata(
+    path: &Path,
+) -> Result<LocalTarballMetadata, TarballError> {
+    let package_url = format!("file:{}", path.display());
+    let (file, size) = open_local_tarball(path).await?;
+    let buffer = read_local_tarball_buffer(file, path, &package_url, size).await?;
+
+    let _post_download_permit = post_download_semaphore()
+        .acquire()
+        .await
+        .expect("post-download semaphore shouldn't be closed this soon");
+    tokio::task::spawn_blocking(move || {
+        let integrity = verify_tarball_integrity(&buffer, None, package_url)?;
+        let tar_data = decompress_gzip(&buffer, None)?;
+        let manifest = read_bundled_manifest(&tar_data)?;
+        Ok(LocalTarballMetadata { integrity, manifest })
+    })
+    .await
+    .map_err(TarballError::TaskJoin)?
+}
+
+/// Read the root `package.json` out of a decompressed tar stream,
+/// narrowed by [`normalize_bundled_manifest`] so it matches the
+/// manifest an extraction stashes on [`PackageFilesIndex`].
+///
+/// Follows the same conventions as the manifest capture in
+/// [`extract_tarball_entries`]: the top-level archive component is
+/// dropped, a duplicate entry wins over earlier ones, and an unparsable
+/// `package.json` degrades to `None` rather than failing the read.
+fn read_bundled_manifest(tar_data: &[u8]) -> Result<Option<serde_json::Value>, TarballError> {
+    let mut archive = Archive::new(Cursor::new(tar_data));
+    let mut manifest = None;
+    for entry in archive.entries_with_seek().map_err(TarballError::ReadTarballEntries)? {
+        let mut entry = entry.map_err(TarballError::ReadTarballEntries)?;
+        if !entry.header().entry_type().is_file() {
+            continue;
+        }
+        let path = entry.path().map_err(TarballError::ReadTarballEntries)?;
+        let mut components = path.components().skip(1);
+        if components.next() != Some(Component::Normal("package.json".as_ref()))
+            || components.next().is_some()
+        {
+            continue;
+        }
+        let mut bytes = Vec::new();
+        entry.read_to_end(&mut bytes).map_err(TarballError::ReadTarballEntries)?;
+        manifest = match parse_manifest_bytes(&bytes) {
+            Ok(parsed) => normalize_bundled_manifest(&parsed),
Relevance

⭐⭐ Medium

Security hardening is often accepted, but no close precedent on bounding tarball
decompression/manifest reads in this crate.

PR-#13371
PR-#13391
PR-#13091

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new resolve-time metadata reader fully inflates untrusted gzip input into a Vec and then reads
package.json into another unbounded Vec, with no hard limit on decompressed output or manifest
size. The tarball crate explicitly documents that its prealloc bounds do not bound decode output,
and the existing extraction pipeline shows a safer slice-based manifest read that avoids
read_to_end.

pnpm/crates/tarball/src/lib.rs[2676-2734]
pnpm/crates/tarball/src/lib.rs[34-44]
pnpm/crates/tarball/src/lib.rs[669-843]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`read_local_tarball_metadata()` currently decompresses a local tarball fully into memory (`decompress_gzip(&buffer, None)`) and `read_bundled_manifest()` reads the embedded `package.json` with an unbounded `read_to_end`. A crafted tarball can therefore cause memory/CPU exhaustion during resolution.

## Issue Context
This PR adds resolve-time tarball introspection for `file:*.tgz` to obtain name/version/deps. The existing extraction path (`extract_tarball_entries`) already demonstrates a safer approach for reading `package.json` without allocating a second buffer (slice via `raw_file_position`), and it performs stricter entry validation.

## Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2676-2734]
- pnpm/crates/tarball/src/lib.rs[669-843]

### Recommended implementation direction
1. **Eliminate unbounded `read_to_end` for `package.json`:**
  - Mirror `extract_tarball_entries`’ approach: when the `package.json` entry is found, compute `(offset, size)` from `raw_file_position()` + header size and borrow a slice from the already-buffered tar data, then call `parse_manifest_bytes(slice)`.
  - Add a defensive upper bound for `package.json` size (e.g. a few MB) and degrade to `None` (or return a structured error) when exceeded.

2. **Avoid full tar inflate where feasible (perf + DoS hardening):**
  - Consider a streaming `gzip -> tar` scan that only materializes the manifest entry (and enforces a maximum decompressed bytes read) rather than building a full `Vec<u8>` tar buffer.

3. **Keep behavior consistent with extraction contract:**
  - Preserve the existing “top-level component stripped” and “duplicate entry wins” semantics, but do so without unbounded allocations.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

7. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only declares a bump for pacquet even though it describes a user-visible `pnpm
install behavior fix. This violates the requirement to explicitly include the pnpm` package with
an appropriate bump type in every changeset.
Code

.changeset/local-tarball-dependency-install.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

⭐ Low

Similar “add pnpm to pacquet-only changeset” requests were repeatedly rejected in prior PRs.

PR-#13347
PR-#12981
PR-#13117

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires every added/modified changeset to explicitly list the pnpm
package with a valid bump type. The new changeset front-matter lists only pacquet, omitting
pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/local-tarball-dependency-install.md[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The changeset front-matter does not include an explicit entry for the `pnpm` package.

## Issue Context
This changeset text describes a `pnpm install` bug fix, and repository guidance requires that changesets always include `pnpm` explicitly with the correct bump type (`patch` for a bug fix).

## Fix Focus Areas
- .changeset/local-tarball-dependency-install.md[1-3]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Previous review results

Review updated until commit e8bed10

Results up to commit 2627039 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Historical comment in module header ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A newly added test file comment/doc comment describes pre-fix broken behavior using historical
phrasing (e.g., “before”, “without the name…”) instead of documenting the current behavior/contract
and intent of the test. This violates the requirement to avoid historical implementation commentary
in source comments.
Code

pnpm/crates/cli/tests/local_tarball_dependency.rs[R4-10]

+//! A `file:` tarball's name, version, and integrity live inside the
+//! archive, not in its specifier. pacquet builds the lockfile before the
+//! install pass, so the local resolver reads them during resolution —
+//! the same reason the remote-tarball resolver downloads at resolve time
+//! (see `tarball_url_dependency.rs`). Without the name the dep path
+//! stays the bare `file:<path>`, which keys no `packages:` / `snapshots:`
+//! entry, and the install exits 0 over a dangling symlink.
Relevance

⭐⭐⭐ High

Repo often accepts rewriting test comments to avoid “before/used to” historical phrasing and focus
on current intent.

PR-#13246
PR-#13138
PR-#13297

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 772199 requires comments to describe current behavior and intent and forbids
referencing past behavior/implementations. In pnpm/crates/cli/tests/local_tarball_dependency.rs, the
header comment explains an old failure mode (“Without the name… install exits 0 over a dangling
symlink”), and a doc comment uses explicit temporal language (“so before it was read at resolve
time…”), both of which are framed as historical context rather than the present-day contract the
test is asserting.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm/crates/cli/tests/local_tarball_dependency.rs[4-10]
pnpm/crates/cli/tests/local_tarball_dependency.rs[84-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Rewrite the newly added comment(s) in the test file to describe the current behavior, contract, and intent being tested, without using historical/temporal phrasing about what happened before a fix.

## Issue Context
PR Compliance ID 772199 forbids source comments that reference past behavior/implementations (e.g., “before”, “used to”, “without X it would…”). If historical background is needed, it belongs in the PR description or commit history; in-code comments should only explain what the code/test asserts now and why it exists.

## Fix Focus Areas
- pnpm/crates/cli/tests/local_tarball_dependency.rs[4-10]
- pnpm/crates/cli/tests/local_tarball_dependency.rs[84-86]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Unbounded tarball inflate read ✓ Resolved 🐞 Bug ⛨ Security
Description
read_local_tarball_metadata() inflates the entire local .tgz into an in-memory tar buffer and
read_bundled_manifest() then reads package.json with an unbounded read_to_end, so a crafted
repo-controlled file: tarball (gzip bomb or huge package.json) can exhaust memory/CPU during
*resolution* before install-time extraction. This is new resolve-time work and can turn `pnpm
install` (or any lockfile-building flow) into a denial-of-service when run on an untrusted
repository.
Code

pnpm/crates/tarball/src/lib.rs[R2676-2723]

+pub async fn read_local_tarball_metadata(
+    path: &Path,
+) -> Result<LocalTarballMetadata, TarballError> {
+    let package_url = format!("file:{}", path.display());
+    let (file, size) = open_local_tarball(path).await?;
+    let buffer = read_local_tarball_buffer(file, path, &package_url, size).await?;
+
+    let _post_download_permit = post_download_semaphore()
+        .acquire()
+        .await
+        .expect("post-download semaphore shouldn't be closed this soon");
+    tokio::task::spawn_blocking(move || {
+        let integrity = verify_tarball_integrity(&buffer, None, package_url)?;
+        let tar_data = decompress_gzip(&buffer, None)?;
+        let manifest = read_bundled_manifest(&tar_data)?;
+        Ok(LocalTarballMetadata { integrity, manifest })
+    })
+    .await
+    .map_err(TarballError::TaskJoin)?
+}
+
+/// Read the root `package.json` out of a decompressed tar stream,
+/// narrowed by [`normalize_bundled_manifest`] so it matches the
+/// manifest an extraction stashes on [`PackageFilesIndex`].
+///
+/// Follows the same conventions as the manifest capture in
+/// [`extract_tarball_entries`]: the top-level archive component is
+/// dropped, a duplicate entry wins over earlier ones, and an unparsable
+/// `package.json` degrades to `None` rather than failing the read.
+fn read_bundled_manifest(tar_data: &[u8]) -> Result<Option<serde_json::Value>, TarballError> {
+    let mut archive = Archive::new(Cursor::new(tar_data));
+    let mut manifest = None;
+    for entry in archive.entries_with_seek().map_err(TarballError::ReadTarballEntries)? {
+        let mut entry = entry.map_err(TarballError::ReadTarballEntries)?;
+        if !entry.header().entry_type().is_file() {
+            continue;
+        }
+        let path = entry.path().map_err(TarballError::ReadTarballEntries)?;
+        let mut components = path.components().skip(1);
+        if components.next() != Some(Component::Normal("package.json".as_ref()))
+            || components.next().is_some()
+        {
+            continue;
+        }
+        let mut bytes = Vec::new();
+        entry.read_to_end(&mut bytes).map_err(TarballError::ReadTarballEntries)?;
+        manifest = match parse_manifest_bytes(&bytes) {
+            Ok(parsed) => normalize_bundled_manifest(&parsed),
Relevance

⭐⭐ Medium

Security hardening is often accepted, but no close precedent on bounding tarball
decompression/manifest reads in this crate.

PR-#13371
PR-#13391
PR-#13091

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new resolve-time metadata reader fully inflates untrusted gzip input into a Vec and then reads
package.json into another unbounded Vec, with no hard limit on decompressed output or manifest
size. The tarball crate explicitly documents that its prealloc bounds do not bound decode output,
and the existing extraction pipeline shows a safer slice-based manifest read that avoids
read_to_end.

pnpm/crates/tarball/src/lib.rs[2676-2734]
pnpm/crates/tarball/src/lib.rs[34-44]
pnpm/crates/tarball/src/lib.rs[669-843]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`read_local_tarball_metadata()` currently decompresses a local tarball fully into memory (`decompress_gzip(&buffer, None)`) and `read_bundled_manifest()` reads the embedded `package.json` with an unbounded `read_to_end`. A crafted tarball can therefore cause memory/CPU exhaustion during resolution.

## Issue Context
This PR adds resolve-time tarball introspection for `file:*.tgz` to obtain name/version/deps. The existing extraction path (`extract_tarball_entries`) already demonstrates a safer approach for reading `package.json` without allocating a second buffer (slice via `raw_file_position`), and it performs stricter entry validation.

## Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2676-2734]
- pnpm/crates/tarball/src/lib.rs[669-843]

### Recommended implementation direction
1. **Eliminate unbounded `read_to_end` for `package.json`:**
  - Mirror `extract_tarball_entries`’ approach: when the `package.json` entry is found, compute `(offset, size)` from `raw_file_position()` + header size and borrow a slice from the already-buffered tar data, then call `parse_manifest_bytes(slice)`.
  - Add a defensive upper bound for `package.json` size (e.g. a few MB) and degrade to `None` (or return a structured error) when exceeded.

2. **Avoid full tar inflate where feasible (perf + DoS hardening):**
  - Consider a streaming `gzip -> tar` scan that only materializes the manifest entry (and enforces a maximum decompressed bytes read) rather than building a full `Vec<u8>` tar buffer.

3. **Keep behavior consistent with extraction contract:**
  - Preserve the existing “top-level component stripped” and “duplicate entry wins” semantics, but do so without unbounded allocations.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational
3. Changeset missing pnpm entry 📘 Rule violation § Compliance
Description
The new changeset only declares a bump for pacquet even though it describes a user-visible `pnpm
install behavior fix. This violates the requirement to explicitly include the pnpm` package with
an appropriate bump type in every changeset.
Code

.changeset/local-tarball-dependency-install.md[R1-3]

+---
+"pacquet": patch
+---
Relevance

⭐ Low

Similar “add pnpm to pacquet-only changeset” requests were repeatedly rejected in prior PRs.

PR-#13347
PR-#12981
PR-#13117

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
PR Compliance ID 713436 requires every added/modified changeset to explicitly list the pnpm
package with a valid bump type. The new changeset front-matter lists only pacquet, omitting
pnpm.

Rule 713436: Explicitly declare pnpm package and correct bump type in changesets
.changeset/local-tarball-dependency-install.md[1-3]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The changeset front-matter does not include an explicit entry for the `pnpm` package.

## Issue Context
This changeset text describes a `pnpm install` bug fix, and repository guidance requires that changesets always include `pnpm` explicitly with the correct bump type (`patch` for a bug fix).

## Fix Focus Areas
- .changeset/local-tarball-dependency-install.md[1-3]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit d559849 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Manifest parse error hidden ✓ Resolved 🐞 Bug ☼ Reliability
Description
read_bundled_manifest() swallows JSON parse errors for the tarball’s package.json and returns
None, even when the entry exists. For local file: tarballs this drops the only available
name/version source that the resolver uses to prefix the dep path (<name>@file:<path>) for
lockfile keying, obscuring the root cause.
Code

pnpm/crates/tarball/src/lib.rs[R2735-2737]

+        drop(components);
+        let bytes = tar_entry_payload(tar_data, &entry)?;
+        manifest = match parse_manifest_bytes(bytes) {
Relevance

⭐⭐⭐ High

Team has accepted preserving/propagating manifest read/parse errors instead of silently swallowing
them.

PR-#13404

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The tarball helper explicitly degrades an unparsable package.json to None, while the local
resolver tests state the bundled manifest is what enables the <name>@ prefix used for lockfile key
parsing.

pnpm/crates/tarball/src/lib.rs[2710-2747]
pnpm/crates/resolving-local-resolver/tests/resolve.rs[245-252]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`read_bundled_manifest()` currently treats an invalid `package.json` inside a tarball as a best-effort condition and clears the manifest to `None`. For local `file:` tarballs, that manifest is the only source of the package identity used to build `<name>@file:<path>` lockfile keys; silently dropping it makes failures harder to diagnose and can break resolution/lockfile output.

### Issue Context
- The resolver/test suite documents that the bundled manifest is required to prefix the dep path so a lockfile key can be parsed.
- The manifest parse failure is a strong signal of a corrupted/invalid tarball input and should surface as a clear error at resolution time.

### Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2710-2748]
- pnpm/crates/resolving-local-resolver/tests/resolve.rs[245-252]

### Suggested fix
- In `read_bundled_manifest()`, if a root `package.json` entry is found but `parse_manifest_bytes(...)` fails, return an error (new `TarballError` variant or reuse an appropriate existing one) that includes context (e.g., `file:` URL/path) instead of returning `None`.
- Keep `None` only for the “no root package.json entry found” case (if that is intended to be tolerated), but prefer a targeted diagnostic if local tarballs are expected to always contain it.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit e3ac44e ⚖️ Balanced


🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Non-object manifest bypasses error 🐞 Bug ≡ Correctness
Description
read_bundled_manifest() only maps JSON *parse* failures to TarballError::ParseBundledManifest;
if the bundled package.json is valid JSON but not a JSON object (e.g. null, string, array),
normalize_bundled_manifest() returns None and the resolver can fall back to the raw
file:<path> id again. This can recreate the “no lockfile key parseable” path for local tarballs
instead of failing fast with ERR_PNPM_TARBALL_EXTRACT.
Code

pnpm/crates/tarball/src/lib.rs[R2769-2773]

+    let Some(payload) = payload else { return Ok(None) };
+    let parsed = parse_manifest_bytes(payload).map_err(|source| {
+        TarballError::ParseBundledManifest { tarball: tarball_path.to_string(), source }
+    })?;
+    Ok(normalize_bundled_manifest(&parsed))
Relevance

⭐⭐⭐ High

Repo trend: don’t swallow manifest/parse anomalies; prefer fail-fast correctness hardening in
tarball/manifest paths.

PR-#13404
PR-#13059

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The resolve-time manifest reader normalizes non-object JSON to None, and the dep-id prefixing
logic explicitly returns the raw id when the manifest has no name, which is the same failure mode
this PR is trying to prevent for local file: tarballs.

pnpm/crates/tarball/src/lib.rs[2731-2773]
pnpm/crates/tarball/src/lib.rs[527-556]
pnpm/crates/package-manifest/src/lib.rs[852-867]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[3243-3259]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`read_bundled_manifest()` treats a present-but-non-object `package.json` as `None` (same as “missing manifest”), which can drop the package identity used to prefix `file:` tarball ids.

## Issue Context
`parse_manifest_bytes()` returns any `serde_json::Value` (not necessarily an object). `normalize_bundled_manifest()` returns `None` when the parsed value isn’t an object, so `read_bundled_manifest()` currently can’t distinguish “missing `package.json`” from “invalid shape `package.json`”. Downstream, when the manifest has no `name`, `build_pkg_id_with_patch_hash()` returns the raw id unchanged.

## Fix Focus Areas
- pnpm/crates/tarball/src/lib.rs[2769-2773]
- pnpm/crates/tarball/src/lib.rs[2736-2742]
- pnpm/crates/tarball/src/tests.rs[1354-1376]

## Suggested change
1. After parsing `payload`, require the manifest to be a JSON object for the resolve-time path; if it’s not an object, return an error with the same diagnostic code as `ParseBundledManifest` (either reuse `ParseBundledManifest` via a new error variant that doesn’t require `serde_json::Error`, or add a dedicated `InvalidBundledManifestShape` that maps to `ERR_PNPM_TARBALL_EXTRACT`).
2. Add a unit test that writes `package/package.json` as e.g. `null` or `"oops"` and asserts `read_local_tarball_metadata()` fails with the expected tarball error.

This preserves the intended behavior of tolerating *absence* of `package.json`, while rejecting a present-but-invalid manifest that would otherwise lose identity.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit 2b04f85 ⚖️ Balanced


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Action required
1. Tarball name not validated ✓ Resolved 🐞 Bug ⛨ Security
Description
bundled_package_name() only rejects empty names, so a tarball with an invalid npm name (e.g.
"evil@name") can be accepted and later used to prefix IDs (<name>@file:...), producing strings
that downstream parsers split on the first @ and can’t parse into lockfile keys. This can
reintroduce resolution/lockfile failures (or silent drops, depending on the downstream caller)
despite the new manifest read.
Code

pnpm/crates/resolving-local-resolver/src/local_resolver.rs[R350-352]

+fn bundled_package_name(manifest: Option<&serde_json::Value>) -> Option<&str> {
+    manifest?.get("name")?.as_str().filter(|name| !name.is_empty())
+}
Relevance

⭐⭐ Medium

Hardening is often accepted, but early npm-name validation was rejected (PR13353); no direct
local-tarball precedent found.

PR-#13353
PR-#13059
PR-#12864

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The resolver currently accepts any non-empty name from the bundled tarball manifest, but
downstream code prefixes IDs with that manifest name; lockfile-related parsing uses @ as a
structural delimiter, so invalid names with additional @ characters (or other invalid forms
rejected by pnpm’s validator) can break parsing and keying.

pnpm/crates/resolving-local-resolver/src/local_resolver.rs[218-231]
pnpm/crates/resolving-local-resolver/src/local_resolver.rs[350-356]
pnpm/crates/resolving-parse-wanted-dependency/src/validate_npm_package_name.rs[31-59]
pnpm/crates/resolving-deps-resolver/src/resolve_dependency_tree.rs[3243-3264]
pnpm/crates/lockfile/src/pkg_name_suffix.rs[48-77]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The local resolver treats any non-empty manifest `name` as usable (`bundled_package_name`), but pacquet later prefixes IDs with that name; invalid npm names containing `@` (not as a scope marker), whitespace, etc. can create dep paths / lockfile keys that downstream parsing splits incorrectly, recreating “unparseable key” failure modes.

## Issue Context
- The tarball’s manifest name is now consumed during resolution and becomes part of the package identity.
- The repo already has an npm-name validator (`is_valid_old_npm_package_name`) that mirrors pnpm’s JS behavior.

## Fix
1. Update `bundled_package_name()` to validate the string with `pacquet_resolving_parse_wanted_dependency::is_valid_old_npm_package_name` (or equivalent validation) instead of only checking `!is_empty()`.
2. When `has_manifest_entry == true` and the bundled name is missing *or invalid*, fail resolution with an explicit error (prefer `ERR_PNPM_INVALID_PACKAGE_NAME`; alternatively reuse `ERR_PNPM_MISSING_PACKAGE_NAME` if you must preserve the existing code path).
3. Add/extend a regression test that writes a tarball with a bundled manifest name like `"evil@name"` (or leading/trailing whitespace) and asserts the resolver fails early (before lockfile build).

## Fix Focus Areas
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[132-144]
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[218-227]
- pnpm/crates/resolving-local-resolver/src/local_resolver.rs[350-353]
- pnpm/crates/resolving-local-resolver/tests/resolve.rs[214-249]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@codecov-commenter

codecov-commenter commented Jul 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.72566% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.57%. Comparing base (5ed47dc) to head (e8bed10).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
pnpm/crates/tarball/src/lib.rs 81.08% 14 Missing ⚠️
...tes/resolving-local-resolver/src/local_resolver.rs 96.29% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #13409      +/-   ##
==========================================
+ Coverage   87.55%   87.57%   +0.02%     
==========================================
  Files         544      544              
  Lines       93464    93557      +93     
==========================================
+ Hits        81832    81937     +105     
+ Misses      11632    11620      -12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

zkochan added 2 commits July 27, 2026 01:10
`read_bundled_manifest` read `package.json` through the tar entry with
`read_to_end`, sizing a fresh allocation from the archive's own header.
The reader is seekable over an in-memory buffer, so the bytes are
already there: slice them instead, the way the extraction path beside it
already does.

Extract that offset/size arithmetic — which both call sites need, with
the same three bounds checks — into `tar_entry_payload`.

Defer the `build_packages_and_snapshots` hardening to its own change.
Erroring on a dep path that keys no lockfile row is only correct once
pacquet grows pnpm's `getManifestFromResponse` fallback: without it, a
tarball carrying no `package.json` at all — which pnpm installs as
`<alias>@file:<path>` with `version: 0.0.0` — would start failing
closed. Both halves are tracked in
#13410.

Drop the backward-looking prose from the new tests, per the review
guidance that a comment describes what the code asserts now.
Copilot AI review requested due to automatic review settings July 26, 2026 23:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

Thanks — responses to the three findings.

1. Historical comment in module header — fixed in d559849. The module doc was narrating implementation history and repeating what the test names and assertions already state; trimmed to the one non-obvious point (why the manifest is read at resolve time rather than at fetch time), and reworded the per-test prose to describe what is asserted now. Same finding as Greptile's.

2. Unbounded tarball inflate read — partly fixed in d559849.

The read_to_end half was real and is gone. read_bundled_manifest now borrows the payload out of the decompressed archive buffer via a new tar_entry_payload helper, so no allocation is sized from an entry header. That is what extract_tarball_entries beside it already did — my doc comment claimed the two followed the same conventions while the code did not, so this also removes a genuine inconsistency and a needless copy. The offset/size arithmetic and its three bounds checks are now shared by both call sites rather than duplicated.

The gzip-bomb half I have not bounded, deliberately. decompress_gzip(&buffer, None) here inflates exactly the same bytes that the install pass already inflates from the same file moments later — fetch_and_extract_once → extract_tarball_buffer → decompress_gzip — for any file: tarball the project declares. This change moves that work earlier in the same pnpm install; it does not add a decompression an untrusted repo could not already trigger. Note also that the unpacked_size parameter bounds only the eager buffer reservation (bounded_gzip_size_hint), and both paths grow on demand, so passing None is the conservative choice rather than a dropped limit. Capping only this call site would leave the actual exposure unchanged while reading as protection. A real bound belongs on the shared decompression path and applies to every tarball source, which is a larger change than this bug fix.

3. Changeset missing pnpm entry — declining. This is a false positive against this repository's convention. AGENTS.md states it explicitly:

Do not add "pnpm" to a Rust-only changeset: in changesets, pnpm always means the TypeScript CLI package. A changeset whose implementation is Rust-only and targets pacquet must omit "pnpm".

This PR is Rust-only — pnpm 11 already handles file: tarballs correctly — so "pacquet": patch alone is right. The finding itself notes the same request was rejected in #13347, #12981, and #13117; rule 713436 needs the Rust-only carve-out.


Written by an agent (Claude Code, claude-opus-5).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit d559849

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

A `file:` tarball's `package.json` is the only thing that names the
package, and the name is what gives its dep path the `<name>@` prefix a
lockfile key parses. Degrading an unparsable one to `None` — which is
right for the extraction path, where install-side consumers re-read from
disk — silently reproduces the bug this branch fixes: no `packages:` /
`snapshots:` row, and a dangling symlink off an install that exits 0.

pnpm rejects the same tarball with `ERR_PNPM_TARBALL_EXTRACT`
("Failed to add tarball from ... to store: <parse error>"), so raise the
matching code and message. An archive carrying no `package.json` at all
stays a tolerated shape, since pnpm installs that one.

Reported by Qodo on #13409.
Copilot AI review requested due to automatic review settings July 26, 2026 23:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 26, 2026

Copy link
Copy Markdown
Member Author

Re: Manifest parse error hidden — correct finding, fixed in 9b9d6d4.

I checked it against pnpm 11 before changing anything, with a tarball whose package.json is invalid JSON:

[ERR_PNPM_TARBALL_EXTRACT] Failed to add tarball from "/tmp/.../corrupt-pkg-1.0.0.tgz" to store: Expected double-quoted property name in JSON at position 23

pacquet, meanwhile, printed + corrupt-pkg file:corrupt-pkg-1.0.0.tgz and exited 0 over an empty packages: block — i.e. the degradation reproduced the exact bug this PR fixes, just from a corrupt manifest instead of an absent one. So it was a parity gap, not only a diagnostic one.

read_bundled_manifest now raises a new TarballError::ParseBundledManifest carrying pnpm's ERR_PNPM_TARBALL_EXTRACT code and message shape. It applies to the resolve-time read only — extract_tarball_entries keeps degrading to None, which is right there, since install-side consumers fall back to reading the file from disk. The doc comment now spells out why the two differ.

One case stays tolerated: an archive with no package.json at all still yields None rather than an error, because pnpm installs that one (synthesizing { name: <alias>, version: "0.0.0" }). pacquet has no equivalent of that fallback yet and drops the package — tracked separately in #13410, which is also why the build_packages_and_snapshots hardening was pulled out of this PR.

Both new behaviours have tests (read_local_tarball_metadata_rejects_an_unparsable_manifest, read_local_tarball_metadata_tolerates_an_archive_with_no_manifest).


Written by an agent (Claude Code, claude-opus-5).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
pnpm/crates/tarball/src/lib.rs (1)

2735-2750: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use regular comments only for the necessary internal invariant.

  • pnpm/crates/tarball/src/lib.rs#L2735-L2750: replace private-function rustdoc with a concise // invariant.
  • pnpm/crates/tarball/src/tests.rs#L1334-L1336: use a regular rationale comment or remove it.
  • pnpm/crates/tarball/src/tests.rs#L1354-L1356: use a regular rationale comment or remove it.
  • pnpm/crates/tarball/src/tests.rs#L1369-L1369: remove the helper’s behavior-narrating rustdoc.

As per coding guidelines, rustdoc is for public API contracts and regular comments are for implementation rationale; as per path instructions, comments must not narrate function bodies or duplicate test behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm/crates/tarball/src/lib.rs` around lines 2735 - 2750, Replace the
private-function rustdoc near the tarball entry extraction logic in
pnpm/crates/tarball/src/lib.rs:2735-2750 with a concise regular comment
containing only the necessary internal invariant. In
pnpm/crates/tarball/src/tests.rs:1334-1336 and 1354-1356, replace the rustdoc
with brief rationale comments or remove them; at
pnpm/crates/tarball/src/tests.rs:1369, remove the helper’s behavior-narrating
rustdoc. Do not alter function behavior or duplicate test implementation
details.

Sources: Coding guidelines, Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pnpm/crates/tarball/src/lib.rs`:
- Around line 2771-2774: Update the bundled manifest traversal around
parse_manifest_bytes and normalize_bundled_manifest to retain the payload of the
last matching package.json entry without parsing each entry immediately, then
parse and normalize only that final payload after traversal. Preserve
last-entry-wins behavior so malformed earlier duplicates do not fail when
superseded by a valid later entry, and add a regression test covering
malformed-then-valid duplicates.

---

Nitpick comments:
In `@pnpm/crates/tarball/src/lib.rs`:
- Around line 2735-2750: Replace the private-function rustdoc near the tarball
entry extraction logic in pnpm/crates/tarball/src/lib.rs:2735-2750 with a
concise regular comment containing only the necessary internal invariant. In
pnpm/crates/tarball/src/tests.rs:1334-1336 and 1354-1356, replace the rustdoc
with brief rationale comments or remove them; at
pnpm/crates/tarball/src/tests.rs:1369, remove the helper’s behavior-narrating
rustdoc. Do not alter function behavior or duplicate test implementation
details.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c70c2892-ca57-4532-bd1e-21277dfea269

📥 Commits

Reviewing files that changed from the base of the PR and between d559849 and 9b9d6d4.

📒 Files selected for processing (2)
  • pnpm/crates/tarball/src/lib.rs
  • pnpm/crates/tarball/src/tests.rs

Comment thread pnpm/crates/tarball/src/lib.rs Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 9b9d6d4

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

zkochan added 2 commits July 27, 2026 10:47
The test bound an ephemeral port, dropped it, and pointed the registry at
it, assuming nothing would claim it in between — its own comment conceded
the port was only "(very likely)" free. Under a full-workspace run the
suite's mockito servers bind ephemeral ports throughout, so the freed
port can be taken before the request goes out; the connect then succeeds
and the assertion fails. Seen once locally at 7323 tests.

Point it at port 0 instead, which is never a listening port, so the
connect is refused outright and the `is_connect()` branch is reached
deterministically.
Reading the bundled manifest puts the archive's own `name` into the dep
path and, from there, into a `node_modules/<name>` directory. An invalid
one breaks both: `evil@name` yields the dep path
`evil@name@file:<path>`, which parses back out as the unrelated package
`evil` and links a dangling symlink, while a traversal or reserved name
would place the package outside its slot.

pnpm refuses these with `ERR_PNPM_INVALID_DEPENDENCY_NAME`. Validate the
name with the repo's existing `is_valid_old_npm_package_name` — the same
rule `pacquet-lockfile-verification` applies to lockfile-controlled
names — before it reaches either consumer, and raise that code.

Reported by Qodo on #13409.
Copilot AI review requested due to automatic review settings July 27, 2026 08:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 27, 2026

Copy link
Copy Markdown
Member Author

Re: Tarball name not validated — real, and worse than "can't parse". Fixed in e8bed10.

Checked against pnpm 11 first. pnpm refuses both shapes with ERR_PNPM_INVALID_DEPENDENCY_NAME; pacquet split:

bundled name pnpm 11 pacquet (before)
" lead-space" ERR_PNPM_INVALID_DEPENDENCY_NAME already refused, same code
"evil@name" ERR_PNPM_INVALID_DEPENDENCY_NAME exit 0

The whitespace case was already caught downstream, which is why only the @ case slipped: pacquet-lockfile-verification validates key.name, and evil@name@file:bad-1.0.0.tgz parses as name evil — a valid name — with the rest folded into the version. So the install "succeeded":

packages:
  evil@name@file:bad-1.0.0.tgz:
    resolution: {integrity: sha512-..., tarball: file:bad-1.0.0.tgz}
    version: 1.0.0
node_modules/bad -> .pnpm/evil@name@file+bad-1.0.0.tgz/node_modules/evil

...a dangling symlink into a directory named after the mis-parsed name. And this PR is what makes it reachable — before it, a file: tarball's name was never read, so no attacker-controlled name entered the dep path.

bundled_package_name now validates with is_valid_old_npm_package_name, the same rule pacquet-lockfile-verification applies to lockfile-controlled names, and the resolver raises ERR_PNPM_INVALID_DEPENDENCY_NAME before the name reaches either the dep path or a node_modules directory. Covered for evil@name, " lead-space", "../escape", ".hidden", and "node_modules".

I also took CodeRabbit's adjacent request and added {"name": ""} to the nameless matrix — I confirmed pnpm rejects that one too, and that the case fails without the empty-string branch.

Full suite: 7324 passing.


Written by an agent (Claude Code, claude-opus-5).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit e8bed10

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@zkochan
zkochan merged commit 7befc73 into main Jul 27, 2026
35 checks passed
@zkochan
zkochan deleted the fix-13379 branch July 27, 2026 08:55
kairosci added a commit to kairosci/pnpm that referenced this pull request Jul 27, 2026
…cies (pnpm#13409)

A `file:*.tgz` dependency's name, version, and dependencies live only in
the archive's own `package.json`. The local resolver left `manifest`
unset for the tarball branch, so `build_pkg_id_with_patch_hash` had no
name to prefix and emitted the bare `file:<path>` as the dep path. That
parses as no lockfile key, and `build_packages_and_snapshots` dropped it
with a silent `continue` — the install reported success while writing no
`packages:` / `snapshots:` row and linking a dangling symlink into a
virtual-store directory that was never created.

Read the archive during resolution, as the tarball resolver already does
for remote tarballs and the git resolver for git deps: `pacquet-tarball`
grows `read_local_tarball_metadata`, which hashes the file and reads its
bundled `package.json` in one pass, replacing the resolver's hash-only
read. Nothing is written to the store — the install pass addresses a
`file:` tarball's store-index row by its `<name>@file:<path>` dep path,
not by the `<name>@<version>` a resolve-time extraction could key, so
such a row would never be read.

With the name in scope the dep path becomes `<name>@file:<path>`, both
lockfile blocks are emitted, the tarball's own dependencies are walked
(they were dropped entirely before), and the install summary prints the
version instead of the raw specifier. The lockfile is byte-identical to
pnpm 11's for the same manifest.

The manifest is borrowed out of the decompressed archive buffer rather
than read through the tar entry, so an entry header can't size an
allocation; the offset/size arithmetic both call sites need is extracted
into `tar_entry_payload`.

Reading the manifest puts its `name` into the dep path and into a
`node_modules/<name>` directory, so the shapes that used to fail
silently are refused the way pnpm refuses them: a `package.json` that
isn't valid JSON raises `ERR_PNPM_TARBALL_EXTRACT`, one that names no
package raises `ERR_PNPM_MISSING_PACKAGE_NAME`, and one whose name isn't
a valid npm name raises `ERR_PNPM_INVALID_DEPENDENCY_NAME`. Degrading to
"no manifest" is right for the extraction path, whose consumers re-read
from disk, but here the manifest is the package's only source of
identity, so clearing it reproduces the bug above.

An archive with no `package.json` at all stays tolerated, matching pnpm,
which synthesizes a name from the alias. Telling that apart from a
nameless manifest needs more than a `None`, so the reader reports
whether a root `package.json` was present.

pnpm 11 already handles `file:` tarballs correctly (it reads the manifest
from the fetch, and resolves and fetches together), so this needs no
TypeScript counterpart.

Closes pnpm#13379.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pacquet: local file: tarball dependencies are not installed and are missing from the lockfile

3 participants