diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc..8ce26746b 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -363,7 +363,7 @@ The route is taken only when **all** of these hold; otherwise the run takes the **vlt hosted-mode contract**: `scan` / `get --mode hosted` rewrite, in `vlt-lock.json`, every default-registry node of a granted `name@version` (the `''` / `npm` segment or a URL segment equal to the lock's scalar `registry`, both DepID grammars, every peer and modifier variant): slot [2] becomes the granted sha512 and slot [3] the hosted URL (appended to a 3-tuple); the DepID, flags and trailing slots, the line ending and every other byte stay. `options` is never edited and `vlt.json` is only read. A lock with another `lockfileVersion` (decided on the raw JSON token), a BOM, a non-object body or a `nodes` section outside vlt's one-node-per-line layout refuses the whole lock (`redirect_vlt_lock_unsupported`). **Confirmation**: vlt drives when its install state (`node_modules/.vlt-lock.json` or `node_modules/.vlt/`) is present or no other npm-family lock is; then only `vlt-lock.json` confirms a uuid. Otherwise every lock is rewritten, `redirect_vlt_sibling_lockfiles` warns, and the other locks' rules confirm, including a dep `vlt-lock.json` merely does not wire (`redirect_vlt_entry_not_found`, `redirect_vlt_entry_vendored`, or `redirect_vlt_custom_registry_skipped` alone). Whichever lock drives, a dep the vlt rewriter refuses (`redirect_vlt_missing_sha512`, `redirect_vlt_unsupported_lock_key`) is never confirmed by any lock, although a sibling lock may already carry its rewritten URL. **Artifacts**: the scan never downloads the hosted artifacts; the patch server sends them unencoded (`Cache-Control: no-transform`), and vlt verifies slot [2] against the bytes it receives at install time. **Heal**: an installed copy is stale when vlt's hidden lock (`node_modules/.vlt-lock.json`) does not record its DepID at the integrity the lock pins, and cannot be checked without a readable hidden lock; stale installed copies of Socket-owned nodes are removed so the next `vlt install` extracts the patched bytes, and `rollback` / `remove` do the same for the registry bytes (`--no-vlt-install-cleanup` keeps them; optional dependencies' copies are always kept); `redirect_vlt_reinstall_required` says what happened and what to run. The same-run `--vex` never attests a vlt package whose installed copy is stale or unchecked, whose lock a vlt release may ignore (`redirect_vlt_lockfile_version_missing`, `redirect_vlt_old_lockfile_ignored`, `redirect_vlt_scalar_registry_ignored`), or which also resolves from a non-default registry (`redirect_vlt_custom_registry_skipped`). `vlt.json` or vlt install state without `vlt-lock.json` warns `redirect_vlt_no_lockfile` instead of `redirect_npm_no_lockfile`. `rollback` / `remove` restore each hosted node's slots [2] and [3] from the version document of the registry the node resolves against (slot [3] is its `dist.tarball`, as vlt writes it; `upstream_registry_fallback` when that registry can't be read), following the lock's own slot-[3] convention (see "Hosted unwind coverage"). Tested releases: `docs/testing/vlt-compatibility.md`. -**Takeover reconciliation (every hosted ecosystem, v5.0)**: plain `vendor` with at least one hosted pin in scope is not a per-purl takeover: it EJECTS exactly the lockfile's hosted pins as one planned transition (see "Vendor command contract") and ignores `.socket/manifest.json` even when it exists — a manifest-only patch is not vendored, and a manifest naming a different patch for a hosted purl does not displace the hosted one (vendoring the manifest's patches takes a full `scan --mode vendored`, whose edits then land in the lockfiles). The eject runs the same upstream restore and the same backend previews and refusals described below, but reports them as an eject (`eject_planned` / `eject_refused` / `eject_rolled_back`) rather than through the per-purl takeover advisories. Vendoring over a hosted pin with `scan --mode vendored` / `get --mode vendored` (and the legacy manifest-driven `vendor` path, reached only when no hosted pin is in scope) first RESTORES that purl's lock entries to their default upstream registry entry — the same restore `rollback` runs (core `patch::redirect::upstream::restore_upstream`; see "Hosted unwind coverage"), over the hosted pins lockfile discovery finds (v5 keeps no hosted ledger) — and then vendors, so the vendor ledger records the PRISTINE registry entry as its wiring `original` and `vendor --revert` lands back on upstream registry state, never on hosted. The run that takes over records a `vendor_takeover_reverted_redirect` advisory event (`skipped` action beside the purl's genuine outcome; detail ` was hosted; restored its upstream registry entry () before vendoring (mode takeover)`; the human path prints `Warning: …`), plus any advisory the restore raised (`npm_allow_remote_left`, …). **A takeover the vendored backend does not carry through keeps the hosted pin (#853, #944)**: the wet run holds the restore in its group commit, and when the backend then refuses the purl — whatever the code: a pnpm `catalog:` dependency (`vendor_lock_entry_unsupported`), a CRLF `pnpm-lock.yaml` (`vendor_lockfile_crlf_unsupported`), a conflicting `pnpm-workspace.yaml` override — a range, another version or a `>` selector (`vendor_override_conflict`), a uv inline `[tool.uv] sources` table, a prebuilt download that fails, … — or its apply fails with nothing recorded, the restore is rolled back before anything reaches disk: the purl is reported `failed ` with the backend's own code and detail, neither `vendor_takeover_reverted_redirect` nor the restore's advisories are recorded for it, and the hosted wiring stays byte-for-byte (exit 1 / `partialFailure`), so the package stays hosted-patched instead of being un-hosted and then refused. `vendor --dry-run` previews that same `failed ` by running the backend's dry run over the restored project staged in memory (nothing written). A restore that writes a file outside the group commit's captured set (`.socket/gradle/hosted-index.tsv`) is not rolled back. The `scan` / `get --mode vendored --dry-run` preview, which stages no restore (it never touches the registry), predicts the pnpm (lockfileVersion 9) part of this (#853): a hosted pin the pnpm vendored backend refuses on lock or manifest text (a `catalog:` dependency, a CRLF `pnpm-lock.yaml` / `pnpm-workspace.yaml`, a conflicting override, …) is listed `would_refuse` with the wet run's `errorCode` and the backend's own `error` detail, evaluated on the still-hosted project (the pnpm restore only rewrites the entry's `resolution:`, which none of those gates reads); a hosted pin of any other lock flavor or ecosystem — a legacy pnpm 7/8 lock (`lockfileVersion` 5.4 / 6.0) included, whose CRLF, override-conflict and entry refusals are not lock-text gated — still previews `would_vendor` even when the wet takeover refuses it (the wet refusal keeps the hosted pin), except for the gem preflight below. **Gem preflight before the takeover**: `scan` / `get --mode vendored` ask the gem vendored backend's own refusals BEFORE the upstream restore — the manifest gate (`gemfile_not_loaded`: a `gems.rb` twin or a `BUNDLE_GEMFILE`-configured manifest) and the Gemfile declaration gate evaluated on the Gemfile and Gemfile.lock text the restore would leave (`gemfile_declaration_not_editable`: a declaration inside a `group` / `platforms` / conditional block, a parenthesized or duplicate declaration, …) — so a hosted gem vendored mode cannot wire is reported `failed ` with the hosted `Gemfile` / `Gemfile.lock` byte-untouched (exit 1 / `partialFailure`), and their `--dry-run` preview reports that gem as `would_refuse` with the same `errorCode` (exit 0, like the Bun / vlt `would_refuse` rows), never `would_vendor`. Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. `--dry-run` resolves the same restore without writing (registry lookups included): a pin that would restore reports `vendor_would_revert_redirect`, and one that would be refused surfaces in the preview with the wet run's `redirect_revert_failed` code and detail (for bun, whose hosted rewrite replaces the entry's `name@version` spec, the preview first runs the Bun vendored preflight described below and then stops at the advisory instead of reading the still-hosted lock — a lock the vendored backend would refuse is previewed as the wet run's `failed `, never as `vendor_would_revert_redirect`). A purl whose upstream entry cannot be restored — `--offline`, a registry that does not answer, a lock the restore refuses (see "Hosted unwind coverage"; a hosted binary `bun.lockb` pin IS restored for the takeover — its npm registry record is rebuilt natively — while `rollback` / `remove` refuse it) — fails `redirect_revert_failed` with the detail `cannot vendor over the live hosted pin: cannot restore to its upstream registry entry: ; restore it from version control instead (`git checkout -- `)` (for `bun.lock` / `bun.lockb` the detail also adds `, then run \`bun install --force\` (a plain \`bun install\` keeps the patched copy)`) (exit 1 / `partialFailure`, nothing vendored for it, the hosted wiring left in place). The cargo backend's `hosted_redirect_live` refusal backstops a crate whose hosted residue is still in place when it is reached; its detail names `socket-patch rollback` and `git checkout -- Cargo.toml Cargo.lock`. **Bun vendored preflight before the takeover**: `vendor` — like `scan` / `get --mode vendored`, whose pre-download preflight runs earlier — checks `bun.lock` / `bun.lockb` with the shared Bun vendored preflight BEFORE the upstream restore, so a hosted purl on a lock the vendored backend refuses (a pre-version-2 `workspace:` lock → `vendor_bun_workspace_unsupported`; a malformed or unsupported binary lock → `vendor_bun_lockb_invalid`; an unsupported text-lock version → its code) is reported `failed ` with the hosted wiring and active Bun lock byte-untouched (exit 1 / `partialFailure`): the package stays hosted-patched instead of being un-hosted and then refused. `vendor --dry-run` previews that same `failed` code (exit-code parity with the wet run, nothing written) instead of promising `vendor_would_revert_redirect`. Pinned by `tests/in_process_vendor_bun_takeover.rs` and, against real Bun, `tests/mode_migration_bun.rs`. The npm package-lock backend's lock gate gets the same placement: a hosted pin in a project whose `npm-shrinkwrap.json` / `package-lock.json` is not a v2/v3 lock (npm 6's lockfileVersion 1) is refused `failed vendor_lockfile_version_unsupported` BEFORE the restore, in `vendor`, `scan --mode vendored` and `get --mode vendored` alike, so the package stays hosted-patched; the vendored dry-run preview lists every npm purl of such a project as `would_refuse` with that code. Pinned by `tests/in_process_vendor_npm_v1_takeover.rs`. Hosted → vendored and vendored → hosted (`redirect_takeover_reverted_vendored` in `warnings[]`) both work in place on the locks the target mode accepts. **Removed in v5.0**: the run-level `vendor_supersedes_redirect` warning and its reconcile of the redirect ledger (a live lock that already proved vendored won over a stale hosted ledger record) — once the lock routes a package to `.socket/vendor/`, no hosted state is left to go stale. Which way the live lock points is decided by the same lockfile discovery rules `vex` gates attestations on (see "Manifest-less VEX (lockfile discovery)"), for `redirect_supersedes_vendored` and `hosted_wiring_retained` alike. +**Takeover reconciliation (every hosted ecosystem, v5.0)**: plain `vendor` with at least one hosted pin in scope is not a per-purl takeover: it EJECTS exactly the lockfile's hosted pins as one planned transition (see "Vendor command contract") and ignores `.socket/manifest.json` even when it exists — a manifest-only patch is not vendored, and a manifest naming a different patch for a hosted purl does not displace the hosted one (vendoring the manifest's patches takes a full `scan --mode vendored`, whose edits then land in the lockfiles). The eject runs the same upstream restore and the same backend previews and refusals described below, but reports them as an eject (`eject_planned` / `eject_refused` / `eject_rolled_back`) rather than through the per-purl takeover advisories. Vendoring over a hosted pin with `scan --mode vendored` / `get --mode vendored` (and the legacy manifest-driven `vendor` path, reached only when no hosted pin is in scope) first RESTORES that purl's lock entries to their default upstream registry entry — the same restore `rollback` runs (core `patch::redirect::upstream::restore_upstream`; see "Hosted unwind coverage"), over the hosted pins lockfile discovery finds (v5 keeps no hosted ledger) — and then vendors, so the vendor ledger records the PRISTINE registry entry as its wiring `original` and `vendor --revert` lands back on upstream registry state, never on hosted. The run that takes over records a `vendor_takeover_reverted_redirect` advisory event (`skipped` action beside the purl's genuine outcome; detail ` was hosted; restored its upstream registry entry () before vendoring (mode takeover)`; the human path prints `Warning: …`), plus any advisory the restore raised (`npm_allow_remote_left`, …). **A takeover the vendored backend does not carry through keeps the hosted pin (#853, #944)**: the wet run holds the restore in its group commit, and when the backend then refuses the purl — whatever the code: a pnpm `catalog:` dependency (`vendor_lock_entry_unsupported`), a CRLF `pnpm-lock.yaml` (`vendor_lockfile_crlf_unsupported`), a conflicting `pnpm-workspace.yaml` override — a range, another version or a `>` selector (`vendor_override_conflict`), a uv inline `[tool.uv] sources` table, a prebuilt download that fails, … — or its apply fails with nothing recorded, the restore is rolled back before anything reaches disk: the purl is reported `failed ` with the backend's own code and detail, neither `vendor_takeover_reverted_redirect` nor the restore's advisories are recorded for it, and the hosted wiring stays byte-for-byte (exit 1 / `partialFailure`), so the package stays hosted-patched instead of being un-hosted and then refused. `vendor --dry-run` previews that same `failed ` by running the backend's dry run over the restored project staged in memory (nothing written). A restore that writes a file outside the group commit's captured set (`.socket/gradle/hosted-index.tsv`) is not rolled back. The `scan` / `get --mode vendored --dry-run` preview, which stages no restore (it never touches the registry), predicts the pnpm (lockfileVersion 9) part of this (#853): a hosted pin the pnpm vendored backend refuses on lock or manifest text (a `catalog:` dependency, a CRLF `pnpm-lock.yaml` / `pnpm-workspace.yaml`, a conflicting override, …) is listed `would_refuse` with the wet run's `errorCode` and the backend's own `error` detail, evaluated on the still-hosted project (the pnpm restore only rewrites the entry's `resolution:`, which none of those gates reads); a hosted pin of any other lock flavor or ecosystem — a legacy pnpm 7/8 lock (`lockfileVersion` 5.4 / 6.0) included, whose CRLF, override-conflict and entry refusals are not lock-text gated — still previews `would_vendor` even when the wet takeover refuses it (the wet refusal keeps the hosted pin), except for the gem preflight below. **Gem preflight before the takeover**: `scan` / `get --mode vendored` ask the gem vendored backend's own refusals BEFORE the upstream restore — the manifest gate (`gemfile_not_loaded`: a `gems.rb` twin or a `BUNDLE_GEMFILE`-configured manifest) and the Gemfile declaration gate evaluated on the Gemfile and Gemfile.lock text the restore would leave (`gemfile_declaration_not_editable`: a declaration inside a `group` / `platforms` / conditional block, a parenthesized or duplicate declaration, …) — so a hosted gem vendored mode cannot wire is reported `failed ` with the hosted `Gemfile` / `Gemfile.lock` byte-untouched (exit 1 / `partialFailure`; the one exception is a gem refused for its declaration that is installed and already holds the selected patch through that pin, which is the benign skip `vendor_gem_patched_in_other_mode`, see its row), and their `--dry-run` preview reports that gem as `would_refuse` with the same `errorCode` (exit 0, like the Bun / vlt `would_refuse` rows), never `would_vendor`. Pinned against real Bundler by `tests/e2e_redirect_gem_build.rs`. `--dry-run` resolves the same restore without writing (registry lookups included): a pin that would restore reports `vendor_would_revert_redirect`, and one that would be refused surfaces in the preview with the wet run's `redirect_revert_failed` code and detail (for bun, whose hosted rewrite replaces the entry's `name@version` spec, the preview first runs the Bun vendored preflight described below and then stops at the advisory instead of reading the still-hosted lock — a lock the vendored backend would refuse is previewed as the wet run's `failed `, never as `vendor_would_revert_redirect`). A purl whose upstream entry cannot be restored — `--offline`, a registry that does not answer, a lock the restore refuses (see "Hosted unwind coverage"; a hosted binary `bun.lockb` pin IS restored for the takeover — its npm registry record is rebuilt natively — while `rollback` / `remove` refuse it) — fails `redirect_revert_failed` with the detail `cannot vendor over the live hosted pin: cannot restore to its upstream registry entry: ; restore it from version control instead (`git checkout -- `)` (for `bun.lock` / `bun.lockb` the detail also adds `, then run \`bun install --force\` (a plain \`bun install\` keeps the patched copy)`) (exit 1 / `partialFailure`, nothing vendored for it, the hosted wiring left in place). The cargo backend's `hosted_redirect_live` refusal backstops a crate whose hosted residue is still in place when it is reached; its detail names `socket-patch rollback` and `git checkout -- Cargo.toml Cargo.lock`. **Bun vendored preflight before the takeover**: `vendor` — like `scan` / `get --mode vendored`, whose pre-download preflight runs earlier — checks `bun.lock` / `bun.lockb` with the shared Bun vendored preflight BEFORE the upstream restore, so a hosted purl on a lock the vendored backend refuses (a pre-version-2 `workspace:` lock → `vendor_bun_workspace_unsupported`; a malformed or unsupported binary lock → `vendor_bun_lockb_invalid`; an unsupported text-lock version → its code) is reported `failed ` with the hosted wiring and active Bun lock byte-untouched (exit 1 / `partialFailure`): the package stays hosted-patched instead of being un-hosted and then refused. `vendor --dry-run` previews that same `failed` code (exit-code parity with the wet run, nothing written) instead of promising `vendor_would_revert_redirect`. Pinned by `tests/in_process_vendor_bun_takeover.rs` and, against real Bun, `tests/mode_migration_bun.rs`. The npm package-lock backend's lock gate gets the same placement: a hosted pin in a project whose `npm-shrinkwrap.json` / `package-lock.json` is not a v2/v3 lock (npm 6's lockfileVersion 1) is refused `failed vendor_lockfile_version_unsupported` BEFORE the restore, in `vendor`, `scan --mode vendored` and `get --mode vendored` alike, so the package stays hosted-patched; the vendored dry-run preview lists every npm purl of such a project as `would_refuse` with that code. Pinned by `tests/in_process_vendor_npm_v1_takeover.rs`. Hosted → vendored and vendored → hosted (`redirect_takeover_reverted_vendored` in `warnings[]`) both work in place on the locks the target mode accepts. **Removed in v5.0**: the run-level `vendor_supersedes_redirect` warning and its reconcile of the redirect ledger (a live lock that already proved vendored won over a stale hosted ledger record) — once the lock routes a package to `.socket/vendor/`, no hosted state is left to go stale. Which way the live lock points is decided by the same lockfile discovery rules `vex` gates attestations on (see "Manifest-less VEX (lockfile discovery)"), for `redirect_supersedes_vendored` and `hosted_wiring_retained` alike. **Withdrawn pins (`scan --mode hosted`, additive/MINOR)**: before the rewrite, a hosted scan checks every patch uuid the lockfiles pin, for a package this run covered, against the reference endpoint. A pin the server reports `withdrawn` (unpublished) or `not_found` (no such patch) no longer installs (the patch server answers 410), so it is restored to its default upstream registry entry: the same restore `rollback` runs (see "Hosted unwind coverage"), under the apply lock, `--dry-run` previewing it without writing. If the package has a replacement patch on offer, the rewrite that follows pins the replacement. Each restored pin is one `rolledBack` event (`verified` on a dry run) with `uuid`, `errorCode: "patch_withdrawn"` and `details.mode: "hosted"`; the restore's advisories (`redirect_bun_reinstall_required`, `redirect_pypi_reinstall_required`, `redirect_vlt_reinstall_required`) join `warnings[]`. Only those two statuses unpin: a pin merely absent from the search results (a failed batch, the free-only proxy fallback, a lapsed paid entitlement), or one reported `forbidden`, `pending_build` or `build_failed`, is kept. If the reference lookup fails, every pin is kept with a `redirect_withdrawn_check_failed` warning; a pin the restore refuses, or whose restored files cannot be written (or the apply lock being held), is kept with a `redirect_withdrawn_restore_failed` warning naming the remedy, and is never reported as `rolledBack`: the write is all or nothing (see "Hosted unwind coverage"), so a failed one leaves every pin of that restore in place. Neither changes the status or the exit code. The one exception is a write that failed part-way and could not put a file back: the lockfiles are then neither pinned nor restored, so the run stops before the rewrite with the top-level error `lockfile_write_failed` (exit 1), whose message names each such file and the state it is left in. A run whose every search batch failed exits before the check. @@ -2518,7 +2518,7 @@ command's integration tests check its output. | `vendor_unsupported_ecosystem` | `skipped` | vendor: no vendor backend for this purl's ecosystem (jsr). | | `already_vendored` | `skipped` | vendor: artifact + wiring already in sync for this patch uuid. | | `vendor_gem_version_not_locked` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (gem): no section of the project's `Gemfile.lock` resolves the gem at this version (typically a gem Ruby ships in the gem home, or another project's copy in a shared gem home, which the crawl of that gem home returns). Decided before any download: the patch is not fetched, the Gemfile and lock stay byte-identical, and nothing is written. Human: `[skip] (vendor_gem_version_not_locked): …` in the download phase of `scan` / `get` (both identifier paths) and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_gem_version_not_locked`. | -| `vendor_gem_patched_in_other_mode` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (gem): the gem builds a native extension, which vendored mode refuses (`native_extensions_unsupported`), and it already holds the selected patch in a mode that refusal names. Either `Gemfile.lock` still pins that patch hosted, or the manifest records it for agent mode; and every installed copy of the gem that the crawl finds holds the patch (a hosted copy by its files; a copy patched in place as `vex` and `apply --check` judge it, its rebuilt extension included). The reason names the mode and the patch uuid. Nothing is written: the hosted pin, the manifest record and the installed copy stay as they were. Human: `Skipping : builds a native extension, which vendored mode cannot vendor; it stays patched in hosted mode (patch )`. The closing totals of `scan` count the gem as patched. A native gem that holds another patch or none, or with an installed copy that does not hold the patch (a hosted pin whose gem was not reinstalled, an unpatched copy in the tree of another Ruby), is still refused with `native_extensions_unsupported` (exit 1). A dry run of `scan` / `get` previews neither the refusal nor this skip. | +| `vendor_gem_patched_in_other_mode` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (gem): vendored mode refuses the gem and sends it to another mode, either for its native extension (`native_extensions_unsupported`) or for its Gemfile declaration (`gemfile_declaration_not_editable`: a `gem` line inside a `group` block, say), and the gem already holds the selected patch in hosted or agent mode. Either `Gemfile.lock` still pins that patch hosted, or the manifest records it for agent mode; and every installed copy of the gem that the crawl finds holds the patch (a hosted copy by its files; a copy patched in place as `vex` and `apply --check` judge it, its rebuilt extension included). The reason says why vendored mode leaves the gem alone and names the mode and the patch uuid. Nothing is written: the hosted pin, the manifest record and the installed copy stay as they were. Human: `Skipping : builds a native extension, which vendored mode cannot vendor; it stays patched in hosted mode (patch )`, or `Skipping : vendored mode cannot edit the Gemfile declaration of ; it stays patched in hosted mode (patch )`. The closing totals of `scan` count the gem as patched. A gem that holds another patch or none, or with an installed copy that does not hold the patch (a hosted pin whose gem was not reinstalled, an unpatched copy in the tree of another Ruby), is still refused with the code of its refusal (exit 1). For a hosted gem refused for its declaration, the patch view is fetched to judge the installed copies when the lock pins the selected patch and the gem is installed; otherwise (a checkout with no copy of the gem installed included) the gem is refused before any fetch, as before. `get ` judges with the view it already holds and raises the refusal before its engine, in the pre-record shape (`status: "error"`), as before. A dry run of `scan` / `get` reads no installed copy and previews neither the native-extension refusal nor this skip: it still lists a hosted gem declared inside a block as `would_refuse`, and one patched in agent mode as `would_vendor`. | | `vendor_maven_version_not_selected` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): no module of the build resolves the artifact at the patch's base version; the reason names the versions Maven selects instead (a nearer declaration, the project's own declaration or management, an ``, a version range), or says that no module resolves the artifact. Decided before any download: the patch is not fetched and no file is written, except that a pin an earlier run wrote for that version is taken out of the poms (the reason says so), since it would keep forcing a version the build no longer selects. Human: `[skip] (vendor_maven_version_not_selected): …` in the download phase of `scan` / `get` and in their dry run, `Skipping : …` in `vendor`. The vendored twin of `redirect_maven_version_not_selected`. See [Maven version selection](#maven-version-selection-hosted-and-vendored-maven). | | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 4d5926dcf..2e9afa77c 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -1178,7 +1178,9 @@ pub(crate) fn selection_pairs(selected: &[PatchSearchResult]) -> Vec<(&str, &str /// Every refusal the vendored download phase raises before it fetches a /// view: [`vendor_refusals`] over the selection, plus a hosted gem the /// takeover would refuse (#775, [`gem_takeover_refusals_for`]), refused -/// here with the takeover's code instead of after its fetch. The download +/// here with the takeover's code instead of after its fetch (unless its +/// pin is the selected patch and the gem is installed: the vendor loop then +/// judges, with the view, whether every copy already holds it). The download /// phase only runs online (`--offline` refuses `get` and `scan` before it), /// so the gem's dry-run restore may resolve the registry entry. `prior` is /// scan's npm crawl, when the caller has it (the installed-copy lookup @@ -1191,6 +1193,53 @@ pub(crate) async fn vendored_download_refusals( ledger: LedgerLoad<'_>, prior: Option<&crate::ecosystem_dispatch::NpmCrawlSnapshot>, ) -> VendorRefusals { + vendored_download_refusals_and_deferred(params, selected, ledger, prior) + .await + .0 +} + +/// The gem takeover refusals [`vendored_download_refusals`] leaves to the +/// patch view, keyed by the selected purl: the refusal, and the hosted +/// pin that already holds the selected patch. +pub(crate) type ViewJudgedRefusals = HashMap< + String, + ( + VendorRefusal, + socket_patch_core::patch::redirect::upstream::HostedPin, + ), +>; + +/// A refusal [`vendored_download_refusals`] left to the patch view, +/// settled with `patch`, that view: the skip of a gem that already holds +/// the patch through `pin` in every installed copy, or the refusal +/// itself. +pub(crate) async fn settle_view_judged_refusal( + common: &GlobalArgs, + patch: &PatchResponse, + refusal: &VendorRefusal, + pin: &socket_patch_core::patch::redirect::upstream::HostedPin, +) -> VendorRefusal { + let (_, record) = socket_patch_core::manifest::records::record_from_patch_response(patch); + let (code, detail) = crate::commands::vendor::settle_gem_refusal( + common, + &patch.purl, + &record, + Some(pin), + refusal.code, + refusal.detail.clone(), + ) + .await; + VendorRefusal { code, detail } +} + +/// [`vendored_download_refusals`], with the refusals it left to the patch +/// view: `get ` holds that view already and settles them itself. +pub(crate) async fn vendored_download_refusals_and_deferred( + params: &DownloadParams, + selected: &[PatchSearchResult], + ledger: LedgerLoad<'_>, + prior: Option<&crate::ecosystem_dispatch::NpmCrawlSnapshot>, +) -> (VendorRefusals, ViewJudgedRefusals) { let cwd = params.cwd.as_path(); let origins = crate::commands::hosted_unwind::patch_server_origins_of( params.patch_server_url.as_deref(), @@ -1230,12 +1279,46 @@ pub(crate) async fn vendored_download_refusals( origins, ) .await; + // A gem refused for its declaration whose pin is the selected patch + // and that is installed may hold that patch in every installed copy, + // which only the patch view can tell: its view is fetched, and the + // vendor loop raises this refusal or the skip of a gem already + // patched in hosted mode (#2395). Any other gem is refused here, + // before any fetch. + let pinned_at_selection: Vec = gem + .iter() + .filter(|(purl, (code, _))| { + socket_patch_core::vendor::gem::refusal_names_another_mode(code) + && selected.iter().any(|sr| { + sr.purl == **purl + && pins + .iter() + .any(|pin| pin.uuid == sr.uuid && PurlKey::same(&pin.purl, purl)) + }) + }) + .map(|(purl, _)| purl.clone()) + .collect(); + let installed_at_selection = match pinned_at_selection.is_empty() { + true => std::collections::HashSet::new(), + false => installed(pinned_at_selection).await, + }; + let mut judged_by_view = ViewJudgedRefusals::new(); for (purl, (code, detail)) in gem { - refusals - .entry(purl) - .or_insert(VendorRefusal { code, detail }); + let refusal = VendorRefusal { code, detail }; + let pin = installed_at_selection + .contains(&purl) + .then(|| pins.iter().find(|pin| PurlKey::same(&pin.purl, &purl))) + .flatten(); + match pin { + Some(pin) => { + judged_by_view.insert(purl, (refusal, pin.clone())); + } + None => { + refusals.entry(purl).or_insert(refusal); + } + } } - refusals + (refusals, judged_by_view) } /// The project's hosted pins: the purls whose vendored run is a hosted → diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index c418c32af..2a4f0d34f 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -32,8 +32,9 @@ use crate::commands::agent_download::{ decide_patch_action, download_patch_records_preflighted, download_patch_records_reusing, filter_to_installed_releases, max_vuln_severity, nested_apply_args, next_steps as agent_next_steps, patch_event_metadata, record_apply_outcome, recorded_purls, - report_lock_failure, roll_back_replaced_patches, run_nested_apply, run_outcome, tag_mode, - unwind_new_blobs, vendored_download_refusals, warn_if_manifest_gitignored, + report_lock_failure, roll_back_replaced_patches, run_nested_apply, run_outcome, + settle_view_judged_refusal, tag_mode, unwind_new_blobs, + vendored_download_refusals_and_deferred, warn_if_manifest_gitignored, warn_on_vendored_uuid_drift, write_all_patch_blobs, DetachedDownload, PatchAction, ALREADY_IN_MANIFEST, BLOB_WRITE_FAILED, RELEASE_NARROWING, REPLACED_PATCH_NOT_RESTORED, REPLACED_ROLLED_BACK_UNRECORDED, @@ -2603,14 +2604,31 @@ async fn run_get_vendored( // Human: `Error (): ` on stderr — an error, so it is // exempt from `--silent` like every other `Error (…)` line here. let vendor_state = load_state(&args.common.project_root()).await; - let refusals = Box::pin(vendored_download_refusals( + let (refusals, judged_by_view) = Box::pin(vendored_download_refusals_and_deferred( ¶ms, selected, vendor_state.as_ref().map(|s| &s.entries), None, )) .await; - if let Some(VendorRefusal { code, detail }) = refusals.get(&patch.purl) { + // A hosted gem refused for its declaration, pinned at this patch + // and installed: the view in hand tells whether every installed + // copy holds the patch (the skip of a gem already patched in + // hosted mode) or the refusal stands, here as well (#2395). + let settled = match (refusals.get(&patch.purl), judged_by_view.get(&patch.purl)) { + (Some(refusal), _) => Some(refusal.clone()), + (None, Some((refusal, pin))) => Some( + Box::pin(settle_view_judged_refusal( + &args.common, + patch, + refusal, + pin, + )) + .await, + ), + (None, None) => None, + }; + if let Some(VendorRefusal { code, detail }) = settled.as_ref() { // An expected skip (a gem version this project doesn't lock) // is not an error: the same `skipped` event and `[skip]` line // as the search path and `scan`, exit 0, nothing written. diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1c2af7c4f..c3f94e503 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -208,8 +208,9 @@ async fn keep_older_vendored_patch( } /// The mode in which the gem `candidate` already holds `record`, the -/// patch the run selected for it, for a gem the vendored backend refused -/// for its native extension: `hosted` when the lock still pins that patch +/// patch the run selected for it, for a gem vendored mode refused for +/// its native extension or its declaration: `hosted` when the lock still +/// pins that patch /// (`live_pin`, the candidate's hosted pin unless this run restored its /// upstream entry), `agent` when the manifest records it. Either way /// every installed copy of the gem must hold the patch, as `vex` and @@ -270,11 +271,12 @@ async fn gem_patch_held_in( } } -/// A backend refusal as the run reports it: a gem refused for its native -/// extension that already holds the selected patch in hosted or agent -/// mode is the skip [`vendor::gem::GEM_PATCHED_IN_OTHER_MODE`] (#2269); -/// every other refusal is itself. -async fn settle_gem_refusal( +/// A gem refusal as the run reports it: a gem refused for its native +/// extension or for its Gemfile declaration, which already holds the +/// selected patch in hosted or agent mode, is the skip +/// [`vendor::gem::GEM_PATCHED_IN_OTHER_MODE`] (#2269, #2395); every other +/// refusal is itself. +pub(crate) async fn settle_gem_refusal( common: &GlobalArgs, candidate: &str, record: &PatchRecord, @@ -282,7 +284,7 @@ async fn settle_gem_refusal( code: &'static str, detail: String, ) -> (&'static str, String) { - if code != vendor::gem::NATIVE_EXTENSIONS_UNSUPPORTED { + if !vendor::gem::refusal_names_another_mode(code) { return (code, detail); } match gem_patch_held_in(common, candidate, record, live_pin).await { @@ -292,7 +294,7 @@ async fn settle_gem_refusal( .map_or(&*purl, |(name, _)| name); ( vendor::gem::GEM_PATCHED_IN_OTHER_MODE, - vendor::gem::patched_in_other_mode_detail(name, mode, &record.uuid), + vendor::gem::patched_in_other_mode_detail(code, name, mode, &record.uuid), ) } None => (code, detail), @@ -4061,6 +4063,21 @@ pub(crate) async fn vendor_records_reusing( let refusal = gem_takeover_refusal(&common.cwd, candidate, pin, &restore_opts).await; if let Some((code, detail)) = refusal { + // The pin is still live here: a gem that holds + // the selected patch through it is a skip (#2395). + let (code, detail) = + settle_gem_refusal(common, candidate, record, live_pin, code, detail) + .await; + if refusal_is_benign(code) { + if !common.silent && !common.json { + eprintln!("Skipping {}: {detail}", normalize_purl(candidate)); + } + env.record( + PatchEvent::new(PatchAction::Skipped, candidate.clone()) + .with_reason(code, detail), + ); + continue; + } has_errors = true; env.record( PatchEvent::new(PatchAction::Failed, candidate.clone()) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs index 93f020012..9fe825e59 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_build.rs @@ -3519,8 +3519,10 @@ async fn gem_hosted_group_block_pin_survives_a_refused_vendored_takeover() { vendor_takeover_keeps_the_hosted_group_pin(&fx, command, selector, dry_run); // The refusal is known before the download phase: a wet scan // never fetches the patch view (nor its files) of a gem it - // cannot vendor. `get ` fetches the view once to resolve - // its identifier, and that is all it fetches. + // cannot vendor and that is not installed here (an installed + // copy is judged by the view: it may hold the pinned patch + // already). `get ` fetches the view once to resolve its + // identifier, and that is all it fetches. let fetched = view_requests(&fx).await - views; let allowed = usize::from(command == "get"); assert!( diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index e251ca7e9..cee0574f1 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -6189,3 +6189,264 @@ async fn vendored_scan_still_refuses_a_native_gem_that_is_not_patched() { assert_eq!(installed_lib(&gem_dir), left, "{case}"); } } + +/// Declare the fixture gem inside a `group` block, where vendored mode +/// cannot edit its declaration and hosted mode can. +fn declare_in_group(proj: &Path) { + std::fs::write( + proj.join("Gemfile"), + format!( + "source \"https://rubygems.org\"\n\ngroup :development do\n \ + gem \"{DEP}\", \"{DEP_VERSION}\"\nend\n" + ), + ) + .unwrap(); +} + +/// The refusal of a gem declared inside a block. +const DECLARATION_NOT_EDITABLE: &str = "gemfile_declaration_not_editable"; + +/// #2395: vendored mode refuses a gem whose `gem` line sits in a `group` +/// block and names hosted mode as the way to patch it. Once the gem holds +/// the same patch in hosted mode, a later `scan --mode vendored` (or `get +/// --mode vendored`) skips it and says where its patch is: exit 0, the +/// gem counted as patched, the pair and the install untouched. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_scan_skips_a_grouped_gem_that_holds_the_patch_in_hosted_mode() { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = vendorable_project(&server, &proj).await; + declare_in_group(&proj); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let uri = server.uri(); + + // The refusal that names hosted mode. + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + assert!( + gem_events(&env).contains(&format!("failed/{DECLARATION_NOT_EDITABLE}")), + "premise: {env}\nstderr:\n{stderr}" + ); + assert_ne!(code, 0, "premise: {env}"); + assert!(env.to_string().contains("--mode hosted"), "premise: {env}"); + + // The remedy: the gem is patched in hosted mode and installed. + let (code, _, stderr) = common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "premise"); + let pair_before = read_pair(&proj); + assert!(pair_before.0.contains("group :development do"), "premise"); + let home_before = snapshot(&home); + + for _ in 0..2 { + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + events.contains(&format!("skipped/{PATCHED_IN_OTHER_MODE}")) + && !events.iter().any(|e| e.starts_with("failed/")), + "{events:?}\n{env}\nstderr:\n{stderr}" + ); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "success", "{env}"); + let skip = env["events"] + .as_array() + .into_iter() + .flatten() + .find(|e| e["errorCode"] == PATCHED_IN_OTHER_MODE) + .expect("the skip"); + let why = skip["reason"].as_str().unwrap_or_default(); + assert!( + why.contains("patched in hosted mode") + && why.contains("Gemfile") + && why.contains(UUID) + && !why.contains("native extension"), + "{skip}" + ); + assert_eq!(read_pair(&proj), pair_before, "the hosted pin stays"); + assert!(!proj.join(".socket").join("vendor").exists()); + assert!(snapshot(&home) == home_before, "the install is untouched"); + } + + // A human run: no error, and nothing of the gem is left to patch. + let (code, stdout, stderr) = unwind_run(&proj, &uri, &["scan", "--mode", "vendored", "--yes"]); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let shown = format!("{stdout}\n{stderr}"); + assert!(!shown.contains("rror"), "{shown}"); + assert!(shown.contains("Nothing left to patch"), "{shown}"); + assert!(shown.contains("patched in hosted mode"), "{shown}"); + assert_eq!(read_pair(&proj), pair_before, "the hosted pin stays"); + + // `get --mode vendored` reads the same answer. + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["get", UUID, "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + assert!( + gem_events(&env).contains(&format!("skipped/{PATCHED_IN_OTHER_MODE}")), + "{env}\nstderr:\n{stderr}" + ); + assert_eq!(code, 0, "{env}\nstderr:\n{stderr}"); + assert_eq!(read_pair(&proj), pair_before, "the hosted pin stays"); + assert!(!proj.join(".socket").join("vendor").exists()); + assert!(snapshot(&home) == home_before, "the install is untouched"); +} + +/// #2395, the agent half: a gem in a `group` block that agent mode +/// patched in place (the manifest records the patch and the installed +/// copy holds it) is a skip of the vendored scan as well, and its +/// manifest record stays. +#[tokio::test(flavor = "multi_thread")] +async fn vendored_scan_skips_a_grouped_gem_that_holds_the_patch_in_agent_mode() { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = vendorable_project(&server, &proj).await; + declare_in_group(&proj); + let gem_dir = agent_patched_install(&proj, &home); + let uri = server.uri(); + let pair_before = read_pair(&proj); + let manifest_path = proj.join(".socket").join("manifest.json"); + let manifest_before = std::fs::read_to_string(&manifest_path).unwrap(); + + for run in ["first run", "second run"] { + let args = ["scan", "--mode", "vendored", "--yes", "--json"]; + let (code, stdout, stderr) = unwind_run(&proj, &uri, &args); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + events.contains(&format!("skipped/{PATCHED_IN_OTHER_MODE}")) + && !events.iter().any(|e| e.starts_with("failed/")), + "{run}: {events:?}\n{env}\nstderr:\n{stderr}" + ); + assert_eq!(code, 0, "{run}: {env}\nstderr:\n{stderr}"); + assert!( + env.to_string().contains("patched in agent mode"), + "{run}: {env}" + ); + assert_eq!(read_pair(&proj), pair_before, "{run}"); + assert!(!proj.join(".socket").join("vendor").exists(), "{run}"); + assert_eq!( + std::fs::read_to_string(&manifest_path).unwrap(), + manifest_before, + "{run}: the agent record stays" + ); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{run}"); + } +} + +/// The other side of #2395: a gem in a `group` block that does not hold +/// the selected patch everywhere is still refused for its declaration, +/// and the run still fails: an upstream install with no pin and no +/// record; a hosted pin whose installed copy is still the upstream gem; a +/// hosted pin with an unpatched copy in the tree of another Ruby; a +/// hosted pin of an earlier patch than the one the scan selects; a hosted +/// pin on a checkout with no gem installed (refused without fetching the +/// patch view). +#[tokio::test(flavor = "multi_thread")] +async fn vendored_scan_still_refuses_a_grouped_gem_that_is_not_patched() { + for case in [ + "no pin", + "hosted pin over an upstream install", + "hosted pin, one of two copies unpatched", + "hosted pin of an earlier patch", + "hosted pin, gem not installed", + ] { + let server = MockServer::start().await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + let home = vendorable_project(&server, &proj).await; + declare_in_group(&proj); + let uri = server.uri(); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let mut left = UPSTREAM_LIB; + if case != "no pin" { + let (code, _, stderr) = + common::run_with_env(&proj, &scan_args(&proj, &uri, &["--json"]), &[]); + assert_eq!(code, 0, "{case}: hosted scan:\n{stderr}"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}: premise"); + left = PATCHED_LIB; + } + match case { + "hosted pin over an upstream install" => { + // The gem as it is before the pinned build is installed. + std::fs::write(gem_dir.join("lib").join("stale_probe_gem.rb"), UPSTREAM_LIB) + .unwrap(); + left = UPSTREAM_LIB; + } + "hosted pin, one of two copies unpatched" => { + install_real_gem(&home.with_file_name("3.2.0"), UPSTREAM_LIB); + } + "hosted pin of an earlier patch" => { + server.reset().await; + mount_newer_patch(&server).await; + } + "hosted pin, gem not installed" => std::fs::remove_dir_all(&home).unwrap(), + _ => {} + } + let pair_before = read_pair(&proj); + let views_before = view_requests(&server).await; + + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["scan", "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + let events = gem_events(&env); + assert!( + events + .iter() + .any(|e| *e == format!("failed/{DECLARATION_NOT_EDITABLE}")), + "{case}: {events:?}\n{env}\nstderr:\n{stderr}" + ); + assert!( + !env.to_string().contains(PATCHED_IN_OTHER_MODE), + "{case}: {env}" + ); + assert_ne!(code, 0, "{case}: {env}"); + assert_eq!(read_pair(&proj), pair_before, "{case}"); + let scan_views = view_requests(&server).await - views_before; + // `get ` raises the refusal before its engine, in the one + // shape it has for a refused patch, whether or not a copy is + // installed. + if case.starts_with("hosted pin") && case != "hosted pin of an earlier patch" { + let (code, stdout, stderr) = unwind_run( + &proj, + &uri, + &["get", UUID, "--mode", "vendored", "--yes", "--json"], + ); + let env = common::parse_json_envelope(&stdout); + assert_eq!(code, 1, "{case}: get: {env}\nstderr:\n{stderr}"); + assert_eq!(env["status"], "error", "{case}: get: {env}"); + assert_eq!( + env["error"]["code"], DECLARATION_NOT_EDITABLE, + "{case}: get: {env}" + ); + assert_eq!(read_pair(&proj), pair_before, "{case}: get"); + } + if case == "hosted pin, gem not installed" { + // Nothing to judge by the patch view: refused before any fetch. + assert_eq!(scan_views, 0, "{case}"); + } else { + assert_eq!(installed_lib(&gem_dir), left, "{case}"); + } + assert!( + !proj.join(".socket").join("vendor").exists(), + "{case}: nothing is vendored" + ); + } +} diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 339dbf08f..09ef3a2ed 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -325,22 +325,41 @@ fn version_not_locked_detail(name: &str, version: &str) -> String { /// extension ([`native_extensions_remedy`]). pub const NATIVE_EXTENSIONS_UNSUPPORTED: &str = "native_extensions_unsupported"; -/// Skip code of a gem refused with [`NATIVE_EXTENSIONS_UNSUPPORTED`] that -/// already holds the selected patch in a mode the refusal names: the -/// lock pins that patch hosted, or the manifest records it for agent -/// mode, and every installed copy holds it. An expected skip, not a -/// failure: the remedy the refusal -/// offers is already in place, and a run that asked for it again would -/// fail every time (#2269). +/// Refusal code of a gem whose Gemfile declaration vendored mode cannot +/// edit: a `gem` line inside a block, or a direct dependency declared +/// where no `gem` line names it. The refusal names the mode that can +/// patch the gem as it is declared. +pub const GEMFILE_DECLARATION_NOT_EDITABLE: &str = "gemfile_declaration_not_editable"; + +/// Whether `code` is a refusal that sends the user to another mode for +/// the gem ([`NATIVE_EXTENSIONS_UNSUPPORTED`], +/// [`GEMFILE_DECLARATION_NOT_EDITABLE`]), and so becomes the skip +/// [`GEM_PATCHED_IN_OTHER_MODE`] once the gem holds the selected patch +/// there. +pub fn refusal_names_another_mode(code: &str) -> bool { + code == NATIVE_EXTENSIONS_UNSUPPORTED || code == GEMFILE_DECLARATION_NOT_EDITABLE +} + +/// Skip code of a gem refused with a code that +/// [`refusal_names_another_mode`] and that already holds the selected +/// patch in hosted or agent mode: the lock pins that patch hosted, or the +/// manifest records it for agent mode, and every installed copy holds it. +/// An expected skip, not a failure: the remedy the refusal offers is +/// already in place, and a run that asked for it again would fail every +/// time (#2269, #2395). pub const GEM_PATCHED_IN_OTHER_MODE: &str = "vendor_gem_patched_in_other_mode"; /// The detail of a [`GEM_PATCHED_IN_OTHER_MODE`] skip of the gem `name`, +/// refused with `refusal` (a code that [`refusal_names_another_mode`]), /// which holds the patch `uuid` in `mode` (`hosted` or `agent`). -pub fn patched_in_other_mode_detail(name: &str, mode: &str, uuid: &str) -> String { - format!( - "{name} builds a native extension, which vendored mode cannot vendor; it stays patched \ - in {mode} mode (patch {uuid})" - ) +pub fn patched_in_other_mode_detail(refusal: &str, name: &str, mode: &str, uuid: &str) -> String { + let why = match refusal { + GEMFILE_DECLARATION_NOT_EDITABLE => { + format!("vendored mode cannot edit the Gemfile declaration of {name}") + } + _ => format!("{name} builds a native extension, which vendored mode cannot vendor"), + }; + format!("{why}; it stays patched in {mode} mode (patch {uuid})") } /// The refusals the backend raises for the gem purls of `purls` from @@ -467,7 +486,7 @@ pub async fn gem_vendor_target_preflight( .map_or(Ok(()), Err) }) .err() - .map(|detail| ("gemfile_declaration_not_editable", detail)) + .map(|detail| (GEMFILE_DECLARATION_NOT_EDITABLE, detail)) } async fn gem_prelude( @@ -990,12 +1009,7 @@ fn gem_edits( ) }) { Ok(p) => p, - Err(detail) => { - return Err(Box::new(refused( - "gemfile_declaration_not_editable", - detail, - ))) - } + Err(detail) => return Err(Box::new(refused(GEMFILE_DECLARATION_NOT_EDITABLE, detail))), }; // ── gemspec development dependency (#985) ──────────────────────────── let project_root = prelude.gemfile_path.parent().unwrap_or(Path::new(".")); @@ -1006,10 +1020,7 @@ fn gem_edits( name, version, ) { - return Err(Box::new(refused( - "gemfile_declaration_not_editable", - detail, - ))); + return Err(Box::new(refused(GEMFILE_DECLARATION_NOT_EDITABLE, detail))); } // ── Gemfile.lock edit (pure text surgery, computed before any write) ── // A lock-shape failure therefore costs no download / copy / patch and no diff --git a/crates/socket-patch-core/src/vendor/refusals.rs b/crates/socket-patch-core/src/vendor/refusals.rs index 4e244305c..d45480bd0 100644 --- a/crates/socket-patch-core/src/vendor/refusals.rs +++ b/crates/socket-patch-core/src/vendor/refusals.rs @@ -467,12 +467,35 @@ mod tests { assert!(!refusal_is_benign( crate::vendor::gem::NATIVE_EXTENSIONS_UNSUPPORTED )); - let detail = crate::vendor::gem::patched_in_other_mode_detail("json", "hosted", "u-1"); + let detail = crate::vendor::gem::patched_in_other_mode_detail( + crate::vendor::gem::NATIVE_EXTENSIONS_UNSUPPORTED, + "json", + "hosted", + "u-1", + ); assert!( detail.contains("json builds a native extension") && detail.contains("patched in hosted mode (patch u-1)"), "{detail}" ); + // #2395: the same skip for a gem refused for its declaration. + assert!(crate::vendor::gem::refusal_names_another_mode( + crate::vendor::gem::GEMFILE_DECLARATION_NOT_EDITABLE + )); + assert!(!crate::vendor::gem::refusal_names_another_mode( + crate::vendor::gem::GEM_VERSION_NOT_LOCKED + )); + let detail = crate::vendor::gem::patched_in_other_mode_detail( + crate::vendor::gem::GEMFILE_DECLARATION_NOT_EDITABLE, + "rake", + "hosted", + "u-1", + ); + assert!( + detail.contains("cannot edit the Gemfile declaration of rake") + && detail.contains("patched in hosted mode (patch u-1)"), + "{detail}" + ); } use crate::vendor::load_state; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 843aa0cc3..4cf8bb649 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5111,17 +5111,23 @@ other ecosystems (npm, PyPI, Cargo, Go, Composer, Gradle) to hosted mode. Once a patches of two modes, a `scan` with no `--mode` stops and asks which mode to use, so pass `--mode` on later runs. -A later `scan --mode vendored` doesn't refuse a gem with a native extension again once it holds +A later `scan --mode vendored` doesn't refuse a gem again for its native extension or for its +declaration (`native_extensions_unsupported`, `gemfile_declaration_not_editable`) once it holds the selected patch in hosted or agent mode: `Gemfile.lock` pins the patch hosted, or the manifest records it for agent mode, and every installed copy of the gem holds it. It skips the gem with -`vendor_gem_patched_in_other_mode`, a line that names the mode (`Skipping pkg:gem/json@2.9.1: json -builds a native extension, which vendored mode cannot vendor; it stays patched in hosted mode -(patch )`), counts it as patched in the closing totals, and exits 0 when nothing else -failed. The hosted pin or the agent-mode patch stays exactly as it was. The gem is refused again, -and the run exits 1, when it holds no patch, when it holds a different one from the patch the scan -selects (after the patch service published a newer one, say), or when an installed copy doesn't -hold the patch yet (a hosted pin whose gem was not reinstalled). Patch the gem again in the mode -it is in, as the refusal says, and the next vendored scan skips it. +`vendor_gem_patched_in_other_mode`, a line that says why vendored mode leaves the gem alone and +names the mode (`Skipping pkg:gem/json@2.9.1: json builds a native extension, which vendored mode +cannot vendor; it stays patched in hosted mode (patch )`, or `Skipping pkg:gem/rake@13.4.2: +vendored mode cannot edit the Gemfile declaration of rake; it stays patched in hosted mode (patch +)`), counts it as patched in the closing totals, and exits 0 when nothing else failed. The +hosted pin or the agent-mode patch stays exactly as it was. The gem is refused again, and the run +exits 1, when it holds no patch, when it holds a different one from the patch the scan selects +(after the patch service published a newer one, say), or when an installed copy doesn't hold the +patch yet (a hosted pin whose gem was not reinstalled). Patch the gem again in the mode it is in, +as the refusal says, and the next vendored scan skips it. The gem must be installed for the skip: +on a checkout with no copy of it (before `bundle install`), the scan refuses it as before. A +`--dry-run` doesn't read the installed copies: it still lists a hosted gem declared inside a block +as `would-refuse`. ## Ruby gems: native extensions