Skip to content

feat(pacquet): add Node API bindings for the Rust engine - #12822

Merged
zkochan merged 10 commits into
mainfrom
node-api
Jul 7, 2026
Merged

zkochan merged 10 commits into
mainfrom
node-api

Conversation

@zkochan

@zkochan zkochan commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds @pnpm/napi, napi-rs bindings that expose pacquet's programmatic
engine surface to Node.js, so programmatic pnpm consumers can drive the Rust
engine instead of the TypeScript pnpm packages. Bit is the
reference consumer (it drives pnpm entirely through its programmatic API).

The binding is a new pacquet-napi cdylib crate plus an @pnpm/napi
npm wrapper. Exports — all verified end-to-end against a real registry:

  • install — in-memory importers (single project and multi-importer
    workspaces), a synchronous readPackage hook applied per resolved
    dependency manifest, build-script approval (allowBuilds /
    dangerouslyAllowAllBuilds / strictDepBuilds), and depsRequiringBuild.
  • rebuild, resolveDependency (npm registry), pack, parseBareSpecifier,
    engineVersion.
  • Auth via authHeaderByUri (pre-computed Authorization headers keyed by
    nerf-darted registry URI), applied through AuthHeaders::from_creds_map.

Engine-core changes are minimal and inert for existing callers:
PackageManifest::from_value (build an in-memory manifest without disk IO),
and two Option fields on Install (pnpmfile_hook_override,
workspace_projects_override) defaulted to None at every existing
construction site. A new napi-release profile sets panic = "unwind" — the
workspace release profile uses panic = "abort", which would abort the host
Node process on a panic that unwinds to the FFI boundary.

getPeerDependencyIssues is stubbed (ERR_PNPM_NAPI_UNIMPLEMENTED) pending
the peer-resolution issue renderer that pacquet's CLI has not ported yet.

Opening as a draft: this is the initial binding surface. getPeerDependencyIssues,
the cross-platform prebuild CI, and crate-level tests are follow-ups.

Squash Commit Body

Add `pacquet-napi`, a napi-rs cdylib crate, plus its `@pnpm/napi`
npm wrapper, exposing pacquet's programmatic engine surface to Node.js so
programmatic pnpm consumers can drive the Rust engine instead of the
TypeScript pnpm packages. Bit is the reference consumer.

Exports: install (in-memory importers, single and multi-importer workspaces,
a synchronous readPackage hook per resolved dependency manifest, build-script
approval, and depsRequiringBuild), rebuild, resolveDependency, pack,
parseBareSpecifier, engineVersion, and auth via authHeaderByUri.

The install runs on a dedicated 32 MiB-stack worker thread with its own
tokio runtime; the napi async fn awaits the result over a oneshot channel,
so pacquet's borrowed State never crosses the FFI boundary. A reporter
bridge forwards the engine's wire-compatible log events to a JS callback,
and errors carry pnpm's ERR_PNPM_* code and hint through a structured envelope.

Engine-core changes are minimal and inert for existing callers:
PackageManifest::from_value, and two Option fields on Install
(pnpmfile_hook_override and workspace_projects_override) defaulted to None
everywhere. A new napi-release profile sets panic = "unwind" since the
workspace release profile uses panic = "abort".

getPeerDependencyIssues is stubbed pending pacquet's own peer-issue renderer.
Distribution follows the @pnpm/exe.* model via scripts/generate-packages.mjs.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pacquet/ port, or the description notes what still needs porting. — Rust-only
    addition (a Node binding over pacquet); there is no TypeScript-CLI counterpart.
  • Added a changeset if this PR changes any published package. — Not needed:
    changesets track the TypeScript packages; this adds Rust crates and a new npm
    wrapper package, neither of which participates in the changeset flow.
  • Added or updated tests. — Verified end-to-end manually; crate-level tests
    are a follow-up.
  • Updated the documentation if needed. — Added pacquet/npm/napi/README.md
    and pacquet/plans/NAPI.md.

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

Summary by CodeRabbit

  • New Features
    • Added Node.js N-API bindings for install, rebuild, resolveDependency, pack, and specifier parsing, plus engineVersion.
    • Introduced @pnpm/napi with generated platform wrapper packages and improved native addon loading.
  • Bug Fixes
    • Better install compatibility: engineStrict and nodeVersion are honored during installability checks.
    • Added per-host socket limiting via maxSockets.
  • Documentation
    • Added @pnpm/napi README and TypeScript typings, including structured error details.

@coderabbitai

coderabbitai Bot commented Jul 6, 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

This PR adds the pacquet-napi Rust addon and @pnpm/napi wrapper, extends config and install plumbing for engineStrict, nodeVersion, and maxSockets, and updates the release workflow to build, package, and publish the native addon.

Changes

Pacquet N-API addon and supporting engine changes

