From d9858ef94ab4918e8ff04c7411e0869170c62957 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:22:55 +0000 Subject: [PATCH 1/5] Start fix for gem unwind shared-home remedy Refs #2086 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSmGF7hUwWjuXgRvcM From 911a108641f27a273bcf68b6c37c3f62bc424a0a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:27:25 +0000 Subject: [PATCH 2/5] Test the gem unwind warning for a shared home A hosted rollback or remove that leaves a patched copy in a shared gem home tells the user to re-run with --gem-refresh-shared. The first run removed the wiring, so the re-run exits 1. These tests fail until the unwind names a remedy that works. Refs #2086 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSmGF7hUwWjuXgRvcM --- .../src/commands/gem_refresh.rs | 75 ++++++++++ .../tests/e2e_redirect_gem_stale_install.rs | 135 ++++++++++++++++++ 2 files changed, 210 insertions(+) diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 5f54b1fe9..28298a8ae 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1418,6 +1418,81 @@ mod tests { assert!(fixed < 480, "the whole warning stays short: {fixed}"); } + /// #2086: an unwind leaves nothing for a second run to unwind, so the + /// warning about a shared gem home names no re-run with + /// `--gem-refresh-shared`. It names what works once the wiring is + /// gone: the project-local path, or the files to remove before + /// `bundle install` fetches the upstream gem into the shared home. + #[tokio::test] + async fn an_unwind_names_no_rerun_for_a_shared_home() { + let tmp = tempfile::tempdir().unwrap(); + let (proj, home) = (tmp.path().join("proj"), tmp.path().join("gemhome")); + std::fs::create_dir_all(&proj).unwrap(); + let stale = vec![ + installed("rack", &home, false), + installed("rexml", &home, false), + ]; + let policy = policy(&proj, true, false, false); + let pass = attempt( + &stale, + unobtainable, + &Source::DiskOnly, + &policy, + Direction::Upstream, + ) + .await; + assert!(pass.refreshed.is_empty(), "a shared home is never tried"); + let out = report(Direction::Upstream, &stale, &pass, &policy); + let file = |dir: &str, name: &str| home.join(dir).join(name).display().to_string(); + + assert_eq!(out.warnings.len(), 2, "one --json warning per gem"); + for ((code, detail), name) in out.warnings.iter().zip(["rack", "rexml"]) { + assert_eq!(*code, "upstream_gem_stale_install"); + assert!( + !detail.contains("--gem-refresh-shared") + && !detail.to_lowercase().contains("re-run"), + "a second unwind has nothing to unwind: {detail}" + ); + for needle in [ + "the shared gem home still holds its patched install", + LOCAL_PATH_REMEDY, + &file("specifications", &format!("{name}-1.0.0.gemspec")), + &file("cache", &format!("{name}-1.0.0.gem")), + "and run `bundle install`", + ] { + assert!(detail.contains(needle), "missing {needle:?}: {detail}"); + } + } + + let summary = out.summary.expect("a summary"); + assert_eq!( + summary.headline, + "2 gems still hold the patched build on disk after the switch back to the upstream \ + registry" + ); + assert_eq!( + summary.bullets, + vec![ + format!( + "Shared gem home {} (left alone, other projects may load it): rack 1.0.0, \ + rexml 1.0.0.", + home.display() + ), + format!( + "`bundle install` reuses an installed gem instead of fetching the upstream \ + one. To install them for this project only, run `bundle config set --local \ + path vendor/bundle && bundle install`. To replace the shared copies, run \ + `rm -f {} {} {} {} && bundle install`; another project that loads them \ + needs a `bundle install` too.", + file("specifications", "rack-1.0.0.gemspec"), + file("cache", "rack-1.0.0.gem"), + file("specifications", "rexml-1.0.0.gemspec"), + file("cache", "rexml-1.0.0.gem"), + ), + ] + ); + } + /// A copy that could not be checked against the upstream gem (the /// registry that would say is refused) is reported with the reason and /// the files to remove, apart from the copies known to be stale: it is 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 65ff715e9..8929cb049 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 @@ -2562,6 +2562,141 @@ async fn refresh_after_rollback_restores_the_upstream_gem() { ); } +/// #2086: `rollback` / `remove` of a hosted gem whose patched copy sits in +/// a shared gem home leave that copy alone and warn about it. The warning +/// names no re-run with `--gem-refresh-shared`: the first run removed the +/// wiring, so a second one has nothing to unwind. It names the +/// project-local path, and the files whose removal makes `bundle install` +/// fetch the upstream gem into the shared home. The generic reinstall note +/// does not claim that the next install replaces the copy. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { + const UNWINDS: [&[&str]; 2] = [&["rollback", "--yes"], &["remove", PURL, "--yes"]]; + for (unwind, json) in UNWINDS + .into_iter() + .flat_map(|unwind| [(unwind, false), (unwind, true)]) + { + let case = format!("{unwind:?} json={json}"); + let server = MockServer::start().await; + let (patched, upstream) = (real_gem(PATCHED_LIB), real_gem(UPSTREAM_LIB)); + mount_api_for(&server, None, &sha256_of(&patched)).await; + serve_patched_gem(&server, patched.clone()).await; + serve_upstream_gem(&server, &upstream).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + std::fs::create_dir_all(&proj).unwrap(); + write_manifest_pair(&proj); + let home = tmp.path().join("system-home"); + let bin_dir = tmp.path().join("fake-bin"); + stage_system_home_copy(&home, &bin_dir); + let gem_dir = install_real_gem(&home, UPSTREAM_LIB); + let leaf = format!("{DEP}-{DEP_VERSION}"); + let cache = home.join("cache").join(format!("{leaf}.gem")); + let spec = home.join("specifications").join(format!("{leaf}.gemspec")); + + // The shared copy becomes the patched build. + let uri = server.uri(); + let rubygems = format!("{uri}/upstream"); + let env = [ + ("PATH", bin_dir.to_str().unwrap()), + ("SOCKET_RUBYGEMS_URL", rubygems.as_str()), + ]; + let (code, _, stderr) = common::run_with_env( + &proj, + &scan_args(&proj, &uri, &["--json", "--gem-refresh-shared"]), + &env, + ); + assert_eq!(code, 0, "{case}: {stderr}"); + assert_eq!(installed_lib(&gem_dir), PATCHED_LIB, "{case}: premise"); + std::fs::write(proj.join("Gemfile.lock"), converged_lock(&uri)).unwrap(); + let held_before = snapshot(&home); + + let mut args = unwind.to_vec(); + args.extend([ + "--cwd", + proj.to_str().unwrap(), + "--api-url", + uri.as_str(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + uri.as_str(), + ]); + if json { + args.push("--json"); + } + let (code, stdout, stderr) = common::run_with_env(&proj, &args, &env); + assert_eq!(code, 0, "{case}:\n{stdout}\n{stderr}"); + let lock = std::fs::read_to_string(proj.join("Gemfile.lock")).unwrap(); + assert!(!lock.contains("/patch-registry/"), "{case}:\n{lock}"); + assert!( + snapshot(&home) == held_before, + "{case}: the shared gem home is left alone" + ); + + let remove_files = format!("{} {}", spec.display(), cache.display()); + let warning = if json { + let env = common::parse_json_envelope(&stdout); + let details = details_with_code(&env, "upstream_gem_stale_install"); + assert_eq!(details.len(), 1, "{case}: {env}"); + let reinstall = details_with_code(&env, "reinstall_required"); + assert!( + reinstall + .iter() + .all(|d| d.contains("`bundle install` keeps")), + "{case}: {reinstall:?}" + ); + assert!( + details[0].contains(&format!( + "remove {}, {} and run `bundle install`", + spec.display(), + cache.display() + )), + "{case}: {}", + details[0] + ); + details[0].clone() + } else { + assert_eq!( + stderr.matches("still holds the patched build").count(), + 1, + "{case}: one warning:\n{stderr}" + ); + assert!( + stderr.contains(&format!("run `rm -f {remove_files} && bundle install`")), + "{case}: the remedy as a command:\n{stderr}" + ); + if unwind[0] == "rollback" { + assert!( + stdout.contains("1 unwired package keeps its patched bytes") + && stdout.contains("`bundle install` keeps") + && !stdout.contains("package-manager install."), + "{case}: the note defers to the gem warning:\n{stdout}" + ); + } + stderr.clone() + }; + assert!( + warning.contains("bundle config set --local path vendor/bundle && bundle install"), + "{case}: {warning}" + ); + assert!( + !warning.contains("--gem-refresh-shared") && !warning.to_lowercase().contains("re-run"), + "{case}: a second unwind has nothing to unwind: {warning}" + ); + + // Why no re-run is named: the wiring is gone. + let mut again = args.clone(); + again.push("--gem-refresh-shared"); + let (code, _, _) = common::run_with_env(&proj, &again, &env); + assert_ne!(code, 0, "{case}: premise: a second unwind finds nothing"); + assert!(snapshot(&home) == held_before, "{case}"); + } +} + /// A registry that is refused (plain http, and not this machine) is not /// asked what the upstream gem is. `rollback` still puts the lock back, /// leaves the installed copy as it is, and says so: the copy is reported as From 6e00270cb854cf27d5509bb24e32eb8b948698aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:32:37 +0000 Subject: [PATCH 3/5] Name a working remedy after a gem unwind After a hosted gem rollback or remove, the warning about a patched copy left in a shared gem home said to re-run with --gem-refresh-shared. The first run removed the wiring, so the re-run exits 1 and the shared copy stays patched. In the unwind direction the warning now names the project-local bundle path, or the files to remove before bundle install fetches the upstream gem into the shared home. Rollback's reinstall note no longer implies that the next install replaces such a copy. Fixes #2086 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSmGF7hUwWjuXgRvcM --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- .../src/commands/gem_refresh.rs | 48 ++++++- .../socket-patch-cli/src/commands/rollback.rs | 122 ++++++++++++++---- docs/ecosystems.md | 8 ++ 4 files changed, 147 insertions(+), 37 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0b8d58656..ffe093f6a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -452,11 +452,11 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What is reported.* - Each refreshed materialization is a `redirect_gem_install_refreshed` note in the JSON `warnings[]`; a human run prints one progress line per kind instead (`Replaced the installed copy of 2 gems with the patched build: …`). A replaced cache-dir archive is listed with the files to commit. -- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; never a delete list); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. +- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; never a delete list in this direction); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install` — the one case where a shared home gets a delete list, said with its cost: another project that loads the copy needs a `bundle install` too. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. @@ -2176,7 +2176,7 @@ command's integration tests check its output. | `hosted_reverted` | `removed` | remove (v5.0): a hosted lockfile pin was restored to its upstream registry entry as part of removing the patch (`verified` on dry-run). Beside a manifest entry it bypasses `summary.removed` like `vendor_reverted`. v5.0: carries `details.mode: "hosted"`. | | `hosted_revert_failed` | top-level error | remove (v5.0): a matched hosted pin could not be restored to its upstream registry entry (`--offline`, a registry that does not answer, `bun.lockb`, a lock shape the restore refuses — see "Hosted unwind coverage"), or writing the restored files failed; the message names the `git checkout -- ` remedy. The manifest was not modified, exit 1. Rollback's counterpart is a `failed` `hosted_restore_refused` event (exit 1). v4's `hosted_revert_unsupported` is no longer emitted (every ecosystem has a restore). | | `cargo_cache_patch_kept` | `scan --prune`/`--sync` top-level `warnings[]` (human: `GC: …`) | a Cargo manifest entry the crawl no longer reports (the lock bumped or dropped the crate) was NOT pruned because its copy in the shared `$CARGO_HOME/registry/src` cache still carries the agent-mode patch; the record holds the only blobs that can restore it. The detail names the purl and `socket-patch rollback ` (with `--global` when a `cargo vendor` dir hides the registry cache from the project crawl), which restores the copy and drops the entry. Never affects the exit. | -| `reinstall_required` | rollback `warnings[]` | rollback (v5.0): vendored/hosted wiring was unwound, but installed trees keep their patched bytes until the next package-manager install — the stale-install advisory. When the run also emits a Bun advisory (`vendor_bun_reinstall_required` / `redirect_bun_reinstall_required`) the detail and the human note add " (Bun: a plain `bun install` keeps them; run `bun install --force`)". When it emits a PyPI advisory (`vendor_pypi_reinstall_required` / `redirect_pypi_reinstall_required`) they add " (pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync: run the reinstall the pypi_reinstall_required warning names)". | +| `reinstall_required` | rollback `warnings[]` | rollback (v5.0): vendored/hosted wiring was unwound, but installed trees keep their patched bytes until the next package-manager install — the stale-install advisory. When the run also emits a Bun advisory (`vendor_bun_reinstall_required` / `redirect_bun_reinstall_required`) the detail and the human note add " (Bun: a plain `bun install` keeps them; run `bun install --force`)". When it emits a PyPI advisory (`vendor_pypi_reinstall_required` / `redirect_pypi_reinstall_required`) they add " (pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync: run the reinstall the pypi_reinstall_required warning names)". When it emits `upstream_gem_stale_install` (a gem left on its patched build) they add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". | | `hosted_state_not_preservable` | rollback / remove `warnings[]` | rollback `--preserve-state` (v5.0): hosted pins were restored to upstream anyway — the lockfile pins are hosted mode's only record, so there is no local state to preserve; re-run `scan --mode hosted` to re-wire. (`remove --preserve-state` reports the same code in its `warnings[]` — manifest-backed and hosted-only alike — and prints it as a `Note:` on stderr in human mode.) | | `out_of_scope_copies_restored` | rollback `warnings[]` | path-scoped rollback (v5.0): a selected patch had installed copies outside the given patterns; ALL copies were restored (patches are per-package). Informational — never flips the exit. | | `patched_in_other_scope` | rollback `warnings[]` | the manifest records no scope, so before a rollback drops a record it restored, found already original, or found not installed in its own scope, it checks the other scope (the project at `--cwd` for a `-g` / `--global-prefix` run, the default global install otherwise). A copy there that still holds the patch's afterHash bytes, or has a patched file that exists but cannot be hashed, keeps the record (with its variant group) and its blobs. This warning names the purl, the copy and the rollback of just that purl that restores it (`socket-patch rollback ` or `socket-patch rollback -g`, plus `--cwd` when the run used one). Never flips the exit (#450). | diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 28298a8ae..07112e3b6 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -393,6 +393,13 @@ fn retry_hint(direction: Direction, why: Option<&Why>) -> &'static str { } } +/// What replacing a shared copy by hand costs the other projects that load +/// it: until their own `bundle install`, the gem is missing for them. +fn other_projects_reinstall(gems: usize) -> String { + let them = if gems == 1 { "it" } else { "them" }; + format!("another project that loads {them} needs a `bundle install` too") +} + /// `action` after `hint` (which ends mid-sentence), or as a sentence of /// its own when there is none. fn after_hint(hint: &str, action: &str) -> String { @@ -465,9 +472,18 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh Some((dir, false)) if !matches!(why, Some(Why::Disabled | Why::Failed(_))) => format!( "{purl} {switched}, but the shared gem home still holds its {stale} install at \ {}, and {reuse}. Other projects may load that gem home, so it was left alone. \ - Install the {wanted} gem for this project only with `{LOCAL_PATH_REMEDY}`, or \ - re-run with `--gem-refresh-shared` to replace the shared copy", - dir.display() + Install the {wanted} gem for this project only with `{LOCAL_PATH_REMEDY}`, or {}", + dir.display(), + match direction { + Direction::Patched => { + "re-run with `--gem-refresh-shared` to replace the shared copy".to_string() + } + Direction::Upstream => format!( + "replace the shared copy: remove {} and run `bundle install` ({})", + display_list(&files_to_remove(gem)), + other_projects_reinstall(1) + ), + } ), Some((dir, _)) => format!( "{purl} {switched}, but its {stale} install at {} was not refreshed{}, and \ @@ -637,6 +653,9 @@ pub(crate) fn report( let mut local: BTreeMap> = BTreeMap::new(); // The gems left alone in a shared home that are patched in place. let mut shared_in_place = 0; + // What to remove so `bundle install` fetches the gems left alone in a + // shared home again. + let mut shared_files: Vec = Vec::new(); for gem in stale { let why = why_stale(gem, attempt); if why == Why::Shared && gem.installed.is_some() && gem.in_place { @@ -648,6 +667,7 @@ pub(crate) fn report( )); match (&why, &gem.installed) { (Why::Shared, Some((dir, _))) => { + shared_files.extend(files_to_remove(gem)); let home = dir.parent().and_then(Path::parent).unwrap_or(dir); shared .entry(home.display().to_string()) @@ -741,10 +761,24 @@ pub(crate) fn report( place from the upstream archive beside it. ", ); } - bullets.push(format!( - "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or re-run \ - with `--gem-refresh-shared` to replace the shared {copies}." - )); + bullets.push(match direction { + Direction::Patched => format!( + "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`, or \ + re-run with `--gem-refresh-shared` to replace the shared {copies}." + ), + // An unwind can't be re-run (see `retry_hint`), so the shared + // copies are replaced by hand (#2086). + Direction::Upstream => format!( + "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`. To \ + replace the shared {copies}, run `rm -f {} && bundle install`; {}.", + shared_files + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(" "), + other_projects_reinstall(shared_gems) + ), + }); } for (why, gems) in &local { let files: Vec = gems.iter().flat_map(|gem| files_to_remove(gem)).collect(); diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 9a9d18a0e..36f2e0d1a 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -439,23 +439,60 @@ fn bun_reinstall_advised<'a>(mut codes: impl Iterator) -> bool { }) } -/// The qualifiers the generic reinstall note gets next to a Bun (#764) or -/// PyPI (#477) reinstall advisory. -fn reinstall_qualifiers(bun: bool, pypi: bool) -> String { +/// Appended to the generic reinstall note next to a gem the unwind left on +/// its patched build (#2086): Bundler counts an installed gem as satisfied. +const GEM_REINSTALL_QUALIFIER: &str = + " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)"; + +/// True when the run's leg warnings name a gem still on its patched build. +fn gem_reinstall_advised<'a>(mut codes: impl Iterator) -> bool { + codes.any(|c| c == crate::commands::gem_refresh::Direction::Upstream.stale_code()) +} + +/// The package managers whose reinstall advisory qualifies the generic +/// reinstall note: Bun (#764), PyPI (#477) and Bundler (#2086). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +struct ReinstallAdvised { + bun: bool, + pypi: bool, + gem: bool, +} + +impl ReinstallAdvised { + fn of<'a>(codes: impl Iterator + Clone) -> Self { + Self { + bun: bun_reinstall_advised(codes.clone()), + pypi: crate::commands::pypi_reinstall::advised(codes.clone()), + gem: gem_reinstall_advised(codes), + } + } +} + +/// The qualifiers the generic reinstall note gets next to those advisories. +fn reinstall_qualifiers(advised: ReinstallAdvised) -> String { format!( - "{}{}", - if bun { BUN_REINSTALL_QUALIFIER } else { "" }, - if pypi { + "{}{}{}", + if advised.bun { + BUN_REINSTALL_QUALIFIER + } else { + "" + }, + if advised.pypi { crate::commands::pypi_reinstall::NOTE_QUALIFIER } else { "" + }, + if advised.gem { + GEM_REINSTALL_QUALIFIER + } else { + "" } ) } /// The reinstall note for packages whose wiring was undone but whose /// installed tree still holds patched bytes. -fn format_reinstall_note(still_patched: usize, dry_run: bool, bun: bool, pypi: bool) -> String { +fn format_reinstall_note(still_patched: usize, dry_run: bool, advised: ReinstallAdvised) -> String { let keep = match (still_patched == 1, dry_run) { (true, false) => "keeps its", (true, true) => "would keep its", @@ -466,7 +503,7 @@ fn format_reinstall_note(still_patched: usize, dry_run: bool, bun: bool, pypi: b "Note: {} {keep} patched bytes in installed trees until the next \ package-manager install{}.", plural(still_patched, "unwired package", "unwired packages"), - reinstall_qualifiers(bun, pypi) + reinstall_qualifiers(advised) ) } @@ -2566,14 +2603,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let unwired_any = !vendored_leg.reverted.is_empty() || !vendored_leg.preserved.is_empty() || !hosted_leg.reverted.is_empty(); - let bun_advised = bun_reinstall_advised( - vendored_leg - .warnings - .iter() - .chain(hosted_leg.warnings.iter()) - .map(|(code, _)| code.as_str()), - ); - let pypi_advised = crate::commands::pypi_reinstall::advised( + let advised = ReinstallAdvised::of( vendored_leg .warnings .iter() @@ -2586,7 +2616,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { format!( "unwired packages keep their patched bytes in installed trees until \ the next package-manager install{}", - reinstall_qualifiers(bun_advised, pypi_advised) + reinstall_qualifiers(advised) ), )); } @@ -2864,12 +2894,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { if still_patched > 0 { println!( "\n{}", - format_reinstall_note( - still_patched, - args.common.dry_run, - bun_advised, - pypi_advised - ) + format_reinstall_note(still_patched, args.common.dry_run, advised) ); } } @@ -6590,12 +6615,12 @@ mod tests { #[test] fn reinstall_note_tense_and_number() { assert_eq!( - format_reinstall_note(1, false, false, false), + format_reinstall_note(1, false, ReinstallAdvised::default()), "Note: 1 unwired package keeps its patched bytes in installed trees until the \ next package-manager install." ); assert_eq!( - format_reinstall_note(2, true, false, false), + format_reinstall_note(2, true, ReinstallAdvised::default()), "Note: 2 unwired packages would keep their patched bytes in installed trees \ until the next package-manager install." ); @@ -6606,7 +6631,14 @@ mod tests { #[test] fn reinstall_note_defers_to_the_bun_advisory() { assert_eq!( - format_reinstall_note(1, false, true, false), + format_reinstall_note( + 1, + false, + ReinstallAdvised { + bun: true, + ..Default::default() + } + ), "Note: 1 unwired package keeps its patched bytes in installed trees until the \ next package-manager install (Bun: a plain `bun install` keeps them; run \ `bun install --force`)." @@ -6963,11 +6995,47 @@ mod tests { assert_eq!(rollback_failure_code(&r), "rollback_failed"); } + /// #2086: next to a gem the unwind left on its patched build, the note + /// must not imply that the next `bundle install` replaces it. + #[test] + fn reinstall_note_defers_to_the_gem_warning() { + let advised = + ReinstallAdvised::of(["cleanup_failed", "upstream_gem_stale_install"].into_iter()); + assert_eq!( + advised, + ReinstallAdvised { + gem: true, + ..Default::default() + } + ); + assert_eq!( + format_reinstall_note(1, false, advised), + "Note: 1 unwired package keeps its patched bytes in installed trees until the \ + next package-manager install (Bundler: `bundle install` keeps an installed gem; \ + see the gem warning for what to run)." + ); + // The scan direction's warning is not an unwind's. + assert!(!gem_reinstall_advised( + [ + "redirect_gem_stale_install", + "upstream_gem_install_refreshed" + ] + .into_iter() + )); + } + /// #477: next to a PyPI reinstall advisory the note must not imply /// that the next sync refreshes the copy. #[test] fn reinstall_note_defers_to_the_pypi_advisory() { - let note = format_reinstall_note(1, false, false, true); + let note = format_reinstall_note( + 1, + false, + ReinstallAdvised { + pypi: true, + ..Default::default() + }, + ); assert!( note.contains("(pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync") && note.contains("pypi_reinstall_required"), diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2e0c021f6..4b8e760ba 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2140,6 +2140,14 @@ the shared gem home. Another project that pins the upstream build of the same ge loads the patched code too, and its `bundle pristine` fails on the checksum until it is patched as well. +`rollback` and `remove` take `--gem-refresh-shared` as well, on the run that removes the patch: +it then puts the upstream gem back in the shared gem home. Without it the run warns that the +shared copy still holds the patched build. Running the command again doesn't help, because the +patch is already removed and there is nothing left to roll back. The warning names what to run +instead: the `bundle config` line above, or an `rm -f` of the gem's `specifications/` entry and +its `cache/` archive followed by `bundle install`, which fetches the upstream gem into the shared +gem home. Another project that loads that copy needs a `bundle install` afterwards too. + A shared gem home also holds gem versions this project doesn't use: the gems Ruby ships (`rake`, `rexml`, ...) and the versions other projects installed. Hosted and vendored mode patch what `Gemfile.lock` resolves, so a version the lock doesn't list is skipped, never a failure: hosted From 72974397e6e464966d9ca52ca30985733b400b13 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 05:42:37 +0000 Subject: [PATCH 4/5] Quote rm paths and state the shared-copy cost Review of the unwind remedy: - The cost named for replacing a shared copy by hand was wrong. A project that still pins the hosted patch keeps the upstream copy on its next bundle install; say that instead. - A path in the rm -f remedy is shell-quoted when the shell would split it (a gem home under a directory with a space). - An unwind no longer names --gem-refresh-shared for a project path outside the project directory either. - The end-to-end test asserts rollback's reinstall_required detail and the reason a second unwind fails. Refs #2086 Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeSmGF7hUwWjuXgRvcM --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 +- .../src/commands/gem_refresh.rs | 161 +++++++++++++++--- .../tests/e2e_redirect_gem_stale_install.rs | 30 +++- docs/ecosystems.md | 4 +- 4 files changed, 167 insertions(+), 32 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index ffe093f6a..d50343bfc 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -452,11 +452,11 @@ The rewriter reads a fixed set of candidate files from the project root: the npm *What is reported.* - Each refreshed materialization is a `redirect_gem_install_refreshed` note in the JSON `warnings[]`; a human run prints one progress line per kind instead (`Replaced the installed copy of 2 gems with the patched build: …`). A replaced cache-dir archive is listed with the files to commit. -- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; never a delete list in this direction); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. +- Each materialization that is still stale is a `redirect_gem_stale_install` warning in the JSON `warnings[]`, in three flavors: an installed copy in a SHARED gem home (left alone; the remedy is the project-local bundle path, `bundle config set --local path vendor/bundle && bundle install`, which installs every gem of the project from the lock's sources and leaves the shared home untouched, or `--gem-refresh-shared`; no delete list for a copy that was only left alone); a PROJECT-LOCAL installed copy the refresh did not fix (the reason — the archive could not be downloaded or verified, a native build failed, the path is outside the project, the refresh is turned off — and the files to remove by hand, including the project's stale cache-dir archive when there is one); and a cache-dir archive alone. An installed copy that agent mode patched in place (stale by its upstream archive only, see above) gets the first two flavors in its own words: the detail names the archive and what a reinstall from it does, the delete list is that archive alone (never the `specifications` entry), and it never calls the install unpatched. Its refresh note reads `replaced the upstream archive of the install patched in place at …`, and the human progress line `Replaced the upstream archive beside 1 gem patched in place with the patched gem: …`; that archive is not a file to commit. The warning re-fires on every re-scan until the stale materialization is gone. - A human run prints ONE warning for all of them: how many gems, which gems in which gem home (or why they were not refreshed), why in one sentence, and the remedy as a command. Its headline is `N gems are still unpatched on disk after the switch to hosted patches` when none of the gems it covers was patched in place; when every one was, `N gems patched in place still have their upstream archives on disk after the switch to hosted patches`; and with both kinds, `N gems still have unpatched files or archives on disk after the switch to hosted patches`. - A stale-flagged purl is additionally **excluded from the same run's `--vex` `assume_applied` set** — the envelope must never attest a CVE its own warning says is live; the purl falls back to normal installed-tree verification (a patched install still attests, a stale one is omitted). A same-run `--vex` may still fail on "nothing to attest" per the embedded-VEX contract. -*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install` — the one case where a shared home gets a delete list, said with its cost: another project that loads the copy needs a `bundle install` too. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". +*The unwind direction.* After a hosted unwind — `rollback` / `remove` of a hosted pin, scan's withdrawn-patch restore, `vendor --revert` of a package vendored over hosted wiring before v5 — put a gem back on its upstream registry entry, its installed copies and archives hold the PATCHED gem, with the same consequences in reverse: the patched code keeps running, and on bundler ≥ 2.6 `bundle pristine` fails on the restored upstream checksum. The unwind applies the same refresh with the upstream gem: the sha256 is the restored lock's `CHECKSUMS` entry, else the rubygems.org compact index; the archive is taken from disk, else downloaded from rubygems.org when the lock resolves the gem from it (a gem from another remote is refreshed only from an archive already on disk). An installed copy is stale when its `/cache/.gem` is readable and is not the upstream archive (ruby-platform gems only: the lock's checksum names that archive). A copy whose gem home has no readable archive of it (a pruned `cache/`: Bundler 4.1's `prune` setting, a slim image, `gem cleanup`) is judged as the scan direction judges it (#2092): the unwind fetches the record of each patch the gem was pinned to (`…/patches/view/`, for that gem only, through the run's API client) and the copy is stale when every file a record lists hashes to its `afterHash`. Each such copy is judged on its own files, and it is then replaced from the upstream archive like any other; no `cache/` dir is created for it. When no record proves the copy patched and one of them could not judge it (`--offline`, a failed fetch, a patch the API has no record of, record files missing from the copy), nothing tells it from the patched build: it is left as it is and reported under `upstream_gem_stale_install` as one that could not be checked, with that reason and the files to remove. After a request the API does not answer (a network error), no other record is asked for. Such a copy is judged the same way when nothing proves the upstream sha256 (a lock without `CHECKSUMS`, with `--offline` or a registry error): one proven patched is then reported as left on the patched build, since there is no verified archive to replace it with. An unwind with no such copy fetches no patch record. Notes are `upstream_gem_install_refreshed` / `upstream_gem_install_would_refresh`; an installed copy left on the patched build is `upstream_gem_stale_install` (one consolidated warning in a human run), and an archive left in bundler's cache dir keeps its `upstream_gem_stale_cache` warning. When the lock pins no `CHECKSUMS` sha256 for the gem and the registry that would give one is refused (a `SOCKET_RUBYGEMS_URL` that is plain `http` and not a loopback host), nothing can tell an installed copy from the patched build: the copy is left as it is and reported under the same `upstream_gem_stale_install` code as one that "could not be checked against the upstream gem", with that reason and the files to remove, and the human warning counts it apart ("N gems on disk could not be checked …"). A gem whose installed copies were refreshed is not counted in rollback's "keep their patched bytes" note. A copy left by `--no-gem-install-refresh` or a failed refresh is named with the files to remove before `bundle install`, and no re-run: the unwind already removed the wiring a second run would look for. A copy left alone in a SHARED gem home gets no re-run either (#2086): `--gem-refresh-shared` replaces it only on the run that unwinds the gem, so the warning names the project-local bundle path, or, to replace the shared copy, the files to remove (its `specifications` entry and `/cache/.gem`) before `bundle install`, said with its cost: another project that still pins the hosted patch of that gem version then loads the upstream code, which `socket-patch scan` reports there. A path in the warning's `rm -f` command is shell-quoted when it needs to be. A project path outside the project directory that the unwind left alone is named without `--gem-refresh-shared`, for the same reason. Next to an `upstream_gem_stale_install` warning, rollback's "keep their patched bytes" note and its `reinstall_required` detail add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". *What never refreshes.* A hosted → vendored takeover (`vendor`, `scan` / `get --mode vendored` over a hosted pin) puts the gem on its upstream entry only on its way to the vendored `path:` source, which is what Bundler loads from then on. The copies Bundler already holds are unused leftovers there, so the takeover changes none of them and downloads no gem for them: resetting the installed copy to the upstream build would cost a registry download in the mode that needs none, and would turn a patched leftover into an unpatched one that `vex` reports against the vendored artifact (`vendored_tree_out_of_sync`, whose gem wording names the copy and how to remove it). Its `upstream_gem_stale_cache` advisory about a patched cache-dir archive is as before. A vendored unwind (`remove`, `rollback`, `vendor --revert`, `scan --prune`, `vendor`'s reconcile of a vendored gem) likewise only names that archive, and never replaces it. diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 07112e3b6..9bca9e8ce 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -142,7 +142,15 @@ impl Policy { /// `.bundle/config` `path` or `cache_path` naming another directory, a /// `vendor/bundle` that is a symlink. The repository picks those, so /// they are written only on the same request as a shared gem home. - fn may_replace(&self, path: &Path, project_local: bool) -> Result<(), Why> { + /// + /// The out-of-tree reason names `--gem-refresh-shared` only where a + /// re-run with it can still act: an unwind's can't (see `retry_hint`). + fn may_replace( + &self, + path: &Path, + project_local: bool, + direction: Direction, + ) -> Result<(), Why> { if !project_local && !self.shared { return Err(Why::Shared); } @@ -151,8 +159,14 @@ impl Policy { } if !self.shared && !resolves_inside(&self.root, path) { return Err(Why::Failed( - "it is outside the project directory; `--gem-refresh-shared` refreshes it too" - .to_string(), + match direction { + Direction::Patched => { + "it is outside the project directory; `--gem-refresh-shared` refreshes \ + it too" + } + Direction::Upstream => "it is outside the project directory", + } + .to_string(), )); } Ok(()) @@ -259,7 +273,7 @@ pub(crate) async fn attempt( .map(|path| (Target::CacheArchive(path.clone()), true)), ]; for (target, project_local) in candidates.into_iter().flatten() { - match policy.may_replace(target.path(), project_local) { + match policy.may_replace(target.path(), project_local, direction) { Ok(()) => targets.push(target), Err(why) => { out.left.insert(target.path().to_path_buf(), why); @@ -393,11 +407,35 @@ fn retry_hint(direction: Direction, why: Option<&Why>) -> &'static str { } } -/// What replacing a shared copy by hand costs the other projects that load -/// it: until their own `bundle install`, the gem is missing for them. -fn other_projects_reinstall(gems: usize) -> String { +/// What replacing a shared copy with the upstream gem costs another +/// project: one whose lock still pins the hosted patch of that gem version +/// has it installed already, so its `bundle install` keeps the upstream +/// copy (the mirror of what `--gem-refresh-shared` costs on a scan). +fn other_projects_cost(gems: usize) -> String { let them = if gems == 1 { "it" } else { "them" }; - format!("another project that loads {them} needs a `bundle install` too") + format!( + "another project that still pins the hosted patch of {them} then loads the upstream \ + code, which `socket-patch scan` reports there" + ) +} + +/// `path` as one word of a POSIX shell command: as it is when every +/// character is safe unquoted, else single-quoted. +fn shell_word(path: &Path) -> String { + let text = path.display().to_string(); + let safe = |c: char| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c); + if !text.is_empty() && text.chars().all(safe) { + text + } else { + format!("'{}'", text.replace('\'', "'\\''")) + } +} + +/// The `rm -f … && bundle install` that makes Bundler fetch again the gems +/// `files` belong to. +fn reinstall_command(files: &[PathBuf]) -> String { + let words: Vec = files.iter().map(|path| shell_word(path)).collect(); + format!("rm -f {} && bundle install", words.join(" ")) } /// `action` after `hint` (which ends mid-sentence), or as a sentence of @@ -481,7 +519,7 @@ pub(crate) fn stale_detail(direction: Direction, gem: &StaleGem, why: Option<&Wh Direction::Upstream => format!( "replace the shared copy: remove {} and run `bundle install` ({})", display_list(&files_to_remove(gem)), - other_projects_reinstall(1) + other_projects_cost(1) ), } ), @@ -770,20 +808,15 @@ pub(crate) fn report( // copies are replaced by hand (#2086). Direction::Upstream => format!( "{why}To install {them} for this project only, run `{LOCAL_PATH_REMEDY}`. To \ - replace the shared {copies}, run `rm -f {} && bundle install`; {}.", - shared_files - .iter() - .map(|p| p.display().to_string()) - .collect::>() - .join(" "), - other_projects_reinstall(shared_gems) + replace the shared {copies}, run `{}`; {}.", + reinstall_command(&shared_files), + other_projects_cost(shared_gems) ), }); } for (why, gems) in &local { let files: Vec = gems.iter().flat_map(|gem| files_to_remove(gem)).collect(); - let files: Vec = files.iter().map(|p| p.display().to_string()).collect(); - let reinstall = format!("run `rm -f {} && bundle install`", files.join(" ")); + let reinstall = format!("run `{}`", reinstall_command(&files)); let names = labels(gems.iter().map(|gem| gem.purl.as_str())); bullets.push(match why { Why::Unverified(_) => format!( @@ -1516,8 +1549,9 @@ mod tests { "`bundle install` reuses an installed gem instead of fetching the upstream \ one. To install them for this project only, run `bundle config set --local \ path vendor/bundle && bundle install`. To replace the shared copies, run \ - `rm -f {} {} {} {} && bundle install`; another project that loads them \ - needs a `bundle install` too.", + `rm -f {} {} {} {} && bundle install`; another project that still pins \ + the hosted patch of them then loads the upstream code, which \ + `socket-patch scan` reports there.", file("specifications", "rack-1.0.0.gemspec"), file("cache", "rack-1.0.0.gem"), file("specifications", "rexml-1.0.0.gemspec"), @@ -1527,6 +1561,68 @@ mod tests { ); } + /// A path in the `rm -f` remedy is one shell word: a gem home under a + /// directory with a space or a quote in its name is quoted, so the + /// command removes the files it names. + #[tokio::test] + async fn the_rm_remedy_quotes_a_path_the_shell_would_split() { + assert_eq!( + shell_word(Path::new("/opt/gems/rack-1.0.0.gem")), + "/opt/gems/rack-1.0.0.gem" + ); + assert_eq!( + shell_word(Path::new("/Users/Jane Doe/.gem")), + "'/Users/Jane Doe/.gem'" + ); + assert_eq!( + shell_word(Path::new("/tmp/it's/$HOME")), + r"'/tmp/it'\''s/$HOME'" + ); + + let tmp = tempfile::tempdir().unwrap(); + let (proj, home) = (tmp.path().join("proj"), tmp.path().join("Jane Doe/gemhome")); + std::fs::create_dir_all(&proj).unwrap(); + let file = |dir: &str, name: &str| home.join(dir).join(name).display().to_string(); + let expected = format!( + "run `rm -f '{}' '{}' && bundle install`", + file("specifications", "rack-1.0.0.gemspec"), + file("cache", "rack-1.0.0.gem") + ); + + // A shared home after an unwind. + let stale = vec![installed("rack", &home, false)]; + let policy_on = policy(&proj, true, false, false); + let upstream = |policy: &Policy| { + let (stale, policy) = (stale.clone(), policy.clone()); + async move { + let pass = attempt( + &stale, + unobtainable, + &Source::DiskOnly, + &policy, + Direction::Upstream, + ) + .await; + report(Direction::Upstream, &stale, &pass, &policy) + .summary + .expect("a summary") + .paragraph() + } + }; + let summary = upstream(&policy_on).await; + assert!(summary.contains(&expected), "{summary}"); + + // A project-local copy the run did not refresh. + let stale = vec![installed("rack", &home, true)]; + let policy_off = policy(&proj, false, false, false); + let pass = pass(&stale, &policy_off).await; + let summary = report(Direction::Patched, &stale, &pass, &policy_off) + .summary + .expect("a summary") + .paragraph(); + assert!(summary.contains(&expected), "{summary}"); + } + /// A copy that could not be checked against the upstream gem (the /// registry that would say is refused) is reported with the reason and /// the files to remove, apart from the copies known to be stale: it is @@ -2087,5 +2183,30 @@ mod tests { !summary.contains("Re-run without") && summary.contains("Run `rm -f "), "{summary}" ); + + // Nor the flag a re-run would take (#2086): the out-of-tree path + // is named with the files to remove alone. + let tried = attempt( + &gems, + unobtainable, + &Source::DiskOnly, + &policy_default, + Direction::Upstream, + ) + .await; + let out = report(Direction::Upstream, &gems, &tried, &policy_default); + for (_, detail) in &out.warnings { + assert!(!detail.contains("--gem-refresh-shared"), "{detail}"); + } + assert!( + out.warnings[2] + .1 + .contains("(it is outside the project directory)") + && out.warnings[2].1.contains("and run `bundle install`"), + "{}", + out.warnings[2].1 + ); + let summary = out.summary.expect("stale gems").paragraph(); + assert!(!summary.contains("--gem-refresh-shared"), "{summary}"); } } 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 8929cb049..b97bc96fd 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 @@ -2642,13 +2642,16 @@ async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { let env = common::parse_json_envelope(&stdout); let details = details_with_code(&env, "upstream_gem_stale_install"); assert_eq!(details.len(), 1, "{case}: {env}"); - let reinstall = details_with_code(&env, "reinstall_required"); - assert!( - reinstall - .iter() - .all(|d| d.contains("`bundle install` keeps")), - "{case}: {reinstall:?}" - ); + // rollback's run-level advisory defers to the gem warning. + if unwind[0] == "rollback" { + let reinstall = details_with_code(&env, "reinstall_required"); + assert_eq!(reinstall.len(), 1, "{case}: {env}"); + assert!( + reinstall[0].contains("`bundle install` keeps an installed gem"), + "{case}: {}", + reinstall[0] + ); + } assert!( details[0].contains(&format!( "remove {}, {} and run `bundle install`", @@ -2691,8 +2694,17 @@ async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { // Why no re-run is named: the wiring is gone. let mut again = args.clone(); again.push("--gem-refresh-shared"); - let (code, _, _) = common::run_with_env(&proj, &again, &env); - assert_ne!(code, 0, "{case}: premise: a second unwind finds nothing"); + let (code, stdout, stderr) = common::run_with_env(&proj, &again, &env); + assert_eq!(code, 1, "{case}: premise:\n{stdout}\n{stderr}"); + let nothing = match (json, unwind[0]) { + (true, _) => "\"status\": \"error\"", + (false, "rollback") => "nothing to roll back", + (false, _) => "nothing to remove", + }; + assert!( + format!("{stdout}{stderr}").contains(nothing), + "{case}: premise: a second unwind finds nothing:\n{stdout}\n{stderr}" + ); assert!(snapshot(&home) == held_before, "{case}"); } } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 4b8e760ba..1b3d3e63f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2146,7 +2146,9 @@ shared copy still holds the patched build. Running the command again doesn't hel patch is already removed and there is nothing left to roll back. The warning names what to run instead: the `bundle config` line above, or an `rm -f` of the gem's `specifications/` entry and its `cache/` archive followed by `bundle install`, which fetches the upstream gem into the shared -gem home. Another project that loads that copy needs a `bundle install` afterwards too. +gem home. Another project that still pins the patched build of that gem version then loads the +upstream code; a `socket-patch scan` there reports it, and `--gem-refresh-shared` on that scan +puts the patched build back. A shared gem home also holds gem versions this project doesn't use: the gems Ruby ships (`rake`, `rexml`, ...) and the versions other projects installed. Hosted and vendored mode patch what From 05983230c08e33aa58217d259d4a2396afc42684 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 08:43:33 +0000 Subject: [PATCH 5/5] Expect the shell-quoted remove paths in the gem unwind tests The unwind warning now prints each `rm -f` path through `shell_word`, which single-quotes any path holding a character outside the safe set. A Windows path (backslashes) or a temp dir with a space is printed quoted, but three tests still expected the bare `display()` form: `an_unwind_names_no_rerun_for_a_shared_home`, `vendored_unwind_warns_once_in_a_human_run` and `hosted_unwind_names_no_rerun_for_a_shared_gem_home`. Build the expected words with the same quoting (a test-side copy of `shell_word` in the e2e file) so they hold on Windows and with TMPDIR containing a space. Verified on Linux with both the default TMPDIR and one with a space. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011f9aeQRihEsBSmrqzYJhYi --- .../src/commands/gem_refresh.rs | 8 +++--- .../tests/e2e_redirect_gem_stale_install.rs | 26 ++++++++++++++++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/gem_refresh.rs b/crates/socket-patch-cli/src/commands/gem_refresh.rs index 9bca9e8ce..1166c5634 100644 --- a/crates/socket-patch-cli/src/commands/gem_refresh.rs +++ b/crates/socket-patch-cli/src/commands/gem_refresh.rs @@ -1552,10 +1552,10 @@ mod tests { `rm -f {} {} {} {} && bundle install`; another project that still pins \ the hosted patch of them then loads the upstream code, which \ `socket-patch scan` reports there.", - file("specifications", "rack-1.0.0.gemspec"), - file("cache", "rack-1.0.0.gem"), - file("specifications", "rexml-1.0.0.gemspec"), - file("cache", "rexml-1.0.0.gem"), + shell_word(&home.join("specifications/rack-1.0.0.gemspec")), + shell_word(&home.join("cache/rack-1.0.0.gem")), + shell_word(&home.join("specifications/rexml-1.0.0.gemspec")), + shell_word(&home.join("cache/rexml-1.0.0.gem")), ), ] ); 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 b97bc96fd..fa82cea5e 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 @@ -65,6 +65,20 @@ const PATCHED_LIB: &str = "module StaleProbeGem\n def self.status\n \"PATCHE const UPSTREAM_ARCHIVE: &[u8] = b"upstream-gem-archive-bytes"; const PATCHED_ARCHIVE: &[u8] = b"patched-gem-archive-bytes"; +/// `path` as the CLI prints it in a suggested shell command: unquoted when +/// every character is safe, else single-quoted (mirrors `gem_refresh`'s +/// `shell_word`), so the expectations hold on Windows and in a temp dir +/// whose path has a space. +fn shell_word(path: &Path) -> String { + let text = path.display().to_string(); + let safe = |c: char| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c); + if !text.is_empty() && text.chars().all(safe) { + text + } else { + format!("'{}'", text.replace('\'', "'\\''")) + } +} + fn patched_archive_sha256() -> String { use sha2::Digest as _; hex::encode(sha2::Sha256::digest(PATCHED_ARCHIVE)) @@ -2637,7 +2651,7 @@ async fn hosted_unwind_names_no_rerun_for_a_shared_gem_home() { "{case}: the shared gem home is left alone" ); - let remove_files = format!("{} {}", spec.display(), cache.display()); + let remove_files = format!("{} {}", shell_word(&spec), shell_word(&cache)); let warning = if json { let env = common::parse_json_envelope(&stdout); let details = details_with_code(&env, "upstream_gem_stale_install"); @@ -3582,8 +3596,14 @@ async fn vendored_unwind_warns_once_in_a_human_run() { back to the upstream registry"; assert_eq!(stderr.matches(warning).count(), 1, "{unwind:?}: {stderr}"); assert!( - stderr.contains(&format!("rm -f {}", project_home(&proj).display())) - && stderr.contains(&format!("{} && bundle install", archive.display())), + stderr.contains(&format!( + "rm -f {}", + shell_word( + &project_home(&proj) + .join("specifications") + .join(format!("{DEP}-{DEP_VERSION}.gemspec")) + ) + )) && stderr.contains(&format!("{} && bundle install", shell_word(&archive))), "{unwind:?}: {stderr}" ); assert!(