Layer / File(s) Summary
Workspace and build setup
Cargo.toml, .gitignore, cspell.json, pacquet/crates/napi/*, pacquet/npm/napi/*, pacquet/plans/NAPI.md
Adds workspace dependency entries, build profile and ignore rules, the pacquet-napi crate, npm wrapper files, and the N-API implementation plan.
Config, network, and installability inputs
pacquet/crates/config/*, pacquet/crates/network/*, pacquet/crates/cli/src/state.rs, pacquet/crates/cli/src/config_deps.rs, pacquet/crates/package-manager/src/installability*, install_frozen_lockfile.rs, install_package_from_registry/tests.rs, package-manifest/src/*
Adds config fields and env/workspace parsing for engineStrict, nodeVersion, and maxSockets, plus per-origin socket caps and installability host detection honoring those values.
Install override plumbing
pacquet/crates/package-manager/src/install.rs, install_with_fresh_lockfile.rs, install/tests.rs, cli_args/*.rs, add.rs, remove.rs, update.rs, pnpr/.../resolve.rs
Adds pnpmfile_hook_override and workspace_projects_override to Install and InstallWithFreshLockfile, then threads None defaults through CLI and package-manager call sites.
N-API core bindings
pacquet/crates/napi/src/config.rs, error.rs, hooks.rs, reporter_bridge.rs, install.rs, pack.rs, resolve.rs, specifier.rs, lib.rs, napi_runtime_test_stubs.rs, and related tests
Adds config overlay caching, structured error conversion, pnpmfile/reporting bridges, install and rebuild entrypoints, and the pack, resolveDependency, and parseBareSpecifier bindings.
Release workflow build and publish
.github/workflows/pacquet-release-to-npm.yml
Updates the release workflow to cross-build the N-API addon, attest and upload the .node artifact, inject the napi package version, generate per-platform packages, and publish or stage the napi wrapper.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

  • pnpm/pnpm#11752: Both PRs wire MAX_SOCKETS/ENGINE_STRICT/NODE_VERSION through the config env-overlay/loading pipeline.
  • pnpm/pnpm#11760: Both PRs touch the new N-API resolver surface around resolveDependency and bare-specifier parsing.
  • pnpm/pnpm#12044: Both PRs build the pnpmfile hook bridge used by the N-API install path and the fresh-lockfile hook loading path.

Suggested labels: product: pacquet, product: pnpm@11

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

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.

@github-actions

github-actions Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
tarball/download_dependency    1.00      6.8±0.27ms   634.0 KB/sec    1.01      6.9±0.21ms   628.1 KB/sec

@codecov-commenter

codecov-commenter commented Jul 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 44.34612% with 566 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.80%. Comparing base (d1da02e) to head (034d839).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pacquet/crates/napi/src/install.rs 37.36% 228 Missing ⚠️
pacquet/crates/napi/src/resolve.rs 0.00% 95 Missing ⚠️
pacquet/crates/napi/src/config.rs 73.44% 64 Missing ⚠️
pacquet/crates/napi/src/reporter_bridge.rs 0.00% 63 Missing ⚠️
pacquet/crates/napi/src/pack.rs 0.00% 44 Missing ⚠️
pacquet/crates/napi/src/error.rs 46.80% 25 Missing ⚠️
pacquet/crates/napi/src/specifier.rs 0.00% 20 Missing ⚠️
pacquet/crates/napi/src/hooks.rs 0.00% 11 Missing ⚠️
pacquet/crates/napi/src/lib.rs 0.00% 4 Missing ⚠️
...tes/package-manager/src/install_frozen_lockfile.rs 60.00% 4 Missing ⚠️
... and 3 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #12822      +/-   ##
==========================================
- Coverage   86.33%   85.80%   -0.53%     
==========================================
  Files         438      448      +10     
  Lines       68355    69402    +1047     
==========================================
+ Hits        59013    59550     +537     
- Misses       9342     9852     +510     

☔ 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.

@github-actions

github-actions Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Integrated-Benchmark Report (Linux)

Commit: 77d7c19ca579

Each scenario reports direct installs and pnpr installs. Bencher consumes pacquet@HEAD and pnpr@HEAD.

Scenario: Isolated linker: fresh restore, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.057 ± 0.135 3.869 4.298 1.92 ± 0.12
pacquet@main 4.031 ± 0.108 3.888 4.233 1.91 ± 0.12
pnpr@HEAD 2.111 ± 0.116 1.967 2.263 1.00
pnpr@main 2.119 ± 0.140 1.956 2.348 1.00 ± 0.09
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.05734347558,
      "stddev": 0.1345689023633684,
      "median": 4.04742817118,
      "user": 3.7871572799999997,
      "system": 3.4593402999999996,
      "min": 3.86931277668,
      "max": 4.29776804968,
      "times": [
        4.21701946368,
        3.86931277668,
        3.89491797168,
        3.9867380266800003,
        4.04965974168,
        4.29776804968,
        3.98713930668,
        4.04519660068,
        4.14165753268,
        4.08402528568
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.03063980578,
      "stddev": 0.10843896524089566,
      "median": 4.01382364418,
      "user": 3.8165092799999996,
      "system": 3.4524209,
      "min": 3.8880071546800004,
      "max": 4.23318769468,
      "times": [
        4.00397968468,
        4.04776783768,
        4.03753264968,
        4.02366760368,
        3.9634773826800003,
        3.92411328968,
        4.19205818068,
        4.23318769468,
        3.8880071546800004,
        3.9926065796800003
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.1107243992800004,
      "stddev": 0.11560773503110784,
      "median": 2.1246834326800004,
      "user": 2.6484767799999998,
      "system": 2.9547665000000003,
      "min": 1.96700337868,
      "max": 2.2630599036800003,
      "times": [
        2.21850553768,
        2.2139861836800003,
        2.17319105868,
        2.00366884568,
        2.2050327866800004,
        2.01699472168,
        2.0761758066800002,
        1.96962576968,
        2.2630599036800003,
        1.96700337868
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.1192128179800003,
      "stddev": 0.14047291066660358,
      "median": 2.08802593418,
      "user": 2.70114158,
      "system": 2.9451559,
      "min": 1.95557095768,
      "max": 2.34844477268,
      "times": [
        1.96695247668,
        2.2659177876800003,
        1.97879151568,
        2.05752580968,
        2.16170720168,
        2.0825931516800003,
        2.34844477268,
        2.28116578968,
        1.95557095768,
        2.0934587166800003
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, hot cache + hot store

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 635.5 ± 9.1 624.8 651.9 1.00
pacquet@main 655.2 ± 26.0 635.8 725.0 1.03 ± 0.04
pnpr@HEAD 680.9 ± 19.6 656.8 723.4 1.07 ± 0.03
pnpr@main 717.8 ± 78.6 666.7 920.6 1.13 ± 0.12
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.63553022692,
      "stddev": 0.009063656462178918,
      "median": 0.6324075682200001,
      "user": 0.37498929999999997,
      "system": 1.31071114,
      "min": 0.62477620822,
      "max": 0.6519325612200001,
      "times": [
        0.62870090022,
        0.63112710522,
        0.6387349362200001,
        0.63038358922,
        0.64231391122,
        0.6468006402200001,
        0.62684438622,
        0.6336880312200001,
        0.6519325612200001,
        0.62477620822
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.65524605302,
      "stddev": 0.02595527089886496,
      "median": 0.64632139322,
      "user": 0.368042,
      "system": 1.3257245399999997,
      "min": 0.6358120632200001,
      "max": 0.7249836542200001,
      "times": [
        0.64279813222,
        0.6626429382200001,
        0.65561272522,
        0.6358120632200001,
        0.6432152272200001,
        0.6462720282200001,
        0.6569777592200001,
        0.7249836542200001,
        0.6377752442200001,
        0.6463707582200001
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6809412267200001,
      "stddev": 0.019573691957709357,
      "median": 0.67612480572,
      "user": 0.3844547,
      "system": 1.3387939399999997,
      "min": 0.6568155882200001,
      "max": 0.7233911752200001,
      "times": [
        0.6766824382200001,
        0.7008326422200001,
        0.7233911752200001,
        0.6644058592200001,
        0.6903448982200001,
        0.67424024122,
        0.67556717322,
        0.6662894782200001,
        0.6808427732200001,
        0.6568155882200001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.7178216932200001,
      "stddev": 0.0785658778512738,
      "median": 0.6904137262200001,
      "user": 0.40047390000000005,
      "system": 1.33769474,
      "min": 0.66669970722,
      "max": 0.9205901952200001,
      "times": [
        0.78265355422,
        0.67444104122,
        0.6670501242200001,
        0.66669970722,
        0.6861895102200001,
        0.6995963502200001,
        0.70016899722,
        0.69317770022,
        0.6876497522200001,
        0.9205901952200001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + cold store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 4.187 ± 0.054 4.124 4.276 1.96 ± 0.05
pacquet@main 4.193 ± 0.047 4.105 4.263 1.97 ± 0.05
pnpr@HEAD 2.131 ± 0.045 2.054 2.200 1.00
pnpr@main 2.198 ± 0.119 2.051 2.351 1.03 ± 0.06
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 4.18663558998,
      "stddev": 0.05411648246209384,
      "median": 4.17402090308,
      "user": 3.6978597800000004,
      "system": 3.3281357999999996,
      "min": 4.12416036658,
      "max": 4.27645982358,
      "times": [
        4.12416036658,
        4.134917962579999,
        4.27645982358,
        4.14077381958,
        4.25333601158,
        4.1808103675799995,
        4.16723143858,
        4.1420341575799995,
        4.2174768045799995,
        4.22915514758
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 4.192696603180001,
      "stddev": 0.04652669829741994,
      "median": 4.19480765058,
      "user": 3.7156830800000007,
      "system": 3.3515856,
      "min": 4.1052224075799995,
      "max": 4.26307272758,
      "times": [
        4.23051743158,
        4.14026114458,
        4.16889296658,
        4.22141181758,
        4.1052224075799995,
        4.26307272758,
        4.2013178795799995,
        4.18209531358,
        4.22587692158,
        4.18829742158
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 2.13061360648,
      "stddev": 0.045278124759401336,
      "median": 2.1378460375799997,
      "user": 2.48568448,
      "system": 2.8695713999999994,
      "min": 2.05443417958,
      "max": 2.19980061358,
      "times": [
        2.09859676058,
        2.19980061358,
        2.1620117675799997,
        2.1407800465799998,
        2.0772729815799997,
        2.05443417958,
        2.1664539285799997,
        2.16370060458,
        2.1081731535799997,
        2.1349120285799996
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 2.19785543368,
      "stddev": 0.11925440422687585,
      "median": 2.13836338558,
      "user": 2.52344358,
      "system": 2.8728907,
      "min": 2.05142152958,
      "max": 2.3512059335799997,
      "times": [
        2.14593026458,
        2.13079650658,
        2.10908544558,
        2.32990329258,
        2.34240672758,
        2.30813044558,
        2.3512059335799997,
        2.1139174115799997,
        2.05142152958,
        2.09575677958
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, hot cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 1.394 ± 0.011 1.372 1.413 2.14 ± 0.04
pacquet@main 1.344 ± 0.056 1.313 1.499 2.07 ± 0.09
pnpr@HEAD 0.666 ± 0.035 0.638 0.760 1.02 ± 0.06
pnpr@main 0.650 ± 0.009 0.637 0.670 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 1.39403483826,
      "stddev": 0.011177542901806413,
      "median": 1.3943470857600002,
      "user": 1.32016714,
      "system": 1.76095654,
      "min": 1.37230215226,
      "max": 1.41298634326,
      "times": [
        1.40114060426,
        1.40186618526,
        1.40013541026,
        1.38932363826,
        1.3890438552600002,
        1.3848560222600002,
        1.41298634326,
        1.37230215226,
        1.3968348702600002,
        1.39185930126
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 1.3439936619600001,
      "stddev": 0.05591085864249957,
      "median": 1.3244456902600001,
      "user": 1.27624654,
      "system": 1.6887020400000001,
      "min": 1.31271596226,
      "max": 1.4993974312600002,
      "times": [
        1.32120351926,
        1.31581190126,
        1.4993974312600002,
        1.32834796526,
        1.31923150426,
        1.3234083012600002,
        1.3422961662600001,
        1.32548307926,
        1.3520407892600002,
        1.31271596226
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.66642464716,
      "stddev": 0.0352614607273923,
      "median": 0.66123399126,
      "user": 0.34135924000000006,
      "system": 1.27681714,
      "min": 0.63779733026,
      "max": 0.7602331262600001,
      "times": [
        0.64003192126,
        0.63779733026,
        0.66233312126,
        0.64797179726,
        0.66794570026,
        0.67538178826,
        0.7602331262600001,
        0.66585488826,
        0.66013486126,
        0.64656193726
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.65022413206,
      "stddev": 0.009306622192104328,
      "median": 0.65003818426,
      "user": 0.33540594,
      "system": 1.2717473400000001,
      "min": 0.63662277426,
      "max": 0.67010706626,
      "times": [
        0.65035128726,
        0.64972508126,
        0.65704448026,
        0.65254046126,
        0.65056302226,
        0.67010706626,
        0.64933465526,
        0.63662277426,
        0.63844449826,
        0.64750799426
      ]
    }
  ]
}

Scenario: Isolated linker: fresh install, cold cache + hot store

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 3.003 ± 0.067 2.966 3.183 4.55 ± 0.12
pacquet@main 2.977 ± 0.023 2.949 3.014 4.51 ± 0.07
pnpr@HEAD 0.659 ± 0.008 0.644 0.671 1.00
pnpr@main 0.672 ± 0.088 0.634 0.923 1.02 ± 0.13
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 3.00333344524,
      "stddev": 0.06685146316522365,
      "median": 2.9750204932399997,
      "user": 1.7467357800000003,
      "system": 1.9245064399999996,
      "min": 2.96556808974,
      "max": 3.18300972874,
      "times": [
        2.97960973174,
        2.99602795374,
        2.97290579974,
        2.96556808974,
        2.97322217274,
        2.97639654474,
        2.97156950174,
        3.04138048774,
        3.18300972874,
        2.97364444174
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 2.97658499584,
      "stddev": 0.0230064293360391,
      "median": 2.97146157874,
      "user": 1.7069619799999998,
      "system": 1.9624037400000003,
      "min": 2.94891271074,
      "max": 3.01422662374,
      "times": [
        2.99203159074,
        2.96495325774,
        2.98265480774,
        3.01007378374,
        2.95718436874,
        3.01422662374,
        2.96374198674,
        2.97796989974,
        2.95410092874,
        2.94891271074
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.6593567690400001,
      "stddev": 0.008479247040805705,
      "median": 0.6603834552400001,
      "user": 0.33814108000000004,
      "system": 1.2955933400000001,
      "min": 0.6442496777400001,
      "max": 0.6714347027400001,
      "times": [
        0.6590467227400001,
        0.6525381247400001,
        0.6442496777400001,
        0.6714347027400001,
        0.6674315287400001,
        0.6584018687400001,
        0.6651739887400001,
        0.6494497387400001,
        0.6641211497400001,
        0.6617201877400001
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.67239194144,
      "stddev": 0.08830128566260305,
      "median": 0.6462278667400001,
      "user": 0.33014917999999993,
      "system": 1.2638555399999998,
      "min": 0.6338206997400001,
      "max": 0.9233845497400001,
      "times": [
        0.6460890327400001,
        0.6473782247400001,
        0.6399746277400001,
        0.6487697217400001,
        0.6460583347400001,
        0.6338206997400001,
        0.64723262274,
        0.64484489974,
        0.6463667007400001,
        0.9233845497400001
      ]
    }
  ]
}

Scenario: Isolated linker: fresh resolve, hot cache, offline

Command Mean [ms] Min [ms] Max [ms] Relative
pacquet@HEAD 619.7 ± 6.7 604.7 627.3 5.99 ± 0.10
pacquet@main 624.2 ± 7.8 615.7 640.7 6.04 ± 0.11
pnpr@HEAD 105.0 ± 2.7 102.5 112.9 1.02 ± 0.03
pnpr@main 103.4 ± 1.3 102.3 107.9 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 0.6196547169400001,
      "stddev": 0.006708951188543079,
      "median": 0.6206488805400001,
      "user": 0.5860257600000001,
      "system": 0.1476829,
      "min": 0.6046671785400001,
      "max": 0.62728117454,
      "times": [
        0.62519762054,
        0.62214457054,
        0.62728117454,
        0.6046671785400001,
        0.6154485725400001,
        0.61910378954,
        0.61992375854,
        0.6151285055400001,
        0.62627799654,
        0.6213740025400001
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 0.62415632114,
      "stddev": 0.007840220097275068,
      "median": 0.62219884454,
      "user": 0.5882787599999999,
      "system": 0.1535174,
      "min": 0.6157360015400001,
      "max": 0.64066869754,
      "times": [
        0.61598226854,
        0.62237470654,
        0.6340736435400001,
        0.62557217054,
        0.6192972035400001,
        0.6157360015400001,
        0.64066869754,
        0.62090733054,
        0.62492820654,
        0.62202298254
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 0.10500114790000001,
      "stddev": 0.0027138282918882164,
      "median": 0.10337601354,
      "user": 0.02762,
      "system": 0.017826199999999997,
      "min": 0.10251142254000001,
      "max": 0.11292324354000001,
      "times": [
        0.10698620354,
        0.10449910454000001,
        0.10676294354,
        0.10286465054,
        0.10337601354,
        0.10316790554000001,
        0.10826106454000001,
        0.11292324354000001,
        0.10282759154,
        0.10301984954,
        0.10325220254,
        0.10785670154,
        0.10351990954000001,
        0.10731068354000001,
        0.10339557854,
        0.10326428454,
        0.10815778254000001,
        0.10809932354,
        0.10773097754000001,
        0.10251142254000001,
        0.10332295354000001,
        0.10299714754,
        0.10312317154,
        0.10313432254,
        0.10266366554
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 0.10340133350296297,
      "stddev": 0.0012867605733497074,
      "median": 0.10306539354000001,
      "user": 0.02589974518518519,
      "system": 0.01912738518518518,
      "min": 0.10229060054000001,
      "max": 0.10791486954,
      "times": [
        0.10235313854,
        0.10326122854,
        0.10337170454000001,
        0.10229060054000001,
        0.10341907354,
        0.10253238054000001,
        0.10301625254,
        0.10401980254000001,
        0.10713750154000001,
        0.10293343754,
        0.10316328654000001,
        0.10323581154,
        0.10791486954,
        0.10247749954,
        0.10458766054,
        0.10311095954,
        0.10266079954,
        0.10339696254000001,
        0.10291450354000001,
        0.10267810354000001,
        0.10331557054000001,
        0.10293037254000001,
        0.10328592554,
        0.10306539354000001,
        0.10269701754,
        0.10302231354000001,
        0.10304383454
      ]
    }
  ]
}

Scenario: Isolated linker: fresh restore, cold cache + cold store + cold pnpr

Command Mean [s] Min [s] Max [s] Relative
pacquet@HEAD 6.934 ± 0.208 6.620 7.320 1.41 ± 0.05
pacquet@main 6.853 ± 0.182 6.575 7.164 1.39 ± 0.05
pnpr@HEAD 4.963 ± 0.086 4.851 5.136 1.01 ± 0.03
pnpr@main 4.924 ± 0.100 4.743 5.097 1.00
BENCHMARK_REPORT.json
{
  "results": [
    {
      "command": "pacquet@HEAD",
      "mean": 6.93371765148,
      "stddev": 0.20775854683955144,
      "median": 6.89478596988,
      "user": 3.9452701599999997,
      "system": 3.7022436999999995,
      "min": 6.62027061438,
      "max": 7.31994166238,
      "times": [
        7.09698608538,
        7.31994166238,
        6.80805890238,
        6.95996713038,
        6.62027061438,
        6.77336337438,
        6.81045245838,
        6.97368880238,
        6.82960480938,
        7.1448426753800005
      ]
    },
    {
      "command": "pacquet@main",
      "mean": 6.8531805640800005,
      "stddev": 0.18167745404177602,
      "median": 6.83630195288,
      "user": 3.9942839599999993,
      "system": 3.7423732999999992,
      "min": 6.57496316938,
      "max": 7.16372589038,
      "times": [
        6.75566195238,
        7.16372589038,
        6.81070292638,
        6.97178106538,
        6.805860543380001,
        6.8619009793800005,
        7.07960108638,
        6.86449224438,
        6.64311578338,
        6.57496316938
      ]
    },
    {
      "command": "pnpr@HEAD",
      "mean": 4.96338151468,
      "stddev": 0.08649939989394992,
      "median": 4.94940351588,
      "user": 2.72583366,
      "system": 3.1891845000000005,
      "min": 4.8510920973800005,
      "max": 5.13647137138,
      "times": [
        5.03231712338,
        5.13647137138,
        4.8995730573800005,
        5.03851630538,
        4.96392325038,
        4.89633248338,
        4.8510920973800005,
        4.98469696438,
        4.93488378138,
        4.8960087123800005
      ]
    },
    {
      "command": "pnpr@main",
      "mean": 4.92382904918,
      "stddev": 0.0996828083384531,
      "median": 4.92749943538,
      "user": 2.76827856,
      "system": 3.192608800000001,
      "min": 4.74273004638,
      "max": 5.0972808583800004,
      "times": [
        4.85383219438,
        5.0972808583800004,
        4.74273004638,
        4.8794370353800005,
        4.967950661380001,
        4.92161325638,
        4.96195748238,
        4.93338561438,
        5.02852283138,
        4.85158051138
      ]
    }
  ]
}

@github-actions

github-actions Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12822
Testbedpacquet
Click to view all benchmark results
BenchmarkLatencyBenchmark Result
milliseconds (ms)
(Result Δ%)
Upper Boundary
milliseconds (ms)
(Limit %)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
🚷 view threshold
4,186.64 ms
(-0.75%)Baseline: 4,218.19 ms
5,061.83 ms
(82.71%)
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
🚷 view threshold
3,003.33 ms
(-0.18%)Baseline: 3,008.68 ms
3,610.41 ms
(83.19%)
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
🚷 view threshold
1,394.03 ms
(+4.70%)Baseline: 1,331.45 ms
1,597.74 ms
(87.25%)
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
🚷 view threshold
619.65 ms
(-1.49%)Baseline: 629.03 ms
754.84 ms
(82.09%)
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
🚷 view threshold
4,057.34 ms
(+2.11%)Baseline: 3,973.38 ms
4,768.05 ms
(85.09%)
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
🚷 view threshold
6,933.72 ms
(+1.94%)Baseline: 6,801.61 ms
8,161.93 ms
(84.95%)
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
🚷 view threshold
635.53 ms
(+0.79%)Baseline: 630.57 ms
756.69 ms
(83.99%)
🐰 View full continuous benchmarking report in Bencher

@github-actions

github-actions Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

🐰 Bencher Report

Branchpr/12822
Testbedpnpr

⚠️ WARNING: No Threshold found!

Without a Threshold, no Alerts will ever be generated.

Click here to create a new Threshold
For more information, see the Threshold documentation.
To only post results if a Threshold exists, set the --ci-only-thresholds flag.

Click to view all benchmark results
BenchmarkLatencymilliseconds (ms)
isolated-linker.fresh-install.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,130.61 ms
isolated-linker.fresh-install.cold-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
659.36 ms
isolated-linker.fresh-install.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
666.42 ms
isolated-linker.fresh-resolve.hot-cache.offline📈 view plot
⚠️ NO THRESHOLD
105.00 ms
isolated-linker.fresh-restore.cold-cache.cold-store📈 view plot
⚠️ NO THRESHOLD
2,110.72 ms
isolated-linker.fresh-restore.cold-cache.cold-store.cold-pnpr📈 view plot
⚠️ NO THRESHOLD
4,963.38 ms
isolated-linker.fresh-restore.hot-cache.hot-store📈 view plot
⚠️ NO THRESHOLD
680.94 ms
🐰 View full continuous benchmarking report in Bencher

@zkochan
zkochan force-pushed the node-api branch 2 times, most recently from 460472f to 17e4eed Compare July 6, 2026 14:50
zkochan added a commit that referenced this pull request Jul 6, 2026
Wire the install options the @pnpm/napi binding previously rejected with
ERR_PNPM_NAPI_UNSUPPORTED_OPTION through the Rust engine (Closes #12823,
stacked on #12822). Only authConfig (use authHeaderByUri) and
neverBuiltDependencies remain rejected.

- update/depth: update:true selects UpdateSeedPolicy::DropAll (whole-graph
  re-resolve to highest-in-range) and forces the non-frozen path; depth is a
  no-op toggle without package selectors.
- engineStrict/nodeVersion: two new pacquet_config::Config fields (also parsed
  from pnpm-workspace.yaml / config.yaml / PNPM_CONFIG_*), threaded into
  InstallabilityHost on both install paths via a new detect_with. An explicit
  nodeVersion is authoritative (no node --version probe). Defaults unchanged.
- maxSockets: a per-origin concurrent-connection cap on ThrottledClient
  (with_max_sockets_per_host), mirroring undici's per-origin connections; the
  global networkConcurrency semaphore stays the outer bound.
- enableModulesDir:false maps to the lockfile-only path (no node_modules).
- ignorePackageManifest maps to ignore_manifest_check (skip the freshness gate);
  the project-linking skip (pnpm fetch semantics) is a documented follow-up.
- pnpmHomeDir is accepted and ignored (only global flows consult it).
zkochan added a commit that referenced this pull request Jul 6, 2026
Wire the install options the @pnpm/napi binding previously rejected with
ERR_PNPM_NAPI_UNSUPPORTED_OPTION through the Rust engine (Closes #12823,
stacked on #12822). Only authConfig (use authHeaderByUri) and
neverBuiltDependencies remain rejected.

- update/depth: update:true selects UpdateSeedPolicy::DropAll (whole-graph
  re-resolve to highest-in-range) and forces the non-frozen path; depth is a
  no-op toggle without package selectors.
- engineStrict/nodeVersion: two new pacquet_config::Config fields (also parsed
  from pnpm-workspace.yaml / config.yaml / PNPM_CONFIG_*), threaded into
  InstallabilityHost on both install paths via a new detect_with. An explicit
  nodeVersion is authoritative (no node --version probe). Defaults unchanged.
- maxSockets: a per-origin concurrent-connection cap on ThrottledClient
  (with_max_sockets_per_host), mirroring undici's per-origin connections; the
  global networkConcurrency semaphore stays the outer bound.
- enableModulesDir:false maps to the lockfile-only path (no node_modules).
- ignorePackageManifest maps to ignore_manifest_check (skip the freshness gate);
  the project-linking skip (pnpm fetch semantics) is a documented follow-up.
- pnpmHomeDir is accepted and ignored (only global flows consult it).
zkochan added 3 commits July 6, 2026 23:46
Add `pacquet-napi`, a napi-rs cdylib crate, plus its `@pnpm/napi`
npm wrapper, exposing pacquet's programmatic engine surface to Node.js so
programmatic pnpm consumers can drive the Rust engine instead of the
TypeScript pnpm packages. Bit is the reference consumer.

Exports (all verified end-to-end against a real registry):
- `install` — in-memory importers (single project and multi-importer
  workspaces), a synchronous `readPackage` hook applied per resolved
  dependency manifest, build-script approval (`allowBuilds` /
  `dangerouslyAllowAllBuilds` / `strictDepBuilds`), and `depsRequiringBuild`
  reporting.
- `rebuild`, `resolveDependency` (npm registry), `pack`,
  `parseBareSpecifier`, `engineVersion`.
- Auth via `authHeaderByUri` (pre-computed `Authorization` headers keyed by
  nerf-darted registry URI), applied through `AuthHeaders::from_creds_map`.

The install runs on a dedicated 32 MiB-stack worker thread with its own
tokio runtime; the napi async fn awaits the result over a oneshot channel,
so pacquet's borrowed `State` never crosses the FFI boundary. A reporter
bridge forwards the engine's wire-compatible log events to a JS callback,
and errors carry pnpm's `ERR_PNPM_*` code and hint through a structured
envelope.

Engine-core changes are minimal and inert for existing callers:
`PackageManifest::from_value` (build an in-memory manifest without disk
IO), and two `Option` fields on `Install` — `pnpmfile_hook_override` (an
embedder-supplied `readPackage` hook, preferred over the on-disk pnpmfile
on the fresh-resolve path) and `workspace_projects_override` (supply
importers in memory instead of discovering them from a `pnpm-workspace.yaml`)
— both defaulted to `None` at every existing construction site.

A new `napi-release` build profile inherits `release` but sets
`panic = "unwind"`, since the workspace `release` profile uses
`panic = "abort"`, which would abort the host Node process on a panic that
unwinds to the FFI boundary.

Not yet implemented: `getPeerDependencyIssues` returns
`ERR_PNPM_NAPI_UNIMPLEMENTED`; it needs the peer-resolution issue
renderer that pacquet's own CLI has not ported yet.

Distribution follows the `@pnpm/exe.*` model: `scripts/generate-packages.mjs`
builds the per-platform `@pnpm/napi.<target>` prebuilt packages and
wires them as the wrapper's optional dependencies.
Wire the install options the `@pnpm/napi` binding previously rejected with
ERR_PNPM_NAPI_UNSUPPORTED_OPTION through the Rust engine (Closes #12823,
stacked on #12822). Only authConfig (use authHeaderByUri) and
neverBuiltDependencies remain rejected.

- update/depth: update:true selects UpdateSeedPolicy::DropAll (whole-graph
  re-resolve to highest-in-range) and forces the non-frozen path; depth is a
  no-op toggle without package selectors.
- engineStrict/nodeVersion: two new pacquet_config::Config fields (also parsed
  from pnpm-workspace.yaml / config.yaml / PNPM_CONFIG_*), threaded into
  InstallabilityHost on both install paths via a new detect_with. An explicit
  nodeVersion is authoritative (no node --version probe). Defaults unchanged.
- maxSockets: a per-origin concurrent-connection cap on ThrottledClient
  (with_max_sockets_per_host), mirroring undici's per-origin connections; the
  global networkConcurrency semaphore stays the outer bound.
- enableModulesDir:false maps to the lockfile-only path (no node_modules).
- ignorePackageManifest maps to ignore_manifest_check (skip the freshness gate);
  the project-linking skip (pnpm fetch semantics) is a documented follow-up.
- pnpmHomeDir is accepted and ignored (only global flows consult it).
@zkochan
zkochan marked this pull request as ready for review July 6, 2026 21:59
Copilot AI review requested due to automatic review settings July 6, 2026 21:59

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.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Grey Divider


Action required

1. Per-call Tokio runtime ✓ Resolved 🐞 Bug ⛨ Security
Description
resolveDependency constructs a new multi-thread Tokio runtime for every call, which can spawn
multiple worker threads per invocation and amplify resource usage under concurrent resolves. In
long-lived Node hosts, repeated/parallel resolves can exhaust threads/memory and effectively DoS the
process.
Code

pacquet/crates/napi/src/resolve.rs[R147-157]

+    let runtime =
+        tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|error| {
+            napi::Error::from_reason(format!("failed to build tokio runtime: {error}"))
+        })?;
+
+    let resolved = runtime
+        .block_on(async { resolver.resolve(&wanted_dependency, &resolve_options).await })
+        // `Resolver::resolve` erases its error to `ResolveError`
+        // (`Box<dyn Error>`), so the underlying miette `Diagnostic` — and its
+        // `ERR_PNPM_*` code / hint — is already gone by the time it reaches
+        // here; only the message survives. Restoring the code on this path
Evidence
The N-API resolveDependency path spawns a thread per call and then builds a new **multi-thread**
Tokio runtime inside run_resolve_blocking. Elsewhere in-repo, spawned-thread runtimes commonly use
new_current_thread(), demonstrating an established lighter-weight pattern.

pacquet/crates/napi/src/resolve.rs[63-160]
pacquet/crates/testing-utils/src/registry.rs[65-74]
pacquet/crates/napi/src/install.rs[331-334]

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

## Issue description
`resolveDependency` creates a fresh `tokio::runtime::Builder::new_multi_thread()` runtime for each call. Combined with per-call worker threads, this can multiply thread creation and memory use under concurrency.
## Issue Context
This code runs inside a Node addon in long-lived processes; consumers may call `resolveDependency` frequently and concurrently.
## Fix Focus Areas
- Prefer a lighter runtime per worker thread (e.g. `new_current_thread()`), or reuse a shared runtime via `OnceLock`/`LazyLock`.
- Avoid creating a new multi-thread runtime per call unless you explicitly configure and justify the worker thread count.
- pacquet/crates/napi/src/resolve.rs[63-160]
- pacquet/crates/napi/src/install.rs[331-334]

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


2. Musl detection fallback wrong ✓ Resolved 🐞 Bug ☼ Reliability
Description
On Linux, @pnpm/napi treats any failure to read process.report as “not musl”, which forces the
non-"-musl" triple and can make addon loading fail on musl hosts where process.report is
unavailable/throws. This prevents the Rust engine from initializing even when the correct
@pnpm/napi.<triple>-musl optionalDependency is installed.
Code

pacquet/npm/napi/index.js[R17-29]

+function platformTriple() {
+  const { platform, arch } = process
+  if (platform === 'linux') {
+    const isMusl = (() => {
+      try {
+        const report = process.report?.getReport()
+        return !report?.header?.glibcVersionRuntime
+      } catch {
+        return false
+      }
+    })()
+    return `linux-${arch}${isMusl ? '-musl' : ''}`
+  }
Evidence
The new loader returns false on any exception in the musl probe, which deterministically selects
the non-musl triple. The existing pnpm wrapper shows the intended pattern: treat process.report
unavailability as “unknown” rather than defaulting to glibc.

pacquet/npm/napi/index.js[17-29]
pacquet/npm/pnpm/install.js[163-174]

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

## Issue description
`pacquet/npm/napi/index.js` computes the Linux package triple with a musl probe based on `process.report?.getReport()`. When that probe throws/unavailable, the code currently falls back to `false` (interpreted as glibc), which makes the loader require `@pnpm/napi.linux-<arch>` even on musl.
### Issue Context
The existing pnpm wrapper handles `process.report` unavailability by returning an “unknown” value and still allowing the musl variant to be selected, rather than assuming glibc.
### Fix Focus Areas
- pacquet/npm/napi/index.js[17-31]
### Suggested fix
Change Linux loading to avoid a hard glibc default when musl detection is unavailable. For example:
- Make musl detection tri-state (`'musl' | 'glibc' | null`) like `pacquet/npm/pnpm/install.js`, and when `null`, attempt both candidates:
- `@pnpm/napi.linux-${arch}-musl`
- `@pnpm/napi.linux-${arch}`
(and similarly for local artifact filenames if you support them).
This keeps the loader robust when `process.report` is missing/disabled while preserving the fast path when libc can be detected.

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


3. Default-port origin bypass 🐞 Bug ⛨ Security
Description
origin_of() keys per-origin semaphores using parsed.port(), so https://host and
https://host:443 (and http://host vs http://host:80) become distinct buckets, weakening
maxSockets and allowing more concurrent sockets than configured. Because tarball/metadata URLs are
registry-controlled, a hostile/misconfigured registry can vary explicit default ports to bypass the
cap and increase FD/socket pressure.
Code

pacquet/crates/network/src/lib.rs[R174-183]

+/// The `scheme://host[:port]` origin of `url`, or `None` when it has no host.
+/// The port is included so `https://host` and `https://host:8443` are treated
+/// as distinct origins (matching undici's per-origin keying).
+fn origin_of(url: &str) -> Option<String> {
+    let parsed = reqwest::Url::parse(url).ok()?;
+    let host = parsed.host_str()?;
+    Some(match parsed.port() {
+        Some(port) => format!("{}://{host}:{port}", parsed.scheme()),
+        None => format!("{}://{host}", parsed.scheme()),
+    })
Evidence
The per-origin key is built from scheme://host[:port] and uses parsed.port() directly, which
returns Some(443) when a URL explicitly includes :443, producing a different key than the
implicit-default form. This makes logically identical origins land in different semaphore buckets,
weakening the cap’s effectiveness.

pacquet/crates/network/src/lib.rs[174-183]

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

## Issue description
`origin_of()` treats explicit default ports as distinct origins (e.g. `https://h` vs `https://h:443`), which weakens the `maxSockets` per-origin concurrency guarantee.
## Issue Context
This origin string is used as the key for the per-origin semaphore map in `HostSocketLimit`, so origin-key fragmentation directly translates to extra semaphore buckets and higher-than-configured concurrency.
## Fix Focus Areas
- Normalize default ports (80/443) so explicit default ports do not create a new origin bucket.
- Add unit tests covering default-port normalization.
### Suggested implementation sketch
- Use `Url::port_or_known_default()` to compute the effective port.
- Include the port in the origin key only when it is non-default for the scheme (or when the scheme has no known default).
## Fix Focus Areas (paths/lines)
- pacquet/crates/network/src/lib.rs[174-183]
- pacquet/crates/network/src/tests.rs[794-808]

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


View more (24)
4. Unbounded leaked config cache 🐞 Bug ⛨ Security
Description
resolve_config() leaks a new &'static Config on every cache miss and stores it in a process-global
DashMap with no eviction, so unique dir/overlay inputs permanently grow memory in long-lived Node
hosts. Callers that vary overlays (e.g., authHeaderByUri/registries/network settings per
request/tenant) can trigger memory-DoS and eventual OOM.
Code

pacquet/crates/napi/src/config.rs[R217-224]

+    let key = cache_key(dir, overlay);
+    if let Some(config) = config_cache().get(&key) {
+        return Ok(*config);
+    }
+    let config = build_config(dir, overlay)?;
+    let leaked: &'static Config = config.leak();
+    config_cache().insert(key, leaked);
+    Ok(leaked)
Evidence
The N-API config interning cache stores leaked &'static Config values in a process-global map and
never evicts them; overlays are built directly from caller-supplied install options, so varied
inputs are realistic in programmatic/long-lived usage.

pacquet/crates/napi/src/config.rs[118-224]
pacquet/crates/napi/src/install.rs[441-497]

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

## Issue description
`resolve_config()` permanently leaks a `Config` on every cache miss (`Config::leak()`), and the cache is never evicted. In a long-lived Node process, varying inputs (dir/overlay/config sources) can create unbounded retained memory and enable a practical DoS via repeated calls with unique options.
### Issue Context
pacquet’s engine currently requires `&'static Config`, pushing the binding to leak configs. The current interning approach only de-duplicates identical inputs; it does not prevent growth when inputs vary.
### Fix Focus Areas
- pacquet/crates/napi/src/config.rs[118-224]
- pacquet/crates/napi/src/install.rs[408-497]
- pacquet/crates/napi/src/resolve.rs[85-104]
### What to change
Pick one (or combine):
1) **Eliminate the leak**: refactor the engine surface to accept `&Config` / `Arc<Config>` (thread-scoped) instead of requiring `&'static Config`, so N-API can hold an owned/`Arc` config for the duration of a call.
2) **Hard-cap unique configs** (stop-the-bleeding): before leaking on a miss, enforce a maximum number of cached configs and return a structured error once exceeded (so the process cannot be forced to OOM). Note: clearing the DashMap does *not* recover leaked memory; the cap must prevent additional leaks.
3) **Document + validate**: if the API contract expects stable overlays, validate and/or reject high-churn fields (or provide an alternate API that takes per-call auth separately) so callers don’t accidentally create one config per request.

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


5. resolveDependency loses error codes 🐞 Bug ≡ Correctness
Description
resolve_dependency maps resolver errors to napi::Error using error.to_string(), dropping miette
Diagnostic code/hint so JS consumers don’t receive ERR_PNPM_* fields. This breaks the stable pnpm
error contract that the wrapper is explicitly designed to preserve.
Code

pacquet/crates/napi/src/resolve.rs[R152-154]

+    let resolved = runtime
+        .block_on(async { resolver.resolve(&wanted_dependency, &resolve_options).await })
+        .map_err(|error| napi::Error::from_reason(error.to_string()))?;
Evidence
The binding currently stringifies the resolver error, while the resolver error types in this repo
are miette::Diagnostic with ERR_PNPM_* codes and the N-API layer already has a dedicated
envelope-based conversion helper.

pacquet/crates/napi/src/resolve.rs[147-155]
pacquet/crates/napi/src/error.rs[34-56]
pacquet/crates/resolving-npm-resolver/src/pick_package.rs[332-367]

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

## Issue description
`resolveDependency` currently converts resolver errors to `napi::Error` via `error.to_string()`, which loses `miette::Diagnostic` metadata (code/help). The JS wrapper expects the Rust side to emit the `PNPM_ERR_JSON:` envelope so it can restore `err.code`/`err.hint`.
### Issue Context
The npm resolver errors already carry `ERR_PNPM_*` codes via `#[diagnostic(code(...))]`, and the N-API crate has `to_napi_error()` specifically to preserve those fields.
### Fix Focus Areas
- pacquet/crates/napi/src/resolve.rs[147-161]
- pacquet/crates/napi/src/error.rs[34-56]
### What to change
- Replace the `.map_err(|error| napi::Error::from_reason(error.to_string()))?` with an error conversion that preserves diagnostics, e.g.:
- `.map_err(|e| to_napi_error(&e))?` when the error type implements `miette::Diagnostic`, or
- wrap/convert the error into a Diagnostic type before calling `to_napi_error`.
- Ensure all error paths in `resolveDependency` that should be part of the pnpm contract use the same envelope approach (including the “specifier not claimed” error if you want it to have a stable code).

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


6. Default auth follows repo registry 🐞 Bug ⛨ Security
Description
build_config() rebuilds config.auth_headers via `AuthHeaders::from_creds_map(...,
Some(config.registry.as_str()))`, so the "default" ("" key) auth header is bound to whatever
registry URL Config::current() read from the project/workspace .npmrc. A malicious repo can set
registry=https://attacker.tld/ and cause the host’s default Authorization token to be sent to that
registry during installs/resolves.
Code

pacquet/crates/napi/src/config.rs[R365-370]

+    if let Some(headers) = &overlay.auth_header_by_uri {
+        let auth_headers = AuthHeaders::from_creds_map(
+            headers.iter().map(|(uri, header)| (uri.clone(), header.clone())),
+            Some(config.registry.as_str()),
+        );
+        config.auth_headers = std::sync::Arc::new(auth_headers);
Evidence
The N-API overlay rebuilds auth headers using config.registry (derived from .npmrc), and
AuthHeaders::from_creds_map explicitly binds the empty-string credentials slot to the provided
default registry URL; Config::current reads .npmrc and documents credential scoping designed to
prevent exactly this cross-registry binding.

pacquet/crates/napi/src/config.rs[220-221]
pacquet/crates/napi/src/config.rs[365-370]
pacquet/crates/network/src/auth.rs[127-165]
pacquet/crates/config/src/lib.rs[1725-1776]
REVIEW_GUIDE.md[63-66]

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

## Issue description
When `auth_header_by_uri` is provided, the code uses the *merged* `config.registry` (which is influenced by repo/workspace `.npmrc`) as the `default_registry_url` for `AuthHeaders::from_creds_map`. This makes the `""` (default) credential slot follow a repo-controlled registry, which can exfiltrate host/user auth tokens.
## Issue Context
This directly conflicts with the repo’s security guidance that repo-controlled `.npmrc` must not bind victim secrets into outbound auth/registry requests. `Config::current` explicitly documents pnpm’s defense of pinning unscoped creds to each file’s own registry before merge; rebuilding `AuthHeaders` from a `""` default entry after registry merge bypasses that protection.
## Fix Focus Areas
- pacquet/crates/napi/src/config.rs[365-370]
- pacquet/crates/napi/src/config.rs[220-245]

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


7. Config cache key unstable ✓ Resolved 🐞 Bug ☼ Reliability
Description
resolve_config interns leaked Config values using a cache key that hashes
format!("{overlay:?}"), but ConfigOverlay contains HashMap fields whose Debug output order is
not stable, so logically identical overlays can miss the cache and keep leaking additional
Configs. This can cause unbounded memory growth and undermines the stated leak-avoidance design
for long-lived Node processes.
Code

pacquet/crates/napi/src/config.rs[R123-128]

+fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
+    let mut hasher = DefaultHasher::new();
+    dir.hash(&mut hasher);
+    format!("{overlay:?}").hash(&mut hasher);
+    hash_config_sources(dir, &mut hasher);
+    hasher.finish()
Evidence
ConfigOverlay derives Debug and contains HashMap fields (allow_builds,
auth_header_by_uri), and cache_key hashes format!("{overlay:?}"). That makes cache hits
dependent on Debug output rather than the overlay’s logical contents, defeating interning and
causing additional leaked entries to accumulate.

pacquet/crates/napi/src/config.rs[36-105]
pacquet/crates/napi/src/config.rs[116-129]

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

## Issue description
`pacquet/crates/napi/src/config.rs` computes a u64 cache key using `format!("{overlay:?}")`. Because `ConfigOverlay` includes `HashMap` fields, the Debug string can vary between logically-equal overlays, leading to cache misses and repeated insertion of newly leaked `Config`s.
## Issue Context
This cache is meant to prevent per-call leaking of `Config::leak()` in long-lived Node processes.
## Fix Focus Areas
- Replace Debug-string hashing with a deterministic key:
- Hash each `ConfigOverlay` field directly.
- For map-like fields, hash entries in a stable order (e.g., convert to `BTreeMap`, or collect keys and sort).
- Prefer a dedicated `CacheKey` struct implementing `Hash + Eq` over a raw u64 hash.
- Keep the “config sources” fingerprinting, but avoid reading/hashing more than necessary.
### Code locations
- pacquet/crates/napi/src/config.rs[36-105]
- pacquet/crates/napi/src/config.rs[123-172]

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


8. Branch URL in homepage 📘 Rule violation ⚙ Maintainability
Description
pacquet/npm/napi/package.json sets homepage to a branch-based GitHub /tree/main/... URL, which
is not a commit-SHA permalink. This breaks the requirement to reference code with immutable SHA
links.
Code

pacquet/npm/napi/package.json[12]

+  "homepage": "https://github.com/pnpm/pnpm/tree/main/pacquet",
Evidence
PR Compliance ID 713443 requires GitHub /blob/ or /tree/ links to use a commit SHA rather than a
branch name. The new homepage value uses /tree/main/, which is explicitly branch-based.

Rule 713443: Reference code with commit SHA links, not branch-based URLs
pacquet/npm/napi/package.json[12-12]

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

## Issue description
`homepage` uses a branch-based GitHub code URL (`/tree/main/...`), which violates the requirement to avoid branch-based code links.
## Issue Context
This value is user-visible package metadata and should not point at a mutable branch reference.
## Fix Focus Areas
- pacquet/npm/napi/package.json[12-12]

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


9. Missing trailing comma in install ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
Multi-line TypeScript function parameter lists in pacquet/npm/napi/index.d.ts omit a trailing
comma on the last parameter. This increases diff churn and violates the trailing-comma requirement
for multi-line constructs.
Code

pacquet/npm/napi/index.d.ts[R192-196]

+export function install(
+  options: InstallOptions,
+  onLog?: LogListener,
+  readPackageHook?: ReadPackageHook
+): Promise<InstallResult>
Evidence
PR Compliance ID 713434 requires trailing commas for multi-line TypeScript constructs. The
install(...) declaration spans multiple lines and ends without a trailing comma after
readPackageHook?: ReadPackageHook.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pacquet/npm/napi/index.d.ts[192-196]

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

## Issue description
TypeScript multi-line parameter lists are missing a trailing comma on the final parameter.
## Issue Context
The repository compliance rule requires trailing commas in multi-line TypeScript collections and multi-line constructs (including parameter lists).
## Fix Focus Areas
- pacquet/npm/napi/index.d.ts[192-208]

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


10. reject_non_empty_list takes &Vec ✓ Resolved 📘 Rule violation ➹ Performance
Description
reject_non_empty_list accepts Option> even though it only needs slice behavior, unnecessarily
constraining callers. This violates the requirement to use the most general borrowed parameter
types.
Code

pacquet/crates/napi/src/install.rs[R519-520]

+fn reject_non_empty_list<Value>(value: Option<&Vec<Value>>, option: &str) -> napi::Result<()> {
+    reject_if(value.is_some_and(|items| !items.is_empty()), option)
Evidence
PR Compliance ID 713447 forbids references to owned containers like &Vec when a slice would
suffice. The new helper is declared as Option> and only checks emptiness, which can be done on
&[Value].

Rule 713447: Use the most general borrowed parameter types to avoid unnecessary allocations
pacquet/crates/napi/src/install.rs[519-520]

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 helper function takes `Option<&Vec<T>>` instead of a more general borrowed type.
## Issue Context
Using `&Vec<T>` is less flexible than `&[T]` (or `impl AsRef<[T]>`) and violates the codebase rule to prefer general borrowed parameter types.
## Fix Focus Areas
- pacquet/crates/napi/src/install.rs[519-521]

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


11. Historical wording in test comment ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A new test comment uses historical phrasing (used to reject) instead of describing the current
behavior. This violates the rule requiring comments to describe current behavior, not past
implementations.
Code

pacquet/crates/napi/src/install/tests.rs[R101-103]

+fn newly_supported_install_options_are_accepted() {
+    // Options the binding used to reject now flow through the engine.
+    let mut options = install_options();
Evidence
PR Compliance ID 772199 forbids historical phrasing like "used to" in comments. The added comment
explicitly says the binding "used to reject" these options.

Rule 772199: Comments must describe current behavior, not historical implementations
pacquet/crates/napi/src/install/tests.rs[101-103]

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 new comment describes historical behavior rather than the current contract.
## Issue Context
Repository guidance requires comments to describe current behavior and avoid "used to" / "previously" phrasing.
## Fix Focus Areas
- pacquet/crates/napi/src/install/tests.rs[101-103]

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


12. napi deps added at workspace 📘 Rule violation ⌂ Architecture
Description
napi, napi-build, and napi-derive were added at the workspace level even though the new
pacquet-napi crate is the consumer in this PR. This violates the rule to scope new Rust
dependencies to the crate that uses them.
Code

Cargo.toml[R125-127]

+napi = { version = "3.10.3", default-features = false, features = ["napi8", "serde-json", "tokio_rt", "async"] }
+napi-build = { version = "2.3.2" }
+napi-derive = { version = "3.5.9" }
Evidence
PR Compliance ID 713471 requires scoping new Rust dependencies to the specific crate unless multiple
crates use them. The root Cargo.toml adds the napi* crates, and pacquet/crates/napi/Cargo.toml
is a direct consumer via { workspace = true }.

Rule 713471: Scope new Rust dependencies to the crate that uses them
Cargo.toml[125-127]
pacquet/crates/napi/Cargo.toml[33-45]

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

## Issue description
New Rust dependencies were added to the workspace dependency table even though they appear to be used by only one crate in this PR.
## Issue Context
`pacquet-napi` depends on `napi`, `napi-derive`, and `napi-build`.
## Fix Focus Areas
- Cargo.toml[125-127]
- pacquet/crates/napi/Cargo.toml[33-45]

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


13. Sink not panic-safe ✓ Resolved 🐞 Bug ⛨ Security
Description
install() installs a process-global JS log sink and stats accumulator but only clears them on the
normal return path, so a panic in the worker thread can leave a stale sink/stats active and misroute
subsequent logs across callers. This can leak install paths/package names between independent
operations and makes the addon fragile after a single panic.
Code

pacquet/crates/napi/src/install.rs[R204-222]

+    let had_sink = on_log.is_some();
+    if let Some(sink) = on_log {
+        set_global_log_sink(sink);
+    }
+    let pnpmfile_hook: Option<Arc<dyn PnpmfileHooks>> = read_package_hook
+        .map(|sink| Arc::new(JsReadPackageHook::new(sink)) as Arc<dyn PnpmfileHooks>);
+    begin_stats();
+    let outcome = run_install_inner(options, pnpmfile_hook, EngineMode::Install);
+    let stats = take_stats();
+    if had_sink {
+        clear_global_log_sink();
+    }
+    let store_dir = outcome?;
+    Ok(InstallResult {
+        stats: InstallStatsResult {
+            added: stats.added as f64,
+            removed: stats.removed as f64,
+            linked_to_root: 0.0,
+        },
Evidence
run_install_blocking sets the process-global sink and begins stats, then calls into the engine and
only clears/takes stats after the call returns; if the worker thread panics, that cleanup path is
skipped. The sink is explicitly process-global in reporter_bridge.rs.

pacquet/crates/napi/src/install.rs[199-227]
pacquet/crates/napi/src/reporter_bridge.rs[33-56]
pacquet/crates/napi/src/reporter_bridge.rs[70-97]

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

## Issue description
`run_install_blocking` sets global process state (`set_global_log_sink`, `begin_stats`) and clears it only on the normal path. If `run_install_inner` (or anything before `clear_global_log_sink`) panics, the oneshot sender is dropped, the JS side gets "worker thread panicked", but the global sink/stats remain installed.
## Issue Context
This addon is built with `panic = "unwind"` in `napi-release`, so thread panics are plausible and should not corrupt global state.
## Fix Focus Areas
- Add a small RAII guard that restores/clears the sink and stats on `Drop`.
- Wrap the worker-thread body in `std::panic::catch_unwind` so cleanup always runs and you can return a structured napi error.
- Use the return value of `set_global_log_sink` (previous sink) and restore it on exit (don’t just clear).
### Code pointers
- pacquet/crates/napi/src/install.rs[199-227]
- pacquet/crates/napi/src/reporter_bridge.rs[33-56]
- pacquet/crates/napi/src/reporter_bridge.rs[70-97]

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


14. Pack races global sink ✓ Resolved 🐞 Bug ⛨ Security
Description
pack() also sets/clears the same process-global log sink but does not acquire the serialization
lock used by install/rebuild, so concurrent calls can overwrite each other’s sink and route logs to
the wrong JS callback. This can leak log events between unrelated operations in the same Node
process.
Code

pacquet/crates/napi/src/pack.rs[R49-53]

+pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
+    let had_sink = on_log.is_some();
+    if let Some(sink) = on_log {
+        set_global_log_sink(sink);
+    }
Evidence
install() explicitly serializes engine calls behind install_lock, while pack() manipulates the
same global sink without acquiring any lock. The sink is defined as process-global, so concurrent
access overwrites the single slot.

pacquet/crates/napi/src/pack.rs[48-88]
pacquet/crates/napi/src/install.rs[168-197]
pacquet/crates/napi/src/reporter_bridge.rs[33-56]

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

## Issue description
`pack()` uses the same global log sink as `install()`/`rebuild()`, but it does not participate in the serialization (`install_lock`) that those APIs use. That means `pack()` can run concurrently with `install()` and overwrite the sink slot.
## Issue Context
The sink slot is a single global `RwLock<Option<LogSink>>`. Any overlap will misroute events.
## Fix Focus Areas
- Ensure every API that calls `set_global_log_sink` uses the same global lock (rename `install_lock` to something like `engine_call_lock` and reuse it in `pack`).
- Alternatively, change the reporter bridge design to be per-call/per-thread (avoid process-global sink), but that’s larger.
### Code pointers
- pacquet/crates/napi/src/pack.rs[48-88]
- pacquet/crates/napi/src/install.rs[168-197]
- pacquet/crates/napi/src/reporter_bridge.rs[33-56]

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


15. Malformed manifest becomes empty ✓ Resolved 🐞 Bug ≡ Correctness
Description
PackageManifest::from_value coerces any non-object JSON (null/string/array/etc.) to {}, so the
Node binding can proceed with an empty manifest instead of rejecting invalid input. This can drive
dependency resolution/lockfile generation from missing data and produce incorrect or destructive
on-disk results (e.g., writing a lockfile that no longer reflects the intended dependencies) without
surfacing the input error.
Code

pacquet/crates/package-manifest/src/lib.rs[R167-174]

+        // A manifest must be a JSON object. A non-object value (array / string /
+        // number) supplied across the FFI boundary would otherwise panic later
+        // when a dependency is inserted via `self.value[key] = ...`; coerce
+        // anything that isn't an object to an empty one so malformed input
+        // degrades gracefully instead of aborting the host process.
+        if !value.is_object() {
+            value = json!({});
+        }
Evidence
The new code explicitly replaces any non-object manifest JSON with {}. The N-API install path
passes JS-provided manifest values into from_value, and the install code later persists lockfiles
derived from manifest dependencies—so coercion can result in installs/lockfiles computed from empty
dependency maps rather than rejecting invalid input.

pacquet/crates/package-manifest/src/lib.rs[158-177]
pacquet/crates/napi/src/install.rs[241-260]
pacquet/crates/package-manager/src/install.rs[1006-1010]
pacquet/crates/package-manager/src/dependencies_graph_to_lockfile.rs[306-313]

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

## Issue description
`PackageManifest::from_value` currently turns any non-object JSON value into an empty object (`{}`), which avoids a panic but also hides invalid input at the FFI boundary. For the N-API surface, this means a consumer bug (or untrusted/incorrect input) can yield an install that appears to succeed while operating on an empty manifest and still writing outputs like `pnpm-lock.yaml`.
## Issue Context
The N-API install path constructs `PackageManifest` directly from JS-provided JSON values; those values are not guaranteed to be objects. Silent coercion changes the failure mode from “explicit invalid input” to “successful run with wrong graph/output”.
## Fix Focus Areas
- pacquet/crates/package-manifest/src/lib.rs[158-178]
- pacquet/crates/napi/src/install.rs[241-260]
- pacquet/crates/napi/src/install.rs[394-404]
## Suggested fix
1. Change `PackageManifest::from_value` to fail closed for non-object input:
- Either make it `pub fn try_from_value(...) -> Result<PackageManifest, PackageManifestError>` (preferred), or keep `from_value` but add a strict variant and switch N-API to it.
- Add a dedicated error variant like `PackageManifestError::InvalidManifestJsonType`.
2. In N-API `install`, validate that each `project.manifest` is an object before creating the manifest; return a structured N-API error (with pnpm-style code) when invalid.
3. Keep the “no panic across FFI” property, but ensure invalid input is surfaced as an explicit error rather than being coerced into `{}`.

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


16. invalid_manifest_error uses non-pnpm code 📘 Rule violation ≡ Correctness
Description
invalid_manifest_error() emits the user-visible code ERR_PNPM_NAPI_INVALID_MANIFEST, which does
not match pnpm’s established ERR_PNPM_* error-code namespace for invalid project manifests. This
can break consumers that rely on pnpm-compatible error codes/messages for control flow and error
translation.
Code

pacquet/crates/napi/src/error.rs[R73-83]

+pub fn invalid_manifest_error(root_dir: &str) -> napi::Error {
+    let envelope = ErrorEnvelope {
+        code: Some("ERR_PNPM_NAPI_INVALID_MANIFEST".to_string()),
+        message: format!("the `manifest` for project `{root_dir}` is not a JSON object"),
+        hint: Some(
+            "Each project's `manifest` must be a plain object with the package.json shape.".into(),
+        ),
+    };
+    match serde_json::to_string(&envelope) {
+        Ok(json) => napi::Error::from_reason(format!("{ENVELOPE_PREFIX}{json}")),
+        Err(_) => napi::Error::from_reason(envelope.message),
Evidence
The new code returns ERR_PNPM_NAPI_INVALID_MANIFEST for an invalid manifest shape, creating a new
user-visible code that diverges from pnpm’s established error codes for invalid project manifests.
pnpm’s codebase demonstrates the canonical invalid-manifest error identifier (INVALID_PACKAGE_JSON
→ ERR_PNPM_INVALID_PACKAGE_JSON), so pacquet should reuse the pnpm-compatible code/message instead
of introducing a new one.

Rule 713473: Align pacquet error codes and messages with pnpm
pacquet/crates/napi/src/error.rs[70-83]
pnpm11/deps/inspection/commands/src/view/index.ts[265-281]

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

## Issue description
`invalid_manifest_error()` currently uses a pacquet-specific error code (`ERR_PNPM_NAPI_INVALID_MANIFEST`) for an invalid project manifest shape. Compliance requires pacquet’s user-facing error codes/messages to align with pnpm’s documented/canonical errors when an equivalent pnpm error exists.
## Issue Context
pnpm uses `INVALID_PACKAGE_JSON` (surfacing as `ERR_PNPM_INVALID_PACKAGE_JSON`) for failures to read/parse a project manifest. A non-object `manifest` provided to the engine binding is an invalid project manifest condition and should reuse the closest pnpm canonical code rather than introducing a new `ERR_PNPM_NAPI_*` code.
## Fix Focus Areas
- pacquet/crates/napi/src/error.rs[70-84]

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


17. Linux libc fallback aborts ✓ Resolved 🐞 Bug ☼ Reliability
Description
On Linux, the loader tries both glibc and musl candidates, but it only falls through on
MODULE_NOT_FOUND; an incompatible first candidate can throw (e.g. ERR_DLOPEN_FAILED) and abort
before the other libc variant is attempted. This can make @pnpm/napi fail to load entirely on some
Linux environments where libc probing is unavailable or the initial guess is wrong.
Code

pacquet/npm/napi/index.js[R17-39]

+// `'glibc' | 'musl' | null` — `null` when the host isn't Linux or the libc
+// can't be probed (`process.report` may be unavailable/disabled). glibc builds
+// set `glibcVersionRuntime`; musl leaves it unset.
+function detectLinuxLibc() {
+  if (process.platform !== 'linux') return null
+  try {
+    return process.report?.getReport()?.header?.glibcVersionRuntime ? 'glibc' : 'musl'
+  } catch {
+    return null
+  }
+}
+
+// Ordered platform triples to try. On Linux both libc variants are attempted
+// (ordered by detection) so a musl host whose libc can't be probed still
+// resolves the `-musl` addon instead of failing on the glibc one; elsewhere
+// there is a single triple.
+function platformTriples() {
+  const { platform, arch } = process
+  if (platform === 'linux') {
+    const order = detectLinuxLibc() === 'musl' ? ['-musl', ''] : ['', '-musl']
+    return order.map((suffix) => `linux-${arch}${suffix}`)
+  }
+  return [`${platform}-${arch}`]
Evidence
platformTriples() generates an ordered list including both libc variants on Linux, but tryLoad()
rethrows any error that is not classified as a missing module; native-addon load failures are
typically not MODULE_NOT_FOUND, so the loop stops before trying the next triple.

pacquet/npm/napi/index.js[17-39]
pacquet/npm/napi/index.js[42-53]

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

## Issue description
On Linux, `platformTriples()` produces both glibc and musl triples, but `tryLoad()` only treats `MODULE_NOT_FOUND` as a retryable error. If the first candidate exists but fails to load due to libc/ABI mismatch, `require()` throws (commonly `ERR_DLOPEN_FAILED`) and the loader never tries the fallback triple.
### Issue Context
This was introduced by adding multi-triple Linux resolution; the error handling must now distinguish “candidate exists but is incompatible” from “hard failure where we should stop”.
### Fix Focus Areas
- pacquet/npm/napi/index.js[17-39]
- pacquet/npm/napi/index.js[42-53]
### Suggested fix
- Update `tryLoad()` (or `loadBinding()` around it) so that for Linux triple candidates it treats known native-addon load failures (at minimum `ERR_DLOPEN_FAILED`, and potentially other native-load error codes/messages) as retryable: push the error into `loadErrors` and return `null` so the loop continues to the next candidate.
- Keep explicit override behavior strict: if `PNPM_NAPI_BINARY` is set and the addon exists but fails to load, fail fast rather than silently falling back to other candidates.

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


18. Linux libc fallback aborts ✓ Resolved 🐞 Bug ☼ Reliability
Description
On Linux, the loader tries both glibc and musl candidates, but it only falls through on
MODULE_NOT_FOUND; an incompatible first candidate can throw (e.g. ERR_DLOPEN_FAILED) and abort
before the other libc variant is attempted. This can make @pnpm/napi fail to load entirely on some
Linux environments where libc probing is unavailable or the initial guess is wrong.
Code

pacquet/npm/napi/index.js[R17-39]

+// `'glibc' | 'musl' | null` — `null` when the host isn't Linux or the libc
+// can't be probed (`process.report` may be unavailable/disabled). glibc builds
+// set `glibcVersionRuntime`; musl leaves it unset.
+function detectLinuxLibc() {
+  if (process.platform !== 'linux') return null
+  try {
+    return process.report?.getReport()?.header?.glibcVersionRuntime ? 'glibc' : 'musl'
+  } catch {
+    return null
+  }
+}
+
+// Ordered platform triples to try. On Linux both libc variants are attempted
+// (ordered by detection) so a musl host whose libc can't be probed still
+// resolves the `-musl` addon instead of failing on the glibc one; elsewhere
+// there is a single triple.
+function platformTriples() {
+  const { platform, arch } = process
+  if (platform === 'linux') {
+    const order = detectLinuxLibc() === 'musl' ? ['-musl', ''] : ['', '-musl']
+    return order.map((suffix) => `linux-${arch}${suffix}`)
+  }
+  return [`${platform}-${arch}`]
Evidence
platformTriples() generates an ordered list including both libc variants on Linux, but tryLoad()
rethrows any error that is not classified as a missing module; native-addon load failures are
typically not MODULE_NOT_FOUND, so the loop stops before trying the next triple.

pacquet/npm/napi/index.js[17-39]
pacquet/npm/napi/index.js[42-53]

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

## Issue description
On Linux, `platformTriples()` produces both glibc and musl triples, but `tryLoad()` only treats `MODULE_NOT_FOUND` as a retryable error. If the first candidate exists but fails to load due to libc/ABI mismatch, `require()` throws (commonly `ERR_DLOPEN_FAILED`) and the loader never tries the fallback triple.
### Issue Context
This was introduced by adding multi-triple Linux resolution; the error handling must now distinguish “candidate exists but is incompatible” from “hard failure where we should stop”.
### Fix Focus Areas
- pacquet/npm/napi/index.js[17-39]
- pacquet/npm/napi/index.js[42-53]
### Suggested fix
- Update `tryLoad()` (or `loadBinding()` around it) so that for Linux triple candidates it treats known native-addon load failures (at minimum `ERR_DLOPEN_FAILED`, and potentially other native-load error codes/messages) as retryable: push the error into `loadErrors` and return `null` so the loop continues to the next candidate.
- Keep explicit override behavior strict: if `PNPM_NAPI_BINARY` is set and the addon exists but fails to load, fail fast rather than silently falling back to other candidates.

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


19. invalid_manifest_error uses non-pnpm code ✓ Resolved 📘 Rule violation ≡ Correctness
Description
invalid_manifest_error() emits the user-visible code ERR_PNPM_NAPI_INVALID_MANIFEST, which does
not match pnpm’s established ERR_PNPM_* error-code namespace for invalid project manifests. This
can break consumers that rely on pnpm-compatible error codes/messages for control flow and error
translation.
Code

pacquet/crates/napi/src/error.rs[R73-83]

+pub fn invalid_manifest_error(root_dir: &str) -> napi::Error {
+    let envelope = ErrorEnvelope {
+        code: Some("ERR_PNPM_NAPI_INVALID_MANIFEST".to_string()),
+        message: format!("the `manifest` for project `{root_dir}` is not a JSON object"),
+        hint: Some(
+            "Each project's `manifest` must be a plain object with the package.json shape.".into(),
+        ),
+    };
+    match serde_json::to_string(&envelope) {
+        Ok(json) => napi::Error::from_reason(format!("{ENVELOPE_PREFIX}{json}")),
+        Err(_) => napi::Error::from_reason(envelope.message),
Evidence
The new code returns ERR_PNPM_NAPI_INVALID_MANIFEST for an invalid manifest shape, creating a new
user-visible code that diverges from pnpm’s established error codes for invalid project manifests.
pnpm’s codebase demonstrates the canonical invalid-manifest error identifier (INVALID_PACKAGE_JSON
→ ERR_PNPM_INVALID_PACKAGE_JSON), so pacquet should reuse the pnpm-compatible code/message instead
of introducing a new one.

Rule 713473: Align pacquet error codes and messages with pnpm
pacquet/crates/napi/src/error.rs[70-83]
pnpm11/deps/inspection/commands/src/view/index.ts[265-281]

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

## Issue description
`invalid_manifest_error()` currently uses a pacquet-specific error code (`ERR_PNPM_NAPI_INVALID_MANIFEST`) for an invalid project manifest shape. Compliance requires pacquet’s user-facing error codes/messages to align with pnpm’s documented/canonical errors when an equivalent pnpm error exists.
## Issue Context
pnpm uses `INVALID_PACKAGE_JSON` (surfacing as `ERR_PNPM_INVALID_PACKAGE_JSON`) for failures to read/parse a project manifest. A non-object `manifest` provided to the engine binding is an invalid project manifest condition and should reuse the closest pnpm canonical code rather than introducing a new `ERR_PNPM_NAPI_*` code.
## Fix Focus Areas
- pacquet/crates/napi/src/error.rs[70-84]

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


20. Malformed manifest becomes empty ✓ Resolved 🐞 Bug ≡ Correctness
Description
PackageManifest::from_value coerces any non-object JSON (null/string/array/etc.) to {}, so the
Node binding can proceed with an empty manifest instead of rejecting invalid input. This can drive
dependency resolution/lockfile generation from missing data and produce incorrect or destructive
on-disk results (e.g., writing a lockfile that no longer reflects the intended dependencies) without
surfacing the input error.
Code

pacquet/crates/package-manifest/src/lib.rs[R167-174]

+        // A manifest must be a JSON object. A non-object value (array / string /
+        // number) supplied across the FFI boundary would otherwise panic later
+        // when a dependency is inserted via `self.value[key] = ...`; coerce
+        // anything that isn't an object to an empty one so malformed input
+        // degrades gracefully instead of aborting the host process.
+        if !value.is_object() {
+            value = json!({});
+        }
Evidence
The new code explicitly replaces any non-object manifest JSON with {}. The N-API install path
passes JS-provided manifest values into from_value, and the install code later persists lockfiles
derived from manifest dependencies—so coercion can result in installs/lockfiles computed from empty
dependency maps rather than rejecting invalid input.

[pacquet/crates/package-manifest/src/lib.rs[158-177]](https://github.com/pnpm/pnpm/blob/034d8396...

@qodo-code-review

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

Copy link
Copy Markdown

PR Summary by Qodo

feat(pacquet): Add Node API bindings for the Rust engine (@pnpm/napi)

✨ Enhancement ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Adds pacquet-napi cdylib + @pnpm/napi wrapper exposing Rust engine APIs to Node.js.
• Runs installs on a dedicated worker thread; bridges logs and readPackage hook to JS.
• Extends engine config/network/installability to support embedder needs and safe NAPI release
 builds.
Diagram

graph TD
    JS["JS Consumer (Bit)"] --> WRAPPER["@pnpm/napi\nindex.js"] --> ADDON["pacquet-napi\n.node cdylib"]

    ADDON --> INSTALL["install.rs\ninstall/rebuild"] --> PKG_MGR["pacquet-package-manager\nInstall"] --> NETWORK["pacquet-network\nThrottledClient"]
    ADDON --> RESOLVE["resolve.rs\nresolveDependency"] --> NPM_RESOLVER["pacquet-resolving\nnpm-resolver"] --> NETWORK
    ADDON --> PACK["pack.rs\npack"] --> PACK_CRATE["pacquet-pack\napi"]

    INSTALL --> CONFIG_MOD["config.rs\nresolve_config"] --> CONFIG_CRATE["pacquet-config\nConfig"]
    INSTALL --> REPORTER["reporter_bridge.rs\nlog bridge"] --> JS
    INSTALL --> HOOKS["hooks.rs\nreadPackage"] --> JS
    ADDON --> ERROR["error.rs\nERR envelope"] --> WRAPPER

    subgraph Legend
      direction LR
      _js["JS Layer"] ~~~ _rust["Rust Binding"] ~~~ _eng[("Engine Crates")]
    end
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Run engine calls directly on napi async runtime (no worker thread)
  • ➕ Less plumbing (no oneshot/thread spawn)
  • ➕ Potentially lower overhead for small calls
  • ➖ Not viable without refactoring pacquet install to avoid borrowed state crossing FFI
  • ➖ Risk of blocking the napi tokio runtime during deep synchronous call chains
2. Use a stable/non-DoS hash for config cache keys
  • ➕ Avoids theoretical DefaultHasher collision issues for long-lived Node processes
  • ➕ Key stability across Rust versions/toolchains
  • ➖ Minor complexity/dependency for a low-probability scenario
  • ➖ Current approach is pragmatic and likely sufficient short-term

Recommendation: The worker-thread + oneshot approach is the right design given pacquet’s borrowed install state and deep synchronous call chains; it keeps non-&#x27;static borrows off the FFI boundary and mirrors the CLI’s stack-sizing strategy. The config interning scheme is pragmatic for a long-lived Node host; a follow-up could swap DefaultHasher for a stable hasher if desired.

Files changed (51) +3631 / -46

Enhancement (21) +2118 / -25
config_deps.rsApply 'maxSockets' to env-installer dependency client +2/-1

Apply 'maxSockets' to env-installer dependency client

• Chains '.with_max_sockets_per_host(config.max_sockets)' onto the 'ThrottledClient' used for env-installer dependency fetches.

pacquet/crates/cli/src/config_deps.rs

state.rsApply 'maxSockets' to CLI install HTTP client +2/-1

Apply 'maxSockets' to CLI install HTTP client

• Chains '.with_max_sockets_per_host(config.max_sockets)' onto the CLI’s install client, enabling per-origin socket limits.

pacquet/crates/cli/src/state.rs

env_overlay.rsSupport env overrides for maxSockets/engineStrict/nodeVersion +3/-0

Support env overrides for maxSockets/engineStrict/nodeVersion

• Adds 'MAX_SOCKETS', 'ENGINE_STRICT', and 'NODE_VERSION' mappings so corresponding 'PNPM_CONFIG_*' env vars override config.

pacquet/crates/config/src/env_overlay.rs

lib.rsAdd 'engine_strict', 'node_version', 'max_sockets' to 'Config' +32/-10

Add 'engine_strict', 'node_version', 'max_sockets' to 'Config'

• Introduces new config fields for strict engine checks, explicit Node version targeting, and per-origin socket caps. Also exports 'default_config_dir' for NAPI config-source hashing.

pacquet/crates/config/src/lib.rs

workspace_yaml.rsParse/apply 'engineStrict', 'nodeVersion', 'maxSockets' from workspace YAML +20/-0

Parse/apply 'engineStrict', 'nodeVersion', 'maxSockets' from workspace YAML

• Extends 'WorkspaceSettings' and 'apply_to' to set new config fields from 'pnpm-workspace.yaml'/global 'config.yaml'.

pacquet/crates/config/src/workspace_yaml.rs

Cargo.tomlAdd new 'pacquet-napi' cdylib crate manifest +50/-0

Add new 'pacquet-napi' cdylib crate manifest

• Creates a 'cdylib' crate with workspace dependencies on pacquet engine crates plus napi-rs and tokio/serde support.

pacquet/crates/napi/Cargo.toml

config.rsInterned config resolution for long-lived Node hosts +373/-0

Interned config resolution for long-lived Node hosts

• Implements a 'ConfigOverlay' and an intern table of leaked '&'static Config' values keyed by a hash of directory/overlay plus config-source contents ('.npmrc', workspace yaml, env vars, etc.) to avoid leaking one config per call.

pacquet/crates/napi/src/config.rs

error.rsStructured error envelope bridging ERR_PNPM_* to JS +86/-0

Structured error envelope bridging ERR_PNPM_* to JS

• Encodes 'code'/'message'/'hint' into a 'PNPM_ERR_JSON:' envelope for 'napi::Error', plus helpers for unimplemented/unsupported options so JS consumers see stable pnpm error semantics.

pacquet/crates/napi/src/error.rs

hooks.rsJS 'readPackage' hook adapter via ThreadsafeFunction +82/-0

JS 'readPackage' hook adapter via ThreadsafeFunction

• Implements 'JsReadPackageHook' to run the 'readPackage' transform in JS (synchronously) during dependency resolution, replacing '.pnpmfile.cjs' usage for embedders.

pacquet/crates/napi/src/hooks.rs

install.rsImplement NAPI 'install' (worker thread, in-memory importers) + stubs +656/-0

Implement NAPI 'install' (worker thread, in-memory importers) + stubs

• Adds NAPI 'install' that runs on a dedicated 32 MiB-stack worker thread and awaits results via oneshot, supports in-memory importers (single/workspace), build-approval controls, 'depsRequiringBuild', and log/hook bridging. 'rebuild'/'getPeerDependencyIssues' are present with unimplemented stubs per plan.

pacquet/crates/napi/src/install.rs

lib.rsExpose NAPI exports and engineVersion entrypoint +55/-0

Expose NAPI exports and engineVersion entrypoint

• Wires module structure and re-exports public NAPI symbols, adds 'engineVersion()' export, and includes test-only runtime stubs for linking.

pacquet/crates/napi/src/lib.rs

pack.rsExpose 'pack' over NAPI via blocking pool +101/-0

Expose 'pack' over NAPI via blocking pool

• Wraps 'pacquet_pack::api' behind an async NAPI function, forwarding lifecycle-script output through the reporter bridge when a log sink is provided.

pacquet/crates/napi/src/pack.rs

reporter_bridge.rsBridge pacquet Reporter events to JS callback and collect stats +126/-0

Bridge pacquet Reporter events to JS callback and collect stats

• Implements a process-global ThreadsafeFunction sink for wire-compatible log events and a global stats accumulator (added/removed and ignored builds) serialized by an install lock.

pacquet/crates/napi/src/reporter_bridge.rs

resolve.rsExpose npm-registry 'resolveDependency' over NAPI +171/-0

Expose npm-registry 'resolveDependency' over NAPI

• Adds NAPI resolver backed by 'pacquet_resolving_npm_resolver', running on a worker thread with its own tokio runtime; non-npm specifiers currently error (follow-up to support other resolvers).

pacquet/crates/napi/src/resolve.rs

specifier.rsExpose 'parseBareSpecifier' over NAPI +49/-0

Expose 'parseBareSpecifier' over NAPI

• Wraps pacquet’s wanted-dependency parser and returns 'null' for empty input to match the TypeScript contract used by consumers.

pacquet/crates/napi/src/specifier.rs

lib.rsAdd per-origin 'maxSockets' limiting to ThrottledClient +85/-3

Add per-origin 'maxSockets' limiting to ThrottledClient

• Introduces a per-origin semaphore map (keyed by scheme/host/port) and a builder method 'with_max_sockets_per_host'. Acquires per-origin permits before global concurrency to avoid origin bursts starving others.

pacquet/crates/network/src/lib.rs

install.rsAdd embedder overrides to 'Install' (hooks + workspace projects) +24/-3

Add embedder overrides to 'Install' (hooks + workspace projects)

• Adds 'pnpmfile_hook_override' (in-process hooks) and 'workspace_projects_override' (in-memory workspace importers) to 'Install', and uses them to bypass disk-based pnpmfile/workspace discovery when provided.

pacquet/crates/package-manager/src/install.rs

install_with_fresh_lockfile.rsAllow pnpmfile hook override and optimize host detection +20/-4

Allow pnpmfile hook override and optimize host detection

• Threads 'pnpmfile_hook_override' into fresh installs and prefers it over disk '.pnpmfile.cjs'. Adds 'detect_with(engine_strict, node_version)' to avoid blocking 'node --version' probing when pinned.

pacquet/crates/package-manager/src/install_with_fresh_lockfile.rs

installability.rsAdd 'InstallabilityHost::detect_with' and normalize nodeVersion +37/-3

Add 'InstallabilityHost::detect_with' and normalize nodeVersion

• Adds 'detect_with' to apply 'engineStrict' and optional 'nodeVersion' (including trimming and stripping leading 'v') without probing 'node --version'.

pacquet/crates/package-manager/src/installability.rs

lib.rsAdd 'PackageManifest::from_value' for in-memory manifests +14/-0

Add 'PackageManifest::from_value' for in-memory manifests

• Introduces a constructor for programmatic, in-memory manifest values that still applies engines-runtime normalization consistent with disk-loaded manifests.

pacquet/crates/package-manifest/src/lib.rs

index.jsAddon loader + error decoration shim +130/-0

Addon loader + error decoration shim

• Implements binding resolution (env override, optional dependency, local build) and wraps exports so thrown/rejected errors decode the 'PNPM_ERR_JSON:' envelope into 'err.code'/'err.hint'.

pacquet/npm/napi/index.js

Bug fix (1) +18 / -10
install_frozen_lockfile.rsPropagate 'engineStrict'/'nodeVersion' correctly on frozen path +18/-10

Propagate 'engineStrict'/'nodeVersion' correctly on frozen path

• Uses 'config.engine_strict' for host/walker engine policy, and avoids 'node --version' probing when an explicit 'nodeVersion' is configured by using 'detect_with'.

pacquet/crates/package-manager/src/install_frozen_lockfile.rs

Refactor (13) +30 / -0
dedupe.rsDefault new 'Install' fields to 'None' in dedupe CLI +2/-0

Default new 'Install' fields to 'None' in dedupe CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/dedupe.rs

deploy.rsDefault new 'Install' fields to 'None' in deploy CLI +2/-0

Default new 'Install' fields to 'None' in deploy CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/deploy.rs

fetch.rsDefault new 'Install' fields to 'None' in fetch CLI +2/-0

Default new 'Install' fields to 'None' in fetch CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/fetch.rs

import.rsDefault new 'Install' fields to 'None' in import CLI +2/-0

Default new 'Install' fields to 'None' in import CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/import.rs

install.rsDefault new 'Install' fields to 'None' across install paths +6/-0

Default new 'Install' fields to 'None' across install paths

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to all CLI 'Install' struct literals (including pnpr-driven paths) to keep behavior unchanged.

pacquet/crates/cli/src/cli_args/install.rs

link.rsDefault new 'Install' fields to 'None' in link CLI +2/-0

Default new 'Install' fields to 'None' in link CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/link.rs

prune.rsDefault new 'Install' fields to 'None' in prune CLI +2/-0

Default new 'Install' fields to 'None' in prune CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/prune.rs

rebuild.rsDefault new 'Install' fields to 'None' in rebuild CLI +2/-0

Default new 'Install' fields to 'None' in rebuild CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the rebuild 'Install' struct literal.

pacquet/crates/cli/src/cli_args/rebuild.rs

unlink.rsDefault new 'Install' fields to 'None' in unlink CLI +2/-0

Default new 'Install' fields to 'None' in unlink CLI

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to the 'Install' struct literal, preserving existing behavior.

pacquet/crates/cli/src/cli_args/unlink.rs

add.rsDefault new 'Install' override fields to 'None' in add path +2/-0

Default new 'Install' override fields to 'None' in add path

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to 'Install' struct literal to keep existing semantics unchanged.

pacquet/crates/package-manager/src/add.rs

remove.rsDefault new 'Install' override fields to 'None' in remove path +2/-0

Default new 'Install' override fields to 'None' in remove path

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to 'Install' struct literal to keep behavior unchanged.

pacquet/crates/package-manager/src/remove.rs

update.rsDefault new 'Install' override fields to 'None' in update path +2/-0

Default new 'Install' override fields to 'None' in update path

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to 'Install' struct literal to keep behavior unchanged.

pacquet/crates/package-manager/src/update.rs

resolve.rsDefault new 'Install' override fields to 'None' in pnpr resolver +2/-0

Default new 'Install' override fields to 'None' in pnpr resolver

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to 'Install' literal used by pnpr, preserving behavior.

pnpr/crates/pnpr/src/resolver/resolve.rs

Tests (1) +23 / -0
tests.rsTests for new config fields +23/-0

Tests for new config fields

• Adds tests asserting defaults and correct loading from 'pnpm-workspace.yaml' for 'engineStrict', 'nodeVersion', and 'maxSockets'.

pacquet/crates/config/src/tests.rs

Documentation (3) +754 / -0
README.mdDocument '@pnpm/napi' API and distribution model +63/-0

Document '@pnpm/napi' API and distribution model

• Adds README describing the exported API surface, error semantics, authHeaderByUri usage, supported targets, CI-generated prebuild packaging, and local development steps.

pacquet/npm/napi/README.md

index.d.tsTyped TS contract mirroring pnpm programmatic API shapes +290/-0

Typed TS contract mirroring pnpm programmatic API shapes

• Defines the public TypeScript types for install/rebuild/resolveDependency/pack/parseBareSpecifier/engineVersion and the (currently stubbed) peer-issues call.

pacquet/npm/napi/index.d.ts

NAPI.mdAdd design plan for '@pnpm/napi' bindings +401/-0

Add design plan for '@pnpm/napi' bindings

• Adds a detailed design document describing goals, API mapping to pnpm TS, threading/runtime model, error/log contracts, auth handling, distribution approach, and follow-ups.

pacquet/plans/NAPI.md

Other (12) +688 / -11
pacquet-release-to-npm.ymlExtend release workflow to build/publish '@pnpm/napi' artifacts +34/-10

Extend release workflow to build/publish '@pnpm/napi' artifacts

• Adds cross builds for 'pacquet-napi' using 'napi-release', copies platform '.node' artifacts, includes them in attest/upload steps, injects version into 'pacquet/npm/napi/package.json', generates per-platform packages, and publishes both native and wrapper packages.

.github/workflows/pacquet-release-to-npm.yml

Cargo.tomlAdd 'pacquet-napi' workspace entry + napi deps + 'napi-release' profile +14/-0

Add 'pacquet-napi' workspace entry + napi deps + 'napi-release' profile

• Registers the new 'pacquet-napi' crate, adds 'napi'/'napi-build'/'napi-derive' workspace dependencies, and introduces '[profile.napi-release]' with 'panic = "unwind"' for safe Node hosting.

Cargo.toml

cspell.jsonAllowlist new terms used by NAPI build outputs +2/-0

Allowlist new terms used by NAPI build outputs

• Adds 'libpacquet' and 'napi' to the spellchecker dictionary to avoid CI failures.

cspell.json

build.rsSet up napi-rs build integration +3/-0

Set up napi-rs build integration

• Runs 'napi_build::setup()' so the addon links correctly for Node/NAPI.

pacquet/crates/napi/build.rs

tests.rsTests for overlay mapping and option validation +190/-0

Tests for overlay mapping and option validation

• Adds unit tests covering config cache invalidation, supported/unsupported option handling, and correct mapping of network/proxy/engine options into overlays.

pacquet/crates/napi/src/install/tests.rs

napi_runtime_test_stubs.rsTest-only NAPI runtime symbol stubs +24/-0

Test-only NAPI runtime symbol stubs

• Defines no-op 'no_mangle' stubs for napi runtime symbols referenced by generated trampolines so 'cargo test' binaries link without a Node host.

pacquet/crates/napi/src/napi_runtime_test_stubs.rs

tests.rsTests for origin parsing and 'maxSockets' behavior +69/-1

Tests for origin parsing and 'maxSockets' behavior

• Adds tests for 'origin_of' extraction and async tests validating that 'maxSockets=1' blocks concurrent requests per origin without blocking other origins.

pacquet/crates/network/src/tests.rs

tests.rsUpdate install tests for new 'Install' fields +164/-0

Update install tests for new 'Install' fields

• Adds 'pnpmfile_hook_override: None' and 'workspace_projects_override: None' to test 'Install' literals across suite to match the struct change.

pacquet/crates/package-manager/src/install/tests.rs

tests.rsUpdate registry install tests for new 'Install' fields +3/-0

Update registry install tests for new 'Install' fields

• Defaults 'pnpmfile_hook_override' and 'workspace_projects_override' to 'None' in test 'Install' literals.

pacquet/crates/package-manager/src/install_package_from_registry/tests.rs

tests.rsTests for 'detect_with' and strict engine failure semantics +59/-0

Tests for 'detect_with' and strict engine failure semantics

• Adds tests verifying nodeVersion normalization and that 'engine_strict' hard-fails required incompatible dependencies while lenient mode warns/continues.

pacquet/crates/package-manager/src/installability/tests.rs

package.jsonAdd '@pnpm/napi' wrapper package metadata +32/-0

Add '@pnpm/napi' wrapper package metadata

• Creates the npm wrapper package ('main', 'types', Node >=18) that will depend on per-platform optional native packages generated at release time.

pacquet/npm/napi/package.json

generate-packages.mjsGenerate per-platform native packages and patch optionalDependencies +94/-0

Generate per-platform native packages and patch optionalDependencies

• Generates '@pnpm/napi.<target>' packages from CI-produced 'pnpm-napi.<codeTarget>.node' artifacts and updates '@pnpm/napi' optionalDependencies to reference them.

pacquet/npm/napi/scripts/generate-packages.mjs

@qodo-code-review

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (6) 📘 Rule violations (5) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 51 rules

Grey Divider


Action required

1. Linux libc fallback aborts ✓ Resolved 🐞 Bug ☼ Reliability
Description
On Linux, the loader tries both glibc and musl candidates, but it only falls through on
MODULE_NOT_FOUND; an incompatible first candidate can throw (e.g. ERR_DLOPEN_FAILED) and abort
before the other libc variant is attempted. This can make @pnpm/napi fail to load entirely on some
Linux environments where libc probing is unavailable or the initial guess is wrong.
Code

pacquet/npm/napi/index.js[R17-39]

+// `'glibc' | 'musl' | null` — `null` when the host isn't Linux or the libc
+// can't be probed (`process.report` may be unavailable/disabled). glibc builds
+// set `glibcVersionRuntime`; musl leaves it unset.
+function detectLinuxLibc() {
+  if (process.platform !== 'linux') return null
+  try {
+    return process.report?.getReport()?.header?.glibcVersionRuntime ? 'glibc' : 'musl'
+  } catch {
+    return null
+  }
+}
+
+// Ordered platform triples to try. On Linux both libc variants are attempted
+// (ordered by detection) so a musl host whose libc can't be probed still
+// resolves the `-musl` addon instead of failing on the glibc one; elsewhere
+// there is a single triple.
+function platformTriples() {
+  const { platform, arch } = process
+  if (platform === 'linux') {
+    const order = detectLinuxLibc() === 'musl' ? ['-musl', ''] : ['', '-musl']
+    return order.map((suffix) => `linux-${arch}${suffix}`)
+  }
+  return [`${platform}-${arch}`]
Evidence
platformTriples() generates an ordered list including both libc variants on Linux, but tryLoad()
rethrows any error that is not classified as a missing module; native-addon load failures are
typically not MODULE_NOT_FOUND, so the loop stops before trying the next triple.

pacquet/npm/napi/index.js[17-39]
pacquet/npm/napi/index.js[42-53]

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

### Issue description
On Linux, `platformTriples()` produces both glibc and musl triples, but `tryLoad()` only treats `MODULE_NOT_FOUND` as a retryable error. If the first candidate exists but fails to load due to libc/ABI mismatch, `require()` throws (commonly `ERR_DLOPEN_FAILED`) and the loader never tries the fallback triple.

### Issue Context
This was introduced by adding multi-triple Linux resolution; the error handling must now distinguish “candidate exists but is incompatible” from “hard failure where we should stop”.

### Fix Focus Areas
- pacquet/npm/napi/index.js[17-39]
- pacquet/npm/napi/index.js[42-53]

### Suggested fix
- Update `tryLoad()` (or `loadBinding()` around it) so that for Linux triple candidates it treats known native-addon load failures (at minimum `ERR_DLOPEN_FAILED`, and potentially other native-load error codes/messages) as retryable: push the error into `loadErrors` and return `null` so the loop continues to the next candidate.
- Keep explicit override behavior strict: if `PNPM_NAPI_BINARY` is set and the addon exists but fails to load, fail fast rather than silently falling back to other candidates.

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


2. invalid_manifest_error uses non-pnpm code ✓ Resolved 📘 Rule violation ≡ Correctness
Description
invalid_manifest_error() emits the user-visible code ERR_PNPM_NAPI_INVALID_MANIFEST, which does
not match pnpm’s established ERR_PNPM_* error-code namespace for invalid project manifests. This
can break consumers that rely on pnpm-compatible error codes/messages for control flow and error
translation.
Code

pacquet/crates/napi/src/error.rs[R73-83]

+pub fn invalid_manifest_error(root_dir: &str) -> napi::Error {
+    let envelope = ErrorEnvelope {
+        code: Some("ERR_PNPM_NAPI_INVALID_MANIFEST".to_string()),
+        message: format!("the `manifest` for project `{root_dir}` is not a JSON object"),
+        hint: Some(
+            "Each project's `manifest` must be a plain object with the package.json shape.".into(),
+        ),
+    };
+    match serde_json::to_string(&envelope) {
+        Ok(json) => napi::Error::from_reason(format!("{ENVELOPE_PREFIX}{json}")),
+        Err(_) => napi::Error::from_reason(envelope.message),
Evidence
The new code returns ERR_PNPM_NAPI_INVALID_MANIFEST for an invalid manifest shape, creating a new
user-visible code that diverges from pnpm’s established error codes for invalid project manifests.
pnpm’s codebase demonstrates the canonical invalid-manifest error identifier (INVALID_PACKAGE_JSON
→ ERR_PNPM_INVALID_PACKAGE_JSON), so pacquet should reuse the pnpm-compatible code/message instead
of introducing a new one.

Rule 713473: Align pacquet error codes and messages with pnpm
pacquet/crates/napi/src/error.rs[70-83]
pnpm11/deps/inspection/commands/src/view/index.ts[265-281]

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

## Issue description
`invalid_manifest_error()` currently uses a pacquet-specific error code (`ERR_PNPM_NAPI_INVALID_MANIFEST`) for an invalid project manifest shape. Compliance requires pacquet’s user-facing error codes/messages to align with pnpm’s documented/canonical errors when an equivalent pnpm error exists.

## Issue Context
pnpm uses `INVALID_PACKAGE_JSON` (surfacing as `ERR_PNPM_INVALID_PACKAGE_JSON`) for failures to read/parse a project manifest. A non-object `manifest` provided to the engine binding is an invalid project manifest condition and should reuse the closest pnpm canonical code rather than introducing a new `ERR_PNPM_NAPI_*` code.

## Fix Focus Areas
- pacquet/crates/napi/src/error.rs[70-84]

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


3. Malformed manifest becomes empty ✓ Resolved 🐞 Bug ≡ Correctness
Description
PackageManifest::from_value coerces any non-object JSON (null/string/array/etc.) to {}, so the
Node binding can proceed with an empty manifest instead of rejecting invalid input. This can drive
dependency resolution/lockfile generation from missing data and produce incorrect or destructive
on-disk results (e.g., writing a lockfile that no longer reflects the intended dependencies) without
surfacing the input error.
Code

pacquet/crates/package-manifest/src/lib.rs[R167-174]

+        // A manifest must be a JSON object. A non-object value (array / string /
+        // number) supplied across the FFI boundary would otherwise panic later
+        // when a dependency is inserted via `self.value[key] = ...`; coerce
+        // anything that isn't an object to an empty one so malformed input
+        // degrades gracefully instead of aborting the host process.
+        if !value.is_object() {
+            value = json!({});
+        }
Evidence
The new code explicitly replaces any non-object manifest JSON with {}. The N-API install path
passes JS-provided manifest values into from_value, and the install code later persists lockfiles
derived from manifest dependencies—so coercion can result in installs/lockfiles computed from empty
dependency maps rather than rejecting invalid input.

pacquet/crates/package-manifest/src/lib.rs[158-177]
pacquet/crates/napi/src/install.rs[241-260]
pacquet/crates/package-manager/src/install.rs[1006-1010]
pacquet/crates/package-manager/src/dependencies_graph_to_lockfile.rs[306-313]

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

## Issue description
`PackageManifest::from_value` currently turns any non-object JSON value into an empty object (`{}`), which avoids a panic but also hides invalid input at the FFI boundary. For the N-API surface, this means a consumer bug (or untrusted/incorrect input) can yield an install that appears to succeed while operating on an empty manifest and still writing outputs like `pnpm-lock.yaml`.

## Issue Context
The N-API install path constructs `PackageManifest` directly from JS-provided JSON values; those values are not guaranteed to be objects. Silent coercion changes the failure mode from “explicit invalid input” to “successful run with wrong graph/output”.

## Fix Focus Areas
- pacquet/crates/package-manifest/src/lib.rs[158-178]
- pacquet/crates/napi/src/install.rs[241-260]
- pacquet/crates/napi/src/install.rs[394-404]

## Suggested fix
1. Change `PackageManifest::from_value` to fail closed for non-object input:
  - Either make it `pub fn try_from_value(...) -> Result<PackageManifest, PackageManifestError>` (preferred), or keep `from_value` but add a strict variant and switch N-API to it.
  - Add a dedicated error variant like `PackageManifestError::InvalidManifestJsonType`.
2. In N-API `install`, validate that each `project.manifest` is an object before creating the manifest; return a structured N-API error (with pnpm-style code) when invalid.
3. Keep the “no panic across FFI” property, but ensure invalid input is surfaced as an explicit error rather than being coerced into `{}`.

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


View more (7)
4. Historical wording in test comment ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
A new test comment uses historical phrasing (used to reject) instead of describing the current
behavior. This violates the rule requiring comments to describe current behavior, not past
implementations.
Code

pacquet/crates/napi/src/install/tests.rs[R101-103]

+fn newly_supported_install_options_are_accepted() {
+    // Options the binding used to reject now flow through the engine.
+    let mut options = install_options();
Evidence
PR Compliance ID 772199 forbids historical phrasing like "used to" in comments. The added comment
explicitly says the binding "used to reject" these options.

Rule 772199: Comments must describe current behavior, not historical implementations
pacquet/crates/napi/src/install/tests.rs[101-103]

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 new comment describes historical behavior rather than the current contract.

## Issue Context
Repository guidance requires comments to describe current behavior and avoid "used to" / "previously" phrasing.

## Fix Focus Areas
- pacquet/crates/napi/src/install/tests.rs[101-103]

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


5. Sink not panic-safe ✓ Resolved 🐞 Bug ⛨ Security
Description
install() installs a process-global JS log sink and stats accumulator but only clears them on the
normal return path, so a panic in the worker thread can leave a stale sink/stats active and misroute
subsequent logs across callers. This can leak install paths/package names between independent
operations and makes the addon fragile after a single panic.
Code

pacquet/crates/napi/src/install.rs[R204-222]

+    let had_sink = on_log.is_some();
+    if let Some(sink) = on_log {
+        set_global_log_sink(sink);
+    }
+    let pnpmfile_hook: Option<Arc<dyn PnpmfileHooks>> = read_package_hook
+        .map(|sink| Arc::new(JsReadPackageHook::new(sink)) as Arc<dyn PnpmfileHooks>);
+    begin_stats();
+    let outcome = run_install_inner(options, pnpmfile_hook, EngineMode::Install);
+    let stats = take_stats();
+    if had_sink {
+        clear_global_log_sink();
+    }
+    let store_dir = outcome?;
+    Ok(InstallResult {
+        stats: InstallStatsResult {
+            added: stats.added as f64,
+            removed: stats.removed as f64,
+            linked_to_root: 0.0,
+        },
Evidence
run_install_blocking sets the process-global sink and begins stats, then calls into the engine and
only clears/takes stats after the call returns; if the worker thread panics, that cleanup path is
skipped. The sink is explicitly process-global in reporter_bridge.rs.

pacquet/crates/napi/src/install.rs[199-227]
pacquet/crates/napi/src/reporter_bridge.rs[33-56]
pacquet/crates/napi/src/reporter_bridge.rs[70-97]

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

## Issue description
`run_install_blocking` sets global process state (`set_global_log_sink`, `begin_stats`) and clears it only on the normal path. If `run_install_inner` (or anything before `clear_global_log_sink`) panics, the oneshot sender is dropped, the JS side gets "worker thread panicked", but the global sink/stats remain installed.

## Issue Context
This addon is built with `panic = "unwind"` in `napi-release`, so thread panics are plausible and should not corrupt global state.

## Fix Focus Areas
- Add a small RAII guard that restores/clears the sink and stats on `Drop`.
- Wrap the worker-thread body in `std::panic::catch_unwind` so cleanup always runs and you can return a structured napi error.
- Use the return value of `set_global_log_sink` (previous sink) and restore it on exit (don’t just clear).

### Code pointers
- pacquet/crates/napi/src/install.rs[199-227]
- pacquet/crates/napi/src/reporter_bridge.rs[33-56]
- pacquet/crates/napi/src/reporter_bridge.rs[70-97]

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


6. napi deps added at workspace 📘 Rule violation ⌂ Architecture
Description
napi, napi-build, and napi-derive were added at the workspace level even though the new
pacquet-napi crate is the consumer in this PR. This violates the rule to scope new Rust
dependencies to the crate that uses them.
Code

Cargo.toml[R125-127]

+napi = { version = "3.10.3", default-features = false, features = ["napi8", "serde-json", "tokio_rt", "async"] }
+napi-build = { version = "2.3.2" }
+napi-derive = { version = "3.5.9" }
Evidence
PR Compliance ID 713471 requires scoping new Rust dependencies to the specific crate unless multiple
crates use them. The root Cargo.toml adds the napi* crates, and pacquet/crates/napi/Cargo.toml
is a direct consumer via { workspace = true }.

Rule 713471: Scope new Rust dependencies to the crate that uses them
Cargo.toml[125-127]
pacquet/crates/napi/Cargo.toml[33-45]

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

## Issue description
New Rust dependencies were added to the workspace dependency table even though they appear to be used by only one crate in this PR.

## Issue Context
`pacquet-napi` depends on `napi`, `napi-derive`, and `napi-build`.

## Fix Focus Areas
- Cargo.toml[125-127]
- pacquet/crates/napi/Cargo.toml[33-45]

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


7. Branch URL in homepage 📘 Rule violation ⚙ Maintainability
Description
pacquet/npm/napi/package.json sets homepage to a branch-based GitHub /tree/main/... URL, which
is not a commit-SHA permalink. This breaks the requirement to reference code with immutable SHA
links.
Code

pacquet/npm/napi/package.json[12]

+  "homepage": "https://github.com/pnpm/pnpm/tree/main/pacquet",
Evidence
PR Compliance ID 713443 requires GitHub /blob/ or /tree/ links to use a commit SHA rather than a
branch name. The new homepage value uses /tree/main/, which is explicitly branch-based.

Rule 713443: Reference code with commit SHA links, not branch-based URLs
pacquet/npm/napi/package.json[12-12]

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

## Issue description
`homepage` uses a branch-based GitHub code URL (`/tree/main/...`), which violates the requirement to avoid branch-based code links.

## Issue Context
This value is user-visible package metadata and should not point at a mutable branch reference.

## Fix Focus Areas
- pacquet/npm/napi/package.json[12-12]

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


8. reject_non_empty_list takes &Vec ✓ Resolved 📘 Rule violation ➹ Performance
Description
reject_non_empty_list accepts Option<&Vec<Value>> even though it only needs slice behavior,
unnecessarily constraining callers. This violates the requirement to use the most general borrowed
parameter types.
Code

pacquet/crates/napi/src/install.rs[R519-520]

+fn reject_non_empty_list<Value>(value: Option<&Vec<Value>>, option: &str) -> napi::Result<()> {
+    reject_if(value.is_some_and(|items| !items.is_empty()), option)
Evidence
PR Compliance ID 713447 forbids references to owned containers like &Vec<T> when a slice would
suffice. The new helper is declared as Option<&Vec<Value>> and only checks emptiness, which can be
done on &[Value].

Rule 713447: Use the most general borrowed parameter types to avoid unnecessary allocations
pacquet/crates/napi/src/install.rs[519-520]

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 helper function takes `Option<&Vec<T>>` instead of a more general borrowed type.

## Issue Context
Using `&Vec<T>` is less flexible than `&[T]` (or `impl AsRef<[T]>`) and violates the codebase rule to prefer general borrowed parameter types.

## Fix Focus Areas
- pacquet/crates/napi/src/install.rs[519-521]

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


9. Missing trailing comma in install ✓ Resolved 📘 Rule violation ⚙ Maintainability
Description
Multi-line TypeScript function parameter lists in pacquet/npm/napi/index.d.ts omit a trailing
comma on the last parameter. This increases diff churn and violates the trailing-comma requirement
for multi-line constructs.
Code

pacquet/npm/napi/index.d.ts[R192-196]

+export function install(
+  options: InstallOptions,
+  onLog?: LogListener,
+  readPackageHook?: ReadPackageHook
+): Promise<InstallResult>
Evidence
PR Compliance ID 713434 requires trailing commas for multi-line TypeScript constructs. The
install(...) declaration spans multiple lines and ends without a trailing comma after
readPackageHook?: ReadPackageHook.

Rule 713434: Require trailing commas in TypeScript collections and multi-line constructs
pacquet/npm/napi/index.d.ts[192-196]

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

## Issue description
TypeScript multi-line parameter lists are missing a trailing comma on the final parameter.

## Issue Context
The repository compliance rule requires trailing commas in multi-line TypeScript collections and multi-line constructs (including parameter lists).

## Fix Focus Areas
- pacquet/npm/napi/index.d.ts[192-208]

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


10. Pack races global sink ✓ Resolved 🐞 Bug ⛨ Security
Description
pack() also sets/clears the same process-global log sink but does not acquire the serialization
lock used by install/rebuild, so concurrent calls can overwrite each other’s sink and route logs to
the wrong JS callback. This can leak log events between unrelated operations in the same Node
process.
Code

pacquet/crates/napi/src/pack.rs[R49-53]

+pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
+    let had_sink = on_log.is_some();
+    if let Some(sink) = on_log {
+        set_global_log_sink(sink);
+    }
Evidence
install() explicitly serializes engine calls behind install_lock, while pack() manipulates the
same global sink without acquiring any lock. The sink is defined as process-global, so concurrent
access overwrites the single slot.

pacquet/crates/napi/src/pack.rs[48-88]
pacquet/crates/napi/src/install.rs[168-197]
pacquet/crates/napi/src/reporter_bridge.rs[33-56]

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

## Issue description
`pack()` uses the same global log sink as `install()`/`rebuild()`, but it does not participate in the serialization (`install_lock`) that those APIs use. That means `pack()` can run concurrently with `install()` and overwrite the sink slot.

## Issue Context
The sink slot is a single global `RwLock<Option<LogSink>>`. Any overlap will misroute events.

## Fix Focus Areas
- Ensure every API that calls `set_global_log_sink` uses the same global lock (rename `install_lock` to something like `engine_call_lock` and reuse it in `pack`).
- Alternatively, change the reporter bridge design to be per-call/per-thread (avoid process-global sink), but that’s larger.

### Code pointers
- pacquet/crates/napi/src/pack.rs[48-88]
- pacquet/crates/napi/src/install.rs[168-197]
- pacquet/crates/napi/src/reporter_bridge.rs[33-56]

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



Remediation recommended

11. Blocking pool still spawns 🐞 Bug ⛨ Security ⭐ New
Description
resolveDependency now builds a per-call current-thread Tokio runtime to avoid a per-call worker
pool, but the npm resolver path uses tokio::task::spawn_blocking for packument parsing, which will
still create blocking threads per runtime. Under concurrent resolveDependency calls, this can
still amplify OS thread count/memory usage and enables resource-exhaustion (DoS) behavior despite
the runtime change.
Code

pacquet/crates/napi/src/resolve.rs[R147-156]

+    // A single dependency resolve is one packument fetch — no task parallelism
+    // to exploit — and this already runs on a dedicated worker thread. Use a
+    // current-thread runtime so a `resolveDependency` call spawns no extra
+    // worker-thread pool (a per-call multi-thread runtime would multiply threads
+    // under concurrent resolves). The install path keeps a multi-thread runtime
+    // because it fetches packages in parallel.
+    let runtime =
+        tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|error| {
+            napi::Error::from_reason(format!("failed to build tokio runtime: {error}"))
+        })?;
Evidence
The changed code builds a per-call current-thread runtime. The npm resolver’s metadata fetch/parse
path uses spawn_blocking, which relies on Tokio’s blocking pool; with per-call runtimes, this
blocking pool is per-call as well.

pacquet/crates/napi/src/resolve.rs[147-156]
pacquet/crates/resolving-npm-resolver/src/pick_package.rs[648-666]
pacquet/crates/resolving-npm-resolver/src/fetch_full_metadata_cached.rs[168-220]

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

### Issue description
`resolveDependency` creates a fresh `tokio::runtime` per call using `new_current_thread()` to avoid spawning a per-call worker-thread pool. However, the downstream resolver invokes `tokio::task::spawn_blocking` during metadata/packument processing, which will still cause Tokio to create a blocking pool for each per-call runtime. With concurrent `resolveDependency` calls, this can still create many additional OS threads and increase memory pressure.

### Issue Context
Even though the runtime is current-thread, `spawn_blocking` is used on the resolve path (packument parse/persist), so the “no extra thread pool” assumption is incomplete.

### Fix Focus Areas
- pacquet/crates/napi/src/resolve.rs[147-156]

### Suggested fix direction
- Configure the per-call runtime builder to strictly cap blocking threads (e.g., set a very small `max_blocking_threads`) since `resolveDependency` is designed to do minimal work.
- Alternatively (stronger), avoid per-call runtime construction entirely by reusing a shared runtime for resolves, so the blocking pool is shared rather than multiplied per call.

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


12. PNPM_NAPI_BINARY loads directory 🐞 Bug ⛨ Security
Description
PNPM_NAPI_BINARY is validated only by a .node suffix, and tryLoad() only checks existsSync,
so an existing directory ending in .node can be passed to require() and resolved as a JS module
(executing JS) instead of a native addon file. This breaks the stated “only ever hand a .node
addon to require()” guarantee and expands the impact of an untrusted or misconfigured environment
override.
Code

pacquet/npm/napi/index.js[R78-92]

+  const triples = platformTriples()
+  const loadErrors = []
+  // Only ever hand a `.node` addon to require(). Without this, a non-.node
+  // PNPM_NAPI_BINARY value would be require()'d as an arbitrary JS module.
+  const explicit = process.env.PNPM_NAPI_BINARY
+  if (explicit && !explicit.endsWith('.node')) {
+    throw new Error(`PNPM_NAPI_BINARY must point to a .node addon file, got: ${explicit}`)
+  }
+  const candidates = [
+    explicit,
+    ...triples.flatMap((triple) => [
+      `@pnpm/napi.${triple}`,
+      path.join(__dirname, `pnpm-napi.${triple}.node`),
+    ]),
+    path.join(__dirname, 'pnpm-napi.node'),
Evidence
The loader only checks that the env var ends with .node, then treats any existing .node path as
loadable and calls require(candidate); it does not verify that the candidate is a file, so
directories can be loaded as modules.

pacquet/npm/napi/index.js[77-93]
pacquet/npm/napi/index.js[42-46]

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

### Issue description
`loadBinding()` intends to ensure `PNPM_NAPI_BINARY` can’t be used to `require()` arbitrary JS by enforcing a `.node` suffix, but the current checks don’t ensure the value points to an actual `.node` *file*. A directory named `something.node` (or other non-file path) can pass the checks and be loaded as a JS module via Node’s directory/module resolution.

### Issue Context
This is specifically about the `PNPM_NAPI_BINARY` override path. The default candidates (`@pnpm/napi.<triple>` and packaged `.node` files) can continue to use the existing logic.

### Fix Focus Areas
- pacquet/npm/napi/index.js[77-93]
- pacquet/npm/napi/index.js[42-46]

### Suggested fix
- If `PNPM_NAPI_BINARY` is set:
 - Resolve it to an absolute path (`path.resolve(explicit)`), and use `fs.statSync` (or `fs.lstatSync`) to require `isFile()`.
 - Enforce `.node` extension on the resolved path, and reject directories/symlinks-to-directories.
 - Call `require()` with the absolute resolved path (so it cannot be treated as a package specifier).
- Optionally harden `tryLoad()` for `.node` candidates by replacing `existsSync()` with an `isFile()` check so packaged path candidates can’t be directories either.

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


13. detectLinuxLibc duplicated in loader 📘 Rule violation ⚙ Maintainability
Description
pacquet/npm/napi/index.js introduces a detectLinuxLibc() implementation that duplicates existing
libc-detection logic already present in pacquet/npm/pnpm/install.js. This violates the guideline
to extract and reuse shared modules, increasing the risk of drift if either implementation changes.
Code

pacquet/npm/napi/index.js[R17-27]

+// `'glibc' | 'musl' | null` — `null` when the host isn't Linux or the libc
+// can't be probed (`process.report` may be unavailable/disabled). glibc builds
+// set `glibcVersionRuntime`; musl leaves it unset.
+function detectLinuxLibc() {
+  if (process.platform !== 'linux') return null
+  try {
+    return process.report?.getReport()?.header?.glibcVersionRuntime ? 'glibc' : 'musl'
+  } catch {
+    return null
+  }
+}
Evidence
Rule 713439 requires reusing shared logic instead of duplicating similar implementations across
packages/modules. The new loader defines detectLinuxLibc() while an existing, near-identical
detectLinuxLibc() already exists in the pnpm wrapper script.

Rule 713439: Avoid reimplementing existing functionality; extract and reuse shared modules
pacquet/npm/napi/index.js[17-27]
pacquet/npm/pnpm/install.js[163-174]

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

## Issue description
`detectLinuxLibc()` logic is duplicated across multiple JS entrypoints (`@pnpm/napi` loader and the existing `pnpm` wrapper scripts). This increases maintenance cost and risks behavioral divergence over time.

## Issue Context
A nearly identical `detectLinuxLibc()` already exists in `pacquet/npm/pnpm/install.js`. The new `pacquet/npm/napi/index.js` adds a second copy.

## Fix Focus Areas
- pacquet/npm/napi/index.js[17-27]
- pacquet/npm/pnpm/install.js[163-174]

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


View more (7)
14. Secrets in cache-key string 🐞 Bug ⛨ Security
Description
resolve_config() computes its cache key by hashing format!("{overlay:?}"), and ConfigOverlay’s
derived Debug output includes auth_header_by_uri values (Bearer/Basic credentials). This
materializes credentials into a temporary plaintext String and allocates it on every config
resolve, increasing secret exposure surface and adding avoidable overhead.
Code

pacquet/crates/napi/src/config.rs[R125-134]

+fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
+    let mut hasher = DefaultHasher::new();
+    dir.hash(&mut hasher);
+    // The overlay's `Debug` string covers every field. This is only stable
+    // because the map-typed fields are `BTreeMap` (ordered) rather than
+    // `HashMap` (per-instance random iteration order) — otherwise logically
+    // identical overlays would hash differently, miss the cache, and leak a
+    // fresh `Config` on every call.
+    format!("{overlay:?}").hash(&mut hasher);
+    hash_config_sources(dir, &mut hasher);
Evidence
ConfigOverlay derives Debug and includes auth_header_by_uri, documented as carrying
pre-computed Authorization header values. cache_key() hashes format!("{overlay:?}"), which
necessarily formats those header values into a plaintext String before hashing.

pacquet/crates/napi/src/config.rs[33-37]
pacquet/crates/napi/src/config.rs[99-106]
pacquet/crates/napi/src/config.rs[125-134]
pacquet/crates/napi/src/config/tests.rs[10-20]

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

## Issue description
`cache_key()` hashes `format!("{overlay:?}")`, which (via derived `Debug`) includes sensitive `auth_header_by_uri` header values. This creates an avoidable plaintext `String` containing credentials and adds per-call allocation cost.

## Issue Context
The cache key is used for interning leaked `Config` values in a long-lived Node process, so it is computed on every `resolve_config()` call.

## Fix Focus Areas
- pacquet/crates/napi/src/config.rs[33-37]
- pacquet/crates/napi/src/config.rs[99-106]
- pacquet/crates/napi/src/config.rs[125-135]

## Suggested fix
1. Stop using `format!("{overlay:?}")` for hashing.
2. Implement a dedicated hashing routine for `ConfigOverlay` that feeds each field into the hasher directly (iterate `BTreeMap`/`BTreeSet` in order; hash both keys and values).
3. (Optional but recommended) Implement a custom `Debug` for `ConfigOverlay` that redacts secret-bearing fields (e.g., show counts/keys only for `auth_header_by_uri`) so accidental logging won’t expose credentials.
4. Update/extend tests to assert cache-key stability without relying on `Debug` formatting.

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


15. Resolve spawns huge threads 🐞 Bug ☼ Reliability
Description
resolveDependency spawns a new OS thread with a 32 MiB stack per call and has no concurrency
limiter, allowing a consumer to exhaust memory/CPU by issuing many concurrent resolves. This is
especially risky for servers that may call resolveDependency per request or per dependency.
Code

pacquet/crates/napi/src/resolve.rs[R68-78]

+    let (tx, rx) = tokio::sync::oneshot::channel();
+    std::thread::Builder::new()
+        .name("pnpm-napi-resolve".to_string())
+        .stack_size(32 * 1024 * 1024)
+        .spawn(move || {
+            let _ = tx.send(run_resolve_blocking(wanted, &options));
+        })
+        .map_err(|error| {
+            napi::Error::from_reason(format!("failed to spawn resolve thread: {error}"))
+        })?;
+    rx.await.map_err(|_| napi::Error::from_reason("resolve worker thread panicked"))?
Evidence
The function unconditionally allocates a new thread with a 32MiB stack per call and does not
serialize/limit concurrent calls.

pacquet/crates/napi/src/resolve.rs[63-79]

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

## Issue description
`resolve_dependency` creates a fresh 32MiB-stack thread per call. Unlike install/rebuild, there is no global lock, so concurrency is unbounded.

## Issue Context
Even without malicious input, a consumer can accidentally `Promise.all` many resolves.

## Fix Focus Areas
- Prefer `tokio::task::spawn_blocking` (on the existing NAPI Tokio runtime) instead of a new OS thread.
- If a dedicated thread is required, use a small bounded thread pool and a semaphore to limit in-flight resolves.
- Re-evaluate the need for a 32MiB stack for this call path; reduce if possible.

### Code pointers
- pacquet/crates/napi/src/resolve.rs[63-79]

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


16. Stats lock on hot path 🐞 Bug ➹ Performance
Description
NodeBridgeReporter::emit locks a global Mutex on every log event just to check whether the event
affects stats, adding avoidable contention in install hot paths. deps_requiring_build dedupe uses
Vec::contains, causing O(n²) behavior when many packages are reported.
Code

pacquet/crates/napi/src/reporter_bridge.rs[R92-113]

+fn accumulate_stats(event: &LogEvent) {
+    let Ok(mut guard) = stats_slot().lock() else { return };
+    let Some(stats) = guard.as_mut() else { return };
+    match event {
+        LogEvent::Stats(log) => match &log.message {
+            StatsMessage::Added { added, .. } => stats.added += *added,
+            StatsMessage::Removed { removed, .. } => stats.removed += *removed,
+        },
+        LogEvent::IgnoredScripts(log) => {
+            for name in &log.package_names {
+                if !stats.deps_requiring_build.contains(name) {
+                    stats.deps_requiring_build.push(name.clone());
+                }
+            }
+        }
+        _ => {}
+    }
+}
+
+/// [`Reporter`] that forwards every event to the global JS sink.
+pub struct NodeBridgeReporter;
+
Evidence
The code locks stats_slot() before matching on the event variant, so the lock is taken for every
event; dedupe is linear search over a growing Vec.

pacquet/crates/napi/src/reporter_bridge.rs[58-110]

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

## Issue description
`accumulate_stats` unconditionally acquires a global mutex for every reporter event, even though only `Stats` and `IgnoredScripts` variants update stats. Within `IgnoredScripts`, dedupe is done via `Vec::contains`.

## Issue Context
Reporter emission can be frequent; extra locking and O(n²) dedupe can regress install throughput.

## Fix Focus Areas
- Pattern-match `event` before locking; only lock for `LogEvent::Stats` and `LogEvent::IgnoredScripts`.
- Use a `HashSet<String>` (or `BTreeSet`) for `deps_requiring_build` while accumulating, and convert to `Vec` at the end.
- Consider using atomics for `added/removed` if you want to eliminate locking for `StatsMessage`.

### Code pointers
- pacquet/crates/napi/src/reporter_bridge.rs[58-110]

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


17. New napi crates lack approval 📘 Rule violation § Compliance
Description
The PR introduces new third-party crates (napi, napi-build, napi-derive) in workspace
dependencies, which requires explicit approval under the dependency policy. Without documented
approval, this is a compliance violation.
Code

Cargo.toml[R125-127]

+napi = { version = "3.10.3", default-features = false, features = ["napi8", "serde-json", "tokio_rt", "async"] }
+napi-build = { version = "2.3.2" }
+napi-derive = { version = "3.5.9" }
Evidence
PR Compliance ID 713465 forbids introducing new third-party crates without explicit approval. The
diff adds napi, napi-build, and napi-derive as new workspace dependencies.

Rule 713465: Do not introduce new third-party crates without explicit approval
Cargo.toml[125-127]

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

## Issue description
New third-party crates were added to the workspace dependency set, but the policy requires explicit approval for each new crate.

## Issue Context
This PR adds `napi`, `napi-build`, and `napi-derive` to workspace dependencies.

## Fix Focus Areas
- Cargo.toml[125-127]

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


18. Config cache key unstable ✓ Resolved 🐞 Bug ➹ Performance
Description
resolve_config() interns leaked &'static Config values behind a DashMap<u64, …> key derived
from format!("{overlay:?}") and file contents; this is prone to cache misses (Debug output for
map-like fields) and can grow without bound in long-lived Node processes. It also relies on a single
64-bit hash without verifying equality, making (theoretical) collisions able to return the wrong
config including registry/auth policy.
Code

pacquet/crates/napi/src/config.rs[R123-136]

+fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
+    let mut hasher = DefaultHasher::new();
+    dir.hash(&mut hasher);
+    format!("{overlay:?}").hash(&mut hasher);
+    hash_config_sources(dir, &mut hasher);
+    hasher.finish()
+}
+
+fn hash_config_sources(dir: &Path, hasher: &mut DefaultHasher) {
+    hash_file(&dir.join(".npmrc"), hasher);
+
+    let workspace_dir = std::env::var_os("NPM_CONFIG_WORKSPACE_DIR")
+        .or_else(|| std::env::var_os("npm_config_workspace_dir"))
+        .filter(|value| !value.is_empty())
Evidence
The cache key is computed by hashing a Debug-formatted overlay into a DefaultHasher, then the
cache stores leaked configs keyed only by the resulting u64 and never evicts, so misses accumulate
permanently.

pacquet/crates/napi/src/config.rs[116-218]

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 config interning cache uses a `u64` hash key built from `format!("{overlay:?}")` plus config-source file bytes. This makes cache effectiveness sensitive to Debug formatting and provides no collision check, while the cache grows forever (each miss leaks a new `Config`).

## Issue Context
This is in a Node addon intended for long-lived processes that may perform many installs/resolves across directories.

## Fix Focus Areas
- Replace Debug-string hashing with deterministic serialization (e.g., derive/implement `Serialize` for `ConfigOverlay` and hash canonical JSON or bincode; ensure map fields are ordered via `BTreeMap`/sorted vecs before hashing).
- Use a wider digest (e.g., 128/256-bit) and/or store the full serialized key alongside the hash and verify equality on lookup.
- Add a bounded eviction policy (LRU) or scope the cache to a caller-provided context object.

### Code pointers
- pacquet/crates/napi/src/config.rs[116-218]
- pacquet/crates/napi/src/config.rs[174-186]

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


19. #[unsafe(no_mangle)] missing justification 📘 Rule violation ⛨ Security
Description
Only the first #[unsafe(no_mangle)] in napi_runtime_test_stubs.rs has an adjacent justification
comment; later #[unsafe(no_mangle)] uses do not. This violates the requirement that each unsafe
construct has its own nearby justification and safety invariants.
Code

pacquet/crates/napi/src/napi_runtime_test_stubs.rs[R20-24]

+#[unsafe(no_mangle)]
+extern "C" fn napi_delete_reference() {}
+
+#[unsafe(no_mangle)]
+extern "C" fn napi_reference_unref() {}
Evidence
PR Compliance ID 713477 requires a justification comment immediately above (or on) each unsafe
construct. The second and third #[unsafe(no_mangle)] attributes appear without their own adjacent
justification comment.

Rule 713477: Require justification comments for each unsafe code block
pacquet/crates/napi/src/napi_runtime_test_stubs.rs[20-24]

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

## Issue description
Multiple `#[unsafe(no_mangle)]` attributes were added, but only the first one has an adjacent explanation.

## Issue Context
The compliance rule requires an immediately-adjacent justification for every unsafe construct, including unsafe attributes, describing why it is needed and what invariants make it safe.

## Fix Focus Areas
- pacquet/crates/napi/src/napi_runtime_test_stubs.rs[17-24]

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


20. Mutex poison triggers panic 🐞 Bug ☼ Reliability
Description
HostSocketLimit::acquire uses expect() on a Mutex, so any prior panic while holding that lock
poisons it and causes all future acquires (and thus requests) to panic. In the N-API build
(panic=unwind), this can repeatedly kill worker threads and leave global addon state in a bad
configuration.
Code

pacquet/crates/network/src/lib.rs[R160-170]

+    async fn acquire(&self, url: &str) -> Option<OwnedSemaphorePermit> {
+        let origin = origin_of(url)?;
+        // Lock only long enough to look up (or mint) the origin's semaphore and
+        // clone its `Arc` — never held across the `.await` below.
+        let semaphore = {
+            let mut map = self.per_origin.lock().expect("host-socket-limit mutex poisoned");
+            Arc::clone(
+                map.entry(origin).or_insert_with(|| Arc::new(Semaphore::new(self.max.get()))),
+            )
+        };
+        Some(semaphore.acquire_owned().await.expect("host-socket semaphore is never closed"))
Evidence
The code path unconditionally panics on a poisoned mutex, and this lock is taken in the per-request
acquire path when maxSockets is enabled.

pacquet/crates/network/src/lib.rs[156-171]

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 new `HostSocketLimit` uses `Mutex::lock().expect(...)`. A poisoned mutex should not deterministically crash all future requests.

## Issue Context
Poisoning can happen if any panic occurs while holding the lock (including unrelated bugs). In a host process (Node), turning one panic into persistent failure is costly.

## Fix Focus Areas
- Replace `expect(...)` with poison recovery: `match lock() { Ok(g) => g, Err(e) => e.into_inner() }`.
- Alternatively use `parking_lot::Mutex` (no poisoning) if acceptable in this crate.
- Ensure any remaining `expect` messages are not in attacker-influenced hot paths.

### Code pointers
- pacquet/crates/network/src/lib.rs[156-171]

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


Grey Divider

Qodo Logo

Comment thread pacquet/npm/napi/package.json Resolved
Comment thread pacquet/npm/napi/index.d.ts Resolved
Comment thread pacquet/crates/napi/src/install.rs Resolved
Comment thread Cargo.toml Resolved
Comment thread pacquet/crates/napi/src/install.rs Resolved
Comment thread pacquet/crates/napi/src/pack.rs Resolved
@qodo-code-review

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 034d839

Warning

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

CategorySuggestion                                                                                                                                    Impact
Possible issue
Honor per-origin socket limits

Apply config.max_sockets to the NAPI resolveDependency network client.

pacquet/crates/napi/src/resolve.rs [97-109]

 let http_client = Arc::new(
     ThrottledClient::for_installs(
         &config.proxy,
         &config.tls,
         &config.tls_by_uri,
         &NetworkSettings {
             network_concurrency: config.network_concurrency,
             fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
             user_agent: config.user_agent.clone(),
         },
     )
-    .map_err(|error| to_napi_error(&error))?,
+    .map_err(|error| to_napi_error(&error))?
+    .with_max_sockets_per_host(config.max_sockets),
 );
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The PR introduces max_sockets handling but misses applying it in the NAPI resolveDependency client, which can lead to inconsistent network behavior.

High
Fail on invalid local address

Validate networkConfig.localAddress and return an error on parsing failure
instead of silently ignoring it.

pacquet/crates/napi/src/install.rs [559-570]

 fn build_tls_config(input: &NetworkConfigInput) -> napi::Result<TlsConfig> {
+    let local_address = match input.local_address.as_deref() {
+        None => None,
+        Some(value) => Some(value.parse::<IpAddr>().map_err(|_| {
+            unsupported_option_error("install", "networkConfig.localAddress")
+        })?),
+    };
+
     Ok(TlsConfig {
         ca: input.ca.as_ref().map(parse_string_list).transpose()?.unwrap_or_default(),
         cert: input.cert.as_ref().map(parse_single_string).transpose()?.flatten(),
         key: input.key.clone(),
         strict_ssl: input.strict_ssl,
-        local_address: input
-            .local_address
-            .as_deref()
-            .and_then(|value| value.parse::<IpAddr>().ok()),
+        local_address,
     })
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: Properly returning a parsing error for local_address prevents masking misconfigurations that could cause unexpected network behavior.

Medium
Fix cross-compile artifact selection

Use matrix.target instead of runner.os to accurately determine the file
extension of the built library.

.github/workflows/pacquet-release-to-npm.yml [123-131]

 - name: Prepare NAPI addon
   shell: bash
   run: |
-    case "${{ runner.os }}" in
-      Windows) source="target/${{ matrix.target }}/napi-release/pacquet_napi.dll" ;;
-      macOS) source="target/${{ matrix.target }}/napi-release/libpacquet_napi.dylib" ;;
-      *) source="target/${{ matrix.target }}/napi-release/libpacquet_napi.so" ;;
+    case "${{ matrix.target }}" in
+      *-pc-windows-gnu|*-pc-windows-msvc)
+        source="target/${{ matrix.target }}/napi-release/pacquet_napi.dll"
+        ;;
+      *-apple-darwin)
+        source="target/${{ matrix.target }}/napi-release/libpacquet_napi.dylib"
+        ;;
+      *)
+        source="target/${{ matrix.target }}/napi-release/libpacquet_napi.so"
+        ;;
     esac
+
+    test -f "$source" || { echo "Missing NAPI addon at $source" >&2; exit 1; }
     cp "$source" "pnpm-napi.${{ matrix.code-target }}.node"
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: Using the Rust target triple to determine the built artifact's extension is significantly more robust than relying on runner.os, particularly because cross is often used for cross-compiling architectures and OSes.

Medium
Recover from poisoned locks

Use into_inner() to recover from poisoned locks in the reporter and stats slots.

pacquet/crates/napi/src/reporter_bridge.rs [44-90]

 pub fn set_global_log_sink(sink: LogSink) -> Option<LogSink> {
-    match sink_slot().write() {
-        Ok(mut guard) => guard.replace(sink),
-        Err(_) => None,
-    }
+    let mut guard = sink_slot().write().unwrap_or_else(|poisoned| poisoned.into_inner());
+    guard.replace(sink)
 }
 
 pub fn clear_global_log_sink() {
-    if let Ok(mut guard) = sink_slot().write() {
-        *guard = None;
-    }
+    let mut guard = sink_slot().write().unwrap_or_else(|poisoned| poisoned.into_inner());
+    *guard = None;
 }
 
 pub fn begin_stats() {
-    if let Ok(mut guard) = stats_slot().lock() {
-        *guard = Some(InstallStats::default());
-    }
+    let mut guard = stats_slot().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+    *guard = Some(InstallStats::default());
 }
 
 pub fn take_stats() -> InstallStats {
-    stats_slot().lock().ok().and_then(|mut guard| guard.take()).unwrap_or_default()
+    let mut guard = stats_slot().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+    guard.take().unwrap_or_default()
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: Recovering from poisoned locks improves the process-global state's resilience against transient thread panics.

Low
Handle empty version overrides

Return None from normalize_node_version for empty strings to properly fallback
to auto-detection.

pacquet/crates/package-manager/src/installability.rs [283-305]

 pub fn detect_with(engine_strict: bool, node_version: Option<String>) -> Self {
-    match node_version.map(|version| normalize_node_version(&version)) {
+    match node_version.and_then(|version| normalize_node_version(&version)) {
         Some(node_version) => Self {
             node_version,
             node_detected: true,
             os: pacquet_graph_hasher::host_platform(),
             cpu: pacquet_graph_hasher::host_arch(),
             libc: pacquet_graph_hasher::host_libc(),
             supported_architectures: None,
             engine_strict,
         },
         None => Self { engine_strict, ..Self::detect() },
     }
 }
 }
 
 /// Canonicalize a Node.js version string for the engine check: trim surrounding
 /// whitespace and drop a single leading `v` (`v22.11.0` → `22.11.0`) so a value
 /// copied from `process.version` / `node --version` parses as exact semver.
-fn normalize_node_version(version: &str) -> String {
+fn normalize_node_version(version: &str) -> Option<String> {
     let trimmed = version.trim();
-    trimmed.strip_prefix('v').unwrap_or(trimmed).to_string()
+    if trimmed.is_empty() {
+        return None;
+    }
+    Some(trimmed.strip_prefix('v').unwrap_or(trimmed).to_string())
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: Handling empty string cases prevents parsing failures and ensures detect_with falls back correctly to auto-detection.

Low
Normalize paths before matching

Normalize paths before comparing the root project directory to avoid false
negatives due to varying path formats.

pacquet/crates/napi/src/install.rs [237-252]

 let dir = PathBuf::from(&options.dir);
+let dir_norm = normalize_path_for_compare(&dir);
 
 // The root importer is the project at `dir`; any others are siblings. A
 // lone project takes the plain (non-workspace) install path; multiple
 // importers are handed to the engine via `workspace_projects_override`.
 let root_manifest_value = options
     .projects
     .iter()
-    .find(|project| std::path::Path::new(&project.root_dir) == dir)
+    .find(|project| normalize_path_for_compare(std::path::Path::new(&project.root_dir)) == dir_norm)
     .map(|project| project.manifest.clone())
     .ok_or_else(|| {
         napi::Error::from_reason(format!(
             "install options had no project entry for the install dir {}",
             options.dir,
         ))
     })?;
 
+fn normalize_path_for_compare(path: &std::path::Path) -> std::path::PathBuf {
+    let mut out = std::path::PathBuf::new();
+    for component in path.components() {
+        if matches!(component, std::path::Component::CurDir) {
+            continue;
+        }
+        out.push(component.as_os_str());
+    }
+    out
+}
+
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: Provides a defensive normalization for path comparison, improving robustness, though the host might already provide consistent path formats.

Low
  • More

Previous suggestions

Suggestions up to commit 6f84945
CategorySuggestion                                                                                                                                    Impact
Possible issue
Fix cross-target artifact selection

Update the case statement to use matrix.code-target instead of runner.os for
selecting the correct NAPI addon file extension.

.github/workflows/pacquet-release-to-npm.yml [123-131]

 - name: Prepare NAPI addon
   shell: bash
   run: |
-    case "${{ runner.os }}" in
-      Windows) source="target/${{ matrix.target }}/napi-release/pacquet_napi.dll" ;;
-      macOS) source="target/${{ matrix.target }}/napi-release/libpacquet_napi.dylib" ;;
+    case "${{ matrix.code-target }}" in
+      win32-*) source="target/${{ matrix.target }}/napi-release/pacquet_napi.dll" ;;
+      darwin-*) source="target/${{ matrix.target }}/napi-release/libpacquet_napi.dylib" ;;
       *) source="target/${{ matrix.target }}/napi-release/libpacquet_napi.so" ;;
     esac
     cp "$source" "pnpm-napi.${{ matrix.code-target }}.node"
Suggestion importance[1-10]: 10

__

Why: Using runner.os reflects the GitHub Actions runner rather than the build target, which completely breaks artifact selection for cross-compiled targets, making this a critical bug fix.

High
Enforce per-origin socket cap

Apply with_max_sockets_per_host(config.max_sockets) to the HTTP client in
resolve.rs.

pacquet/crates/napi/src/resolve.rs [97-109]

     let http_client = Arc::new(
         ThrottledClient::for_installs(
             &config.proxy,
             &config.tls,
             &config.tls_by_uri,
             &NetworkSettings {
                 network_concurrency: config.network_concurrency,
                 fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
                 user_agent: config.user_agent.clone(),
             },
         )
-        .map_err(|error| to_napi_error(&error))?,
+        .map_err(|error| to_napi_error(&error))?
+        .with_max_sockets_per_host(config.max_sockets),
     );
Suggestion importance[1-10]: 8

__

Why: Applying the max_sockets configuration to the HTTP client in the NAPI resolver is necessary to ensure consistent connection limits across all entry points.

Medium
Validate local address input

Return an error instead of silently ignoring invalid localAddress parsing.

pacquet/crates/napi/src/install.rs [559-570]

 fn build_tls_config(input: &NetworkConfigInput) -> napi::Result<TlsConfig> {
+    let local_address = match input.local_address.as_deref() {
+        None => None,
+        Some(value) => Some(
+            value
+                .parse::<IpAddr>()
+                .map_err(|_| unsupported_option_error("install", "networkConfig.localAddress"))?,
+        ),
+    };
     Ok(TlsConfig {
         ca: input.ca.as_ref().map(parse_string_list).transpose()?.unwrap_or_default(),
         cert: input.cert.as_ref().map(parse_single_string).transpose()?.flatten(),
         key: input.key.clone(),
         strict_ssl: input.strict_ssl,
-        local_address: input
-            .local_address
-            .as_deref()
-            .and_then(|value| value.parse::<IpAddr>().ok()),
+        local_address,
     })
 }
Suggestion importance[1-10]: 7

__

Why: Failing fast on an invalid local address parsing prevents silent misconfigurations in network settings.

Medium
Guard against empty version overrides

Filter out empty strings from the node_version override after normalization to
prevent passing invalid versions downstream.

pacquet/crates/package-manager/src/installability.rs [283-305]

     pub fn detect_with(engine_strict: bool, node_version: Option<String>) -> Self {
-        match node_version.map(|version| normalize_node_version(&version)) {
+        let normalized = node_version
+            .as_deref()
+            .map(normalize_node_version)
+            .filter(|version| !version.is_empty());
+
+        match normalized {
             Some(node_version) => Self {
                 node_version,
                 node_detected: true,
                 os: pacquet_graph_hasher::host_platform(),
                 cpu: pacquet_graph_hasher::host_arch(),
                 libc: pacquet_graph_hasher::host_libc(),
                 supported_architectures: None,
                 engine_strict,
             },
             None => Self { engine_strict, ..Self::detect() },
         }
     }
 }
 
 fn normalize_node_version(version: &str) -> String {
     let trimmed = version.trim();
-    trimmed.strip_prefix('v').unwrap_or(trimmed).to_string()
+    trimmed.strip_prefix('v').unwrap_or(trimmed).trim().to_string()
 }
Suggestion importance[1-10]: 6

__

Why: Filtering out empty strings from nodeVersion is a good defensive programming practice to avoid downstream semver parsing failures.

Low
Avoid masking real load failures

Restrict the ERR_DLOPEN_FAILED retry logic strictly to Linux platforms to avoid
masking real loading errors on other operating systems.

pacquet/npm/napi/index.js [56-64]

 function isRetryableLoadError(err, candidate) {
   if (!err) return false
   // The candidate isn't installed (platform package absent) — try the next one.
   if (isMissingCandidate(err, candidate)) return true
-  // The candidate exists but is the wrong libc / ABI: `require()` throws
-  // `ERR_DLOPEN_FAILED`. Fall through to the other Linux libc variant rather
-  // than aborting the whole load on a wrong first guess.
-  return err.code === 'ERR_DLOPEN_FAILED'
+  // Only treat dlopen failures as retryable when we may be falling through
+  // between glibc/musl variants on Linux; otherwise surface the real error.
+  return process.platform === 'linux' && err.code === 'ERR_DLOPEN_FAILED'
 }
Suggestion importance[1-10]: 5

__

Why: Failing fast on non-Linux platforms improves error transparency by immediately surfacing legitimate ERR_DLOPEN_FAILED loader errors instead of catching and wrapping them.

Low
Security
Prevent config-cache hash collisions

Change the config cache key from a u64 to a structured type with Eq and Hash to
prevent hash collisions.

pacquet/crates/napi/src/config.rs [127-234]

-/// Process-global intern table of leaked configs, keyed by the hash of
-/// `(dir, overlay, config source contents)`.
-fn config_cache() -> &'static DashMap<u64, &'static Config> {
-    static CACHE: OnceLock<DashMap<u64, &'static Config>> = OnceLock::new();
+#[derive(Clone, Debug, Hash, PartialEq, Eq)]
+struct CacheKey {
+    dir: PathBuf,
+    overlay_debug: String,
+    sources_hash: u64,
+}
+
+/// Process-global intern table of leaked configs, keyed by `(dir, overlay, config source contents)`.
+fn config_cache() -> &'static DashMap<CacheKey, &'static Config> {
+    static CACHE: OnceLock<DashMap<CacheKey, &'static Config>> = OnceLock::new();
     CACHE.get_or_init(DashMap::new)
 }
 
-fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
+fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> CacheKey {
     let mut hasher = DefaultHasher::new();
-    dir.hash(&mut hasher);
-    // The overlay's `Debug` string covers every field. This is only stable
-    // because the map-typed fields are `BTreeMap` (ordered) rather than
-    // `HashMap` (per-instance random iteration order) — otherwise logically
-    // identical overlays would hash differently, miss the cache, and leak a
-    // fresh `Config` on every call.
-    format!("{overlay:?}").hash(&mut hasher);
     hash_config_sources(dir, &mut hasher);
-    hasher.finish()
+    CacheKey {
+        dir: dir.to_path_buf(),
+        overlay_debug: format!("{overlay:?}"),
+        sources_hash: hasher.finish(),
+    }
 }
 
 /// Resolve `(dir, overlay)` into an interned `&'static Config`.
 pub fn resolve_config(
     dir: &Path,
     overlay: &ConfigOverlay,
 ) -> Result<&'static Config, LoadWorkspaceYamlError> {
     let key = cache_key(dir, overlay);
     if let Some(config) = config_cache().get(&key) {
         return Ok(*config);
     }
     let config = build_config(dir, overlay)?;
     let leaked: &'static Config = config.leak();
     config_cache().insert(key, leaked);
     Ok(leaked)
 }
Suggestion importance[1-10]: 8

__

Why: Replacing a bare u64 hash with a structured cache key prevents potential hash collisions that could lead to using incorrect configurations.

Medium
Suggestions up to commit 1b837f1
CategorySuggestion                                                                                                                                    Impact
Possible issue
Enforce per-origin socket cap

Enforce the max_sockets configuration on the HTTP client within the NAPI
resolver.

pacquet/crates/napi/src/resolve.rs [97-109]

     let http_client = Arc::new(
         ThrottledClient::for_installs(
             &config.proxy,
             &config.tls,
             &config.tls_by_uri,
             &NetworkSettings {
                 network_concurrency: config.network_concurrency,
                 fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
                 user_agent: config.user_agent.clone(),
             },
         )
-        .map_err(|error| to_napi_error(&error))?,
+        .map_err(|error| to_napi_error(&error))?
+        .with_max_sockets_per_host(config.max_sockets),
     );
Suggestion importance[1-10]: 8

__

Why: Ensures the max_sockets configuration is correctly applied to the NAPI HTTP client, maintaining parity with the CLI and preventing potential registry connection throttling.

Medium
Fail on invalid local address

Return an error when networkConfig.localAddress fails to parse instead of
silently falling back to default routing.

pacquet/crates/napi/src/install.rs [559-570]

 fn build_tls_config(input: &NetworkConfigInput) -> napi::Result<TlsConfig> {
+    let local_address = match input.local_address.as_deref() {
+        None => None,
+        Some(value) => Some(value.parse::<IpAddr>().map_err(|_| {
+            unsupported_option_error("install", "networkConfig.localAddress")
+        })?),
+    };
+
     Ok(TlsConfig {
         ca: input.ca.as_ref().map(parse_string_list).transpose()?.unwrap_or_default(),
         cert: input.cert.as_ref().map(parse_single_string).transpose()?.flatten(),
         key: input.key.clone(),
         strict_ssl: input.strict_ssl,
-        local_address: input
-            .local_address
-            .as_deref()
-            .and_then(|value| value.parse::<IpAddr>().ok()),
+        local_address,
     })
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly addresses a potential silent failure by properly surfacing invalid local_address inputs as errors instead of ignoring them.

Medium
Prevent empty version overrides

Update normalize_node_version to return an Option, filtering out empty or
whitespace-only version strings to prevent invalid overrides.

pacquet/crates/package-manager/src/installability.rs [283-305]

     pub fn detect_with(engine_strict: bool, node_version: Option<String>) -> Self {
-        match node_version.map(|version| normalize_node_version(&version)) {
+        match node_version.and_then(|version| normalize_node_version(&version)) {
             Some(node_version) => Self {
                 node_version,
                 node_detected: true,
                 os: pacquet_graph_hasher::host_platform(),
                 cpu: pacquet_graph_hasher::host_arch(),
                 libc: pacquet_graph_hasher::host_libc(),
                 supported_architectures: None,
                 engine_strict,
             },
             None => Self { engine_strict, ..Self::detect() },
         }
     }
 }
 
     /// Canonicalize a Node.js version string for the engine check: trim surrounding
     /// whitespace and drop a single leading `v` (`v22.11.0` → `22.11.0`) so a value
     /// copied from `process.version` / `node --version` parses as exact semver.
-    fn normalize_node_version(version: &str) -> String {
+    fn normalize_node_version(version: &str) -> Option<String> {
         let trimmed = version.trim();
-        trimmed.strip_prefix('v').unwrap_or(trimmed).to_string()
+        let normalized = trimmed.strip_prefix('v').unwrap_or(trimmed).trim();
+        if normalized.is_empty() { None } else { Some(normalized.to_string()) }
     }
Suggestion importance[1-10]: 6

__

Why: Safeguards against invalid node version overrides that resolve to empty strings, which could otherwise corrupt cache keys or engine compatibility checks.

Low
Security
Enforce hook return shape

Validate that the result from the readPackage JS callback is a JSON object,
returning an explicit error if it's not.

pacquet/crates/napi/src/hooks.rs [53-59]

     match self.read_package.call_async(pkg).await {
-        Ok(transformed) => Ok(Arc::new(transformed)),
+        Ok(transformed) => {
+            if !transformed.is_object() {
+                return Err(HookError::Execution {
+                    pnpmfile: "<napi readPackage>".to_string(),
+                    message: "readPackage must return a JSON object".to_string(),
+                });
+            }
+            Ok(Arc::new(transformed))
+        }
         Err(error) => Err(HookError::Execution {
             pnpmfile: "<napi readPackage>".to_string(),
             message: error.to_string(),
         }),
     }
Suggestion importance[1-10]: 7

__

Why: Adding a type check at the FFI boundary prevents unexpected values from causing panics downstream in the Rust engine, improving stability.

Medium
Prevent config cache collisions

Use a structured CacheKey struct instead of a single u64 hash to prevent
potential cache collisions.

pacquet/crates/napi/src/config.rs [129-145]

-fn config_cache() -> &'static DashMap<u64, &'static Config> {
-    static CACHE: OnceLock<DashMap<u64, &'static Config>> = OnceLock::new();
+#[derive(Clone, Debug, Eq, PartialEq, Hash)]
+struct CacheKey {
+    dir: PathBuf,
+    overlay_debug: String,
+    sources_hash: u64,
+}
+
+fn config_cache() -> &'static DashMap<CacheKey, &'static Config> {
+    static CACHE: OnceLock<DashMap<CacheKey, &'static Config>> = OnceLock::new();
     CACHE.get_or_init(DashMap::new)
 }
 
-fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
-    let mut hasher = DefaultHasher::new();
-    dir.hash(&mut hasher);
-    // The overlay's `Debug` string covers every field. This is only stable
-    // because the map-typed fields are `BTreeMap` (ordered) rather than
-    // `HashMap` (per-instance random iteration order) — otherwise logically
-    // identical overlays would hash differently, miss the cache, and leak a
-    // fresh `Config` on every call.
-    format!("{overlay:?}").hash(&mut hasher);
-    hash_config_sources(dir, &mut hasher);
-    hasher.finish()
+fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> CacheKey {
+    let overlay_debug = format!("{overlay:?}");
+    let sources_hash = {
+        let mut hasher = DefaultHasher::new();
+        hash_config_sources(dir, &mut hasher);
+        hasher.finish()
+    };
+    CacheKey { dir: dir.to_path_buf(), overlay_debug, sources_hash }
 }
Suggestion importance[1-10]: 4

__

Why: While partially improving safety against hash collisions for the directory and overlay inputs, the proposed code still relies on a u64 hash for sources_hash, offering only a marginal improvement to a highly unlikely edge case.

Low
Suggestions up to commit 5cbceee
CategorySuggestion                                                                                                                                    Impact
Possible issue
Honor per-origin socket cap

Apply the max_sockets configuration to ThrottledClient in the NAPI resolve
module to enforce per-origin socket caps.

pacquet/crates/napi/src/resolve.rs [97-109]

 let http_client = Arc::new(
     ThrottledClient::for_installs(
         &config.proxy,
         &config.tls,
         &config.tls_by_uri,
         &NetworkSettings {
             network_concurrency: config.network_concurrency,
             fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
             user_agent: config.user_agent.clone(),
         },
     )
-    .map_err(|error| to_napi_error(&error))?,
+    .map_err(|error| to_napi_error(&error))?
+    .with_max_sockets_per_host(config.max_sockets),
 );
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies that the newly added max_sockets configuration was omitted from the ThrottledClient instantiation in the NAPI resolve module, addressing a significant consistency bug.

High
Normalize paths before matching

Canonicalize project directories before comparing them to the install directory
to avoid mismatches due to formatting or symlinks.

pacquet/crates/napi/src/install.rs [237-252]

 let dir = PathBuf::from(&options.dir);
+let dir_key = std::fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
 
 // The root importer is the project at `dir`; any others are siblings. A
 // lone project takes the plain (non-workspace) install path; multiple
 // importers are handed to the engine via `workspace_projects_override`.
 let root_manifest_value = options
     .projects
     .iter()
-    .find(|project| std::path::Path::new(&project.root_dir) == dir)
+    .find(|project| {
+        let project_dir = PathBuf::from(&project.root_dir);
+        std::fs::canonicalize(&project_dir).unwrap_or(project_dir) == dir_key
+    })
     .map(|project| project.manifest.clone())
     .ok_or_else(|| {
         napi::Error::from_reason(format!(
             "install options had no project entry for the install dir {}",
             options.dir,
         ))
     })?;
Suggestion importance[1-10]: 4

__

Why: Canonicalizing paths improves matching robustness, though it introduces filesystem I/O and could yield unexpected UNC paths on Windows.

Low
Reject empty version overrides

Safely handle empty or degenerate nodeVersion overrides by returning an Option
to avoid downstream semver parsing issues.

pacquet/crates/package-manager/src/installability.rs [302-305]

-fn normalize_node_version(version: &str) -> String {
+fn normalize_node_version(version: &str) -> Option<String> {
     let trimmed = version.trim();
-    trimmed.strip_prefix('v').unwrap_or(trimmed).to_string()
+    if trimmed.is_empty() {
+        return None;
+    }
+    let stripped = trimmed.strip_prefix('v').unwrap_or(trimmed).trim();
+    if stripped.is_empty() {
+        return None;
+    }
+    Some(stripped.to_string())
 }
Suggestion importance[1-10]: 3

__

Why: While it points out a valid edge case, changing the return type to Option<String> independently without updating the caller breaks compilation.

Low
Fall back on invalid overrides

Update detect_with to handle an Option return type from normalize_node_version.

pacquet/crates/package-manager/src/installability.rs [283-296]

 pub fn detect_with(engine_strict: bool, node_version: Option<String>) -> Self {
-    match node_version.map(|version| normalize_node_version(&version)) {
+    match node_version.as_deref().and_then(normalize_node_version) {
         Some(node_version) => Self {
             node_version,
             node_detected: true,
             os: pacquet_graph_hasher::host_platform(),
             cpu: pacquet_graph_hasher::host_arch(),
             libc: pacquet_graph_hasher::host_libc(),
             supported_architectures: None,
             engine_strict,
         },
         None => Self { engine_strict, ..Self::detect() },
     }
 }
Suggestion importance[1-10]: 3

__

Why: Although the logic aligns with the previous suggestion, applying it independently breaks compilation because it expects normalize_node_version to return an Option instead of String.

Low
Security
Enforce absolute project directories

Check that project.root_dir is an absolute path to prevent unintended relative
path resolutions.

pacquet/crates/napi/src/install.rs [505-512]

 fn reject_non_object_manifests(projects: &[NodeApiProject]) -> napi::Result<()> {
     for project in projects {
+        let root_dir = std::path::Path::new(&project.root_dir);
+        if !root_dir.is_absolute() {
+            return Err(napi::Error::from_reason(format!(
+                "project.rootDir must be an absolute path: {}",
+                project.root_dir
+            )));
+        }
         if !project.manifest.is_object() {
             return Err(invalid_manifest_error(&project.root_dir));
         }
     }
     Ok(())
 }
Suggestion importance[1-10]: 5

__

Why: Validating that project directories are absolute paths is a good defense-in-depth measure for inputs crossing the FFI boundary.

Low
Prevent wrapper prototype pollution

Use Object.create(null) instead of an empty object literal ({}) for the wrapper
target to prevent potential prototype pollution.

pacquet/npm/napi/index.js [108-134]

 function wrapExports(binding) {
-  const wrapped = {}
+  const wrapped = Object.create(null)
   for (const key of Object.keys(binding)) {
     const value = binding[key]
     if (typeof value !== 'function') {
       wrapped[key] = value
       continue
     }
     wrapped[key] = function (...args) {
       try {
         const result = value.apply(this, args)
         if (result && typeof result.then === 'function') {
           return result.then(
             (resolved) => resolved,
             (err) => {
               throw decorateError(err)
             }
           )
         }
         return result
       } catch (err) {
         throw decorateError(err)
       }
     }
   }
   return wrapped
 }
Suggestion importance[1-10]: 3

__

Why: While prototype pollution from a native NAPI module export is highly unlikely, using Object.create(null) for the wrapper object is a valid defensive programming practice.

Low
Suggestions up to commit 77d7c19
CategorySuggestion                                                                                                                                    Impact
Possible issue
Honor per-origin socket cap

Apply the max_sockets limit to the ThrottledClient inside resolveDependency.

pacquet/crates/napi/src/resolve.rs [97-109]

 let http_client = Arc::new(
     ThrottledClient::for_installs(
         &config.proxy,
         &config.tls,
         &config.tls_by_uri,
         &NetworkSettings {
             network_concurrency: config.network_concurrency,
             fetch_timeout: std::time::Duration::from_millis(config.fetch_timeout),
             user_agent: config.user_agent.clone(),
         },
     )
-    .map_err(|error| to_napi_error(&error))?,
+    .map_err(|error| to_napi_error(&error))?
+    .with_max_sockets_per_host(config.max_sockets),
 );
Suggestion importance[1-10]: 8

__

Why: It fixes a clear omission in the PR where the newly introduced max_sockets configuration was applied in the CLI but missed in the NAPI resolveDependency client initialization.

Medium
Fail on invalid local address

Return an error when parsing networkConfig.localAddress fails instead of
silently ignoring the invalid value.

pacquet/crates/napi/src/install.rs [551-554]

-local_address: input
-    .local_address
-    .as_deref()
-    .and_then(|value| value.parse::<IpAddr>().ok()),
+local_address: match input.local_address.as_deref() {
+    None => None,
+    Some(value) => Some(value.parse::<IpAddr>().map_err(|_| {
+        napi::Error::from_reason(format!("invalid networkConfig.localAddress: {value}"))
+    })?),
+},
Suggestion importance[1-10]: 7

__

Why: Surfacing parsing errors for network configuration values instead of silently ignoring them prevents confusing networking behavior and aids in debugging.

Medium
Fix fallback on missing binaries

Relax the isMissingCandidate message check for package specifiers to ensure
fallback to local builds when internal .node files are missing.

pacquet/npm/napi/index.js [47-54]

 function isMissingCandidate(err, candidate) {
-  return (
-    err &&
-    err.code === 'MODULE_NOT_FOUND' &&
-    typeof err.message === 'string' &&
-    err.message.includes(`'${candidate}'`)
-  )
+  if (!err || err.code !== 'MODULE_NOT_FOUND') return false
+  if (typeof candidate !== 'string') return false
+  // For explicit paths, keep a strict match so we don't swallow unrelated missing modules.
+  if (candidate.includes('/') || candidate.includes('\\') || candidate.startsWith('.')) {
+    return typeof err.message === 'string' && err.message.includes(`'${candidate}'`)
+  }
+  // For package specifiers, Node may report the missing resolved file path instead.
+  return true
 }
Suggestion importance[1-10]: 5

__

Why: This handles an edge case where a corrupted optional package installation throws a MODULE_NOT_FOUND for the internal .node file, preventing the intended fallback sequence.

Low
Compare normalized project paths

Use fs::canonicalize to normalize paths before comparing options.dir with each
project.root_dir to prevent comparison failures.

pacquet/crates/napi/src/install.rs [241-251]

+let dir_path = PathBuf::from(&options.dir);
+let dir_norm = std::fs::canonicalize(&dir_path).unwrap_or_else(|_| dir_path.clone());
+
 let root_manifest_value = options
     .projects
     .iter()
-    .find(|project| std::path::Path::new(&project.root_dir) == dir)
+    .find(|project| {
+        let project_path = PathBuf::from(&project.root_dir);
+        let project_norm = std::fs::canonicalize(&project_path).unwrap_or(project_path);
+        project_norm == dir_norm
+    })
     .map(|project| project.manifest.clone())
     .ok_or_else(|| {
         napi::Error::from_reason(format!(
             "install options had no project entry for the install dir {}",
             options.dir,
         ))
     })?;
Suggestion importance[1-10]: 4

__

Why: While canonicalizing paths can prevent mismatch issues on case-insensitive systems, using fs::canonicalize introduces filesystem I/O which may be undesirable here, though the suggestion correctly identifies a potential comparison edge case.

Low
Reject empty version overrides

Return Option from normalize_node_version to safely handle empty string values
instead of creating invalid semver strings.

pacquet/crates/package-manager/src/installability.rs [302-305]

-fn normalize_node_version(version: &str) -> String {
+fn normalize_node_version(version: &str) -> Option<String> {
     let trimmed = version.trim();
-    trimmed.strip_prefix('v').unwrap_or(trimmed).to_string()
+    let stripped = trimmed.strip_prefix('v').unwrap_or(trimmed).trim();
+    if stripped.is_empty() {
+        None
+    } else {
+        Some(stripped.to_string())
+    }
 }
Suggestion importance[1-10]: 4

__

Why: It handles an edge case where an empty or whitespace-only node version could bypass checks, though such invalid inputs are usually prevented by config schema validation earlier.

Low
Recover from mutex poisoning

Recover from a poisoned mutex using into_inner() rather than panicking with
expect().

pacquet/crates/network/src/lib.rs [164-169]

 let semaphore = {
-    let mut map = self.per_origin.lock().expect("host-socket-limit mutex poisoned");
+    let mut map = match self.per_origin.lock() {
+        Ok(guard) => guard,
+        Err(poisoned) => poisoned.into_inner(),
+    };
     Arc::clone(
         map.entry(origin).or_insert_with(|| Arc::new(Semaphore::new(self.max.get()))),
     )
 };
Suggestion importance[1-10]: 3

__

Why: Handling mutex poisoning via into_inner() is a valid technique, but since the critical section here contains no panicking operations, the mutex is practically immune to poisoning, making the current expect idiomatic.

Low
Fall back on invalid overrides

Update detect_with to handle an Option returned by normalize_node_version and
fall back to auto-detection on invalid inputs.

pacquet/crates/package-manager/src/installability.rs [283-296]

 pub fn detect_with(engine_strict: bool, node_version: Option<String>) -> Self {
-    match node_version.map(|version| normalize_node_version(&version)) {
+    match node_version.as_deref().and_then(normalize_node_version) {
         Some(node_version) => Self {
             node_version,
             node_detected: true,
             os: pacquet_graph_hasher::host_platform(),
             cpu: pacquet_graph_hasher::host_arch(),
             libc: pacquet_graph_hasher::host_libc(),
             supported_architectures: None,
             engine_strict,
         },
         None => Self { engine_strict, ..Self::detect() },
     }
 }
Suggestion importance[1-10]: 3

__

Why: While it correctly integrates the changes proposed in the previous suggestion, applying it independently would result in a compilation error since normalize_node_version currently returns a String.

Low
Preserve promise rejection semantics

Use .catch() and Promise.reject() instead of .then() and throw for Promise
rejection handling.

pacquet/npm/napi/index.js [119-126]

 wrapped[key] = function (...args) {
   try {
     const result = value.apply(this, args)
     if (result && typeof result.then === 'function') {
-      return result.then(
-        (resolved) => resolved,
-        (err) => {
-          throw decorateError(err)
-        }
-      )
+      return result.catch((err) => Promise.reject(decorateError(err)))
     }
     return result
   } catch (err) {
     throw decorateError(err)
   }
 }
Suggestion importance[1-10]: 3

__

Why: Using .catch() and Promise.reject() is slightly cleaner, but the existing code's use of .then() and throw is semantically equivalent and safer for generic thenables.

Low
General
Harden error decoration against throwables

Ensure err is an Error instance before mutating it, and save the original
envelope string to a custom property.

pacquet/npm/napi/index.js [92-104]

 function decorateError(err) {
-  if (err && typeof err.message === 'string' && err.message.startsWith(ENVELOPE_PREFIX)) {
+  const e = err instanceof Error ? err : new Error(typeof err === 'string' ? err : 'Unknown error')
+  if (typeof e.message === 'string' && e.message.startsWith(ENVELOPE_PREFIX)) {
+    const raw = e.message
     try {
-      const parsed = JSON.parse(err.message.slice(ENVELOPE_PREFIX.length))
-      if (parsed.code != null) err.code = parsed.code
-      if (parsed.hint != null) err.hint = parsed.hint
-      if (typeof parsed.message === 'string') err.message = parsed.message
+      const parsed = JSON.parse(raw.slice(ENVELOPE_PREFIX.length))
+      if (parsed.code != null) e.code = parsed.code
+      if (parsed.hint != null) e.hint = parsed.hint
+      if (typeof parsed.message === 'string') e.message = parsed.message
     } catch {
-      // Leave the error untouched if the envelope doesn't parse.
+      // Leave message as-is.
+    } finally {
+      try {
+        Object.defineProperty(e, 'pnpmEnvelope', { value: raw, configurable: true })
+      } catch {}
     }
   }
-  return err
+  return e
 }
Suggestion importance[1-10]: 2

__

Why: While it handles highly unlikely edge cases (such as frozen errors), napi-rs natively returns standard, extensible Error objects, making this suggestion mostly unnecessary.

Low
✅ Suggestions up to commit 2dd141a
CategorySuggestion                                                                                                                                    Impact
High-level
✅ Fix thread explosion and logger concurrency hazards
Suggestion Impact:Implemented the safe-logging portion: pack now acquires a shared engine_call_lock to serialize calls that use the process-global log sink, and uses an EngineCallGuard to restore the previous sink on drop instead of manually setting/clearing it. The resolve_dependency thread/runtime explosion part was not addressed in this patch.

code diff:

@@ -15,7 +15,8 @@
 
 use crate::{
     error::to_napi_error,
-    reporter_bridge::{LogSink, NodeBridgeReporter, clear_global_log_sink, set_global_log_sink},
+    install::engine_call_lock,
+    reporter_bridge::{EngineCallGuard, LogSink, NodeBridgeReporter},
 };
 
 /// Inputs for [`pack`]. Mirrors [`PackOptions`] in `index.d.ts`.
@@ -47,10 +48,11 @@
 
 #[napi]
 pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
-    let had_sink = on_log.is_some();
-    if let Some(sink) = on_log {
-        set_global_log_sink(sink);
-    }
+    // Share the serialization lock with install/rebuild: they all drive the
+    // same process-global log sink, so overlapping calls would misroute events.
+    let _guard = engine_call_lock().lock().await;
+    // Restores the previous sink on drop, whatever path `pack` returns on.
+    let _sink_guard = EngineCallGuard::new(on_log);
 
     let pack_opts = pacquet_pack::PackOptions {
         dir: PathBuf::from(&options.dir),
@@ -82,10 +84,6 @@
     })
     .await;
 
-    if had_sink {
-        clear_global_log_sink();
-    }
-
     match result {

Addresses severe concurrency bugs in resolveDependency (which spawns unbounded
threads and runtimes per call) and pack (which mutates global loggers without
synchronization). Ensures bounded thread usage and safe logging across parallel
API invocations.

Examples:

pacquet/crates/napi/src/resolve.rs [64-78]
pub async fn resolve_dependency(
    wanted: WantedDependencyInput,
    options: ResolveDependencyOptions,
) -> napi::Result<ResolveDependencyResult> {
    let (tx, rx) = tokio::sync::oneshot::channel();
    std::thread::Builder::new()
        .name("pnpm-napi-resolve".to_string())
        .stack_size(32 * 1024 * 1024)
        .spawn(move || {
            let _ = tx.send(run_resolve_blocking(wanted, &options));

 ... (clipped 5 lines)
pacquet/crates/napi/src/pack.rs [48-55]
#[napi]
pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
    let had_sink = on_log.is_some();
    if let Some(sink) = on_log {
        set_global_log_sink(sink);
    }

    let pack_opts = pacquet_pack::PackOptions {

Solution Walkthrough:

Before:

// In resolve.rs
pub async fn resolve_dependency(...) -> napi::Result<ResolveDependencyResult> {
    // No concurrency limit: spawns a dedicated OS thread per call
    std::thread::Builder::new().spawn(move || {
        // Spawns a multi-threaded Tokio runtime per call
        let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
        // ...
    });
}

// In pack.rs
pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
    // Mutates process-global state without locking `install_lock()`
    if let Some(sink) = on_log {
        set_global_log_sink(sink);
    }
    // ...
    if had_sink { clear_global_log_sink(); }
}

After:

// Use a globally shared Tokio runtime or bounded semaphore for resolution
static RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = ...;

// In resolve.rs
pub async fn resolve_dependency(...) -> napi::Result<ResolveDependencyResult> {
    // Await completion without spawning unbounded OS threads and Tokio runtimes
    RUNTIME.spawn_blocking(move || {
        run_resolve_blocking(...)
    }).await.unwrap()
}

// In pack.rs
pub async fn pack(options: PackOptions, on_log: Option<LogSink>) -> napi::Result<PackResult> {
    // Acquire the global lock to safely mutate process-global log sink
    let _guard = install_lock().lock().await;
    
    if let Some(sink) = on_log {
        set_global_log_sink(sink);
    }
    // ...
    if had_sink { clear_global_log_sink(); }
}
Suggestion importance[1-10]: 10

__

Why: The suggestion addresses critical architectural flaws in the FFI bindings that would reliably cause severe performance degradation (OOM or OS thread exhaustion via resolveDependency) and race conditions dropping or misrouting events via the global logger in pack.

High
Possible issue
✅ Use BTreeMap to fix memory leaks
Suggestion Impact:The commit replaces ConfigOverlay's HashMap fields (allow_builds and auth_header_by_uri) with BTreeMap, adds rationale about stable Debug-based cache keys, removes HashMap import, and updates config building to collect allow_builds from the BTreeMap into the target type.

code diff:

 use std::{
-    collections::{BTreeMap, BTreeSet, HashMap, hash_map::DefaultHasher},
+    collections::{BTreeMap, BTreeSet, hash_map::DefaultHasher},
     fs,
     hash::{Hash, Hasher},
     path::{Path, PathBuf},
@@ -78,8 +87,9 @@
     pub strict_dep_builds: Option<bool>,
     /// Per-package build-script allow-list: `name -> allowed`. A package must
     /// be `true` here (or covered by `dangerously_allow_all_builds`) for its
-    /// lifecycle scripts to run.
-    pub allow_builds: Option<HashMap<String, bool>>,
+    /// lifecycle scripts to run. `BTreeMap` (not `HashMap`) so the overlay's
+    /// `Debug` output — which feeds the config intern cache key — is stable.
+    pub allow_builds: Option<BTreeMap<String, bool>>,
     /// Allow every dependency's build scripts to run.
     pub dangerously_allow_all_builds: Option<bool>,
     /// When `true`, skip all dependency and project lifecycle scripts.
@@ -100,8 +110,9 @@
     /// registry. When present, replaces the `.npmrc`-derived `auth_headers` —
     /// the host (which owns the raw `.npmrc`/config credentials) resolves the
     /// `Bearer ...` / `Basic ...` values and passes them in, so the binding never
-    /// reparses npmrc auth.
-    pub auth_header_by_uri: Option<HashMap<String, String>>,
+    /// reparses npmrc auth. `BTreeMap` (not `HashMap`) so the overlay's `Debug`
+    /// output — which feeds the config intern cache key — is stable.
+    pub auth_header_by_uri: Option<BTreeMap<String, String>>,
 }
 
 /// Host-supplied `peerDependencyRules`. Mirrors pnpm's shape and pacquet's
@@ -123,6 +134,11 @@
 fn cache_key(dir: &Path, overlay: &ConfigOverlay) -> u64 {
     let mut hasher = DefaultHasher::new();
     dir.hash(&mut hasher);
+    // The overlay's `Debug` string covers every field. This is only stable
+    // because the map-typed fields are `BTreeMap` (ordered) rather than
+    // `HashMap` (per...

- `invalid_manifest_error` now emits pnpm's canonical
  `ERR_PNPM_INVALID_PACKAGE_JSON` instead of a bespoke `ERR_PNPM_NAPI_*` code,
  so consumers translate an invalid project manifest like any other pnpm error.
- The `@pnpm/napi` loader now tries both Linux libc variants (ordered by
  detection) instead of hard-defaulting to glibc when `process.report` is
  unavailable, so a musl host whose libc cannot be probed still resolves the
  `-musl` addon rather than failing on the glibc one.
@zkochan

zkochan commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Both valid — fixed in 1b837f143a:

invalid_manifest_error used a bespoke code — switched to pnpm's canonical ERR_PNPM_INVALID_PACKAGE_JSON (the code the TS engine throws for "failed to read or parse project manifest"), so consumers translate a non-object project manifest like any other pnpm error instead of a ERR_PNPM_NAPI_* special case.

musl detection fell back to glibc — the loader now tries both Linux libc variants (ordered by detection, glibc-first only as a tiebreak) instead of hard-defaulting to glibc when process.report is unavailable, mirroring the @pnpm/exe.* wrapper. A musl host whose libc can't be probed now falls through to the -musl addon rather than failing on the glibc one.


Written by an agent (Claude Code, claude-fable-5), on behalf of @zkochan.

Comment thread pacquet/npm/napi/index.js Resolved
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1b837f1

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 1b837f1

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

…erride strict

Now that the loader tries both Linux libc variants, treat an `ERR_DLOPEN_FAILED`
from a wrong-ABI candidate as retryable so it falls through to the other libc
variant instead of aborting on a wrong first guess. An explicit
`PNPM_NAPI_BINARY` stays strict: a non-.node value is rejected, and a `.node`
that exists but fails to load surfaces that error rather than silently falling
back to a platform package.
Copilot AI review requested due to automatic review settings July 7, 2026 08:20
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

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 7, 2026

Copy link
Copy Markdown
Member Author

Good catch — fixed in 6f84945679. tryLoad now treats ERR_DLOPEN_FAILED (a candidate that exists but is the wrong libc/ABI) as retryable, so a wrong first guess falls through to the other Linux libc variant instead of aborting. The explicit PNPM_NAPI_BINARY override is kept strict: it's pulled out of the retry loop, so a .node that exists but fails to load surfaces the real error rather than silently falling back (a non-.node value is still rejected up front, and a missing path still falls back to a platform package).


Written by an agent (Claude Code, claude-fable-5), on behalf of @zkochan.

resolveDependency built a fresh multi-thread Tokio runtime per call, spawning a
worker-thread pool for a single packument fetch — concurrent resolves in a
long-lived host could multiply threads. It already runs on a dedicated worker
thread, so a current-thread runtime does the one fetch with no extra threads.
The install path keeps its multi-thread runtime, which it needs to fetch
packages in parallel.
@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 6f84945

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@zkochan

zkochan commented Jul 7, 2026

Copy link
Copy Markdown
Member Author

Fixed for resolveDependency in 034d839635: it now builds a current-thread Tokio runtime instead of a multi-thread one. A single resolve is one packument fetch with no task parallelism to exploit, and it already runs on a dedicated worker thread, so this spawns no extra worker-thread pool — removing the per-call thread multiplication under concurrent resolves.

On the install.rs reference: leaving that one as a multi-thread runtime intentionally. The install path fetches packages in parallel (that's where pnpm's throughput comes from), so it genuinely needs the worker pool. It's also serialized behind engine_call_lock, so at most one such runtime exists at a time — no concurrent-call amplification there.


Written by an agent (Claude Code, claude-fable-5), on behalf of @zkochan.

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 034d839

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

Grey Divider

New Review Started

This review has been superseded by a new analysis

Grey Divider

Qodo Logo

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 034d839

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.

3 participants