From 5d02aac4709331bb35220332ca614dd5aa823b91 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:23:25 +0000 Subject: [PATCH 1/5] Start gem revert fix for a removed dependency Refs #2325. Assisted-by: Claude Code:claude-fable-5-2 From 0d27b2bc9d647b4755fe113b92852e639a78d41b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:40:14 +0000 Subject: [PATCH 2/5] Add failing tests for a dropped vendored gem After bundle remove, or a move to another release, neither the Gemfile nor Gemfile.lock names the vendored copy. The gem revert still reports the entry as drift and keeps the copy and the ledger record on every run. Three of the unit tests and the end-to-end test fail until the revert learns that case. Refs #2325. Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_vendor_gem_build.rs | 111 ++++++++++ crates/socket-patch-core/src/vendor/gem.rs | 189 ++++++++++++++++++ 2 files changed, 300 insertions(+) diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 0c654c0f7..037f746b4 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2228,6 +2228,117 @@ fn gem_vendor_drops_positional_constraints() { } } +/// #2325: after the project drops a vendored gem (`bundle remove`) or moves +/// it to another release, nothing bundler reads names the vendored copy any +/// more. `vendor --check` reports the dead entry, and each undo command +/// then cleans it up: the copy and its ledger record go, the user's +/// Gemfile and Gemfile.lock stay byte for byte, a frozen install still +/// passes, and `vendor --check` is green again. +#[test] +#[ignore = "host capstone: shells out to a real bundler >= 1.17; the unpinned `test` job \ + skips it, the e2e job runs it with a pinned toolchain via --ignored"] +fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { + // How the project drops the gem, and the command that cleans up. + let cases: [(&str, &[&str]); 4] = [ + ("remove", &["vendor", "--revert"]), + ("remove", &["rollback"]), + ("remove", &["remove", "--yes"]), + ("upgrade", &["vendor", "--revert"]), + ]; + for (how, undo) in cases { + let what = format!("{how}, then `{}`", undo.join(" ")); + let Some((_tmp, proj, _bundler, purl)) = staged_rack_project("dropped gem") else { + return; + }; + let cwd = proj.to_str().unwrap(); + let (code, stdout, stderr) = + run_socket(&proj, &["vendor", "--json", "--offline", "--cwd", cwd]); + assert_eq!(code, 0, "{what}: vendor failed.\n{stdout}\n{stderr}"); + let uuid_dir = proj.join(".socket/vendor/gem").join(UUID); + assert!(uuid_dir.is_dir(), "{what}: vendored copy written"); + + // The user's edit, with real bundler. + let edit = match how { + "remove" => bundle(&proj, &["remove", DEP], false), + _ => { + let version = purl.rsplit('@').next().unwrap(); + let other = if version == "3.1.8" { "3.1.9" } else { "3.1.8" }; + std::fs::write( + proj.join("Gemfile"), + format!("source \"https://rubygems.org\"\n\ngem \"rack\", \"{other}\"\n"), + ) + .unwrap(); + bundle(&proj, &["install"], false) + } + }; + assert!( + edit.status.success(), + "{what}: the user's bundler command (test premise):\n{}", + String::from_utf8_lossy(&edit.stderr) + ); + let gemfile = std::fs::read(proj.join("Gemfile")).unwrap(); + let lock = std::fs::read(proj.join("Gemfile.lock")).unwrap(); + for file in [&gemfile, &lock] { + assert!( + !String::from_utf8_lossy(file).contains(".socket/vendor"), + "{what}: bundler left no reference to the vendored copy (test premise)" + ); + } + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + assert_eq!( + code, 1, + "{what}: vendor --check reports the dead entry.\n{stdout}\n{stderr}" + ); + + // The clean-up. + let mut args: Vec<&str> = undo.to_vec(); + if undo[0] != "vendor" { + args.push(&purl); + } + args.extend(["--json", "--cwd", cwd]); + let (code, stdout, stderr) = run_socket(&proj, &args); + assert_eq!( + code, 0, + "{what}: failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{what}: {env}"); + let all = format!("{stdout}{stderr}"); + assert!( + !all.contains("drift"), + "{what}: a dropped gem is not reported as drift:\n{all}" + ); + + assert!(!uuid_dir.exists(), "{what}: the dead copy is removed"); + let state = proj.join(".socket/vendor/state.json"); + assert!( + !state.exists() || !std::fs::read_to_string(&state).unwrap().contains(UUID), + "{what}: the ledger record is dropped" + ); + assert_eq!( + std::fs::read(proj.join("Gemfile")).unwrap(), + gemfile, + "{what}: the user's Gemfile is left alone" + ); + assert_eq!( + std::fs::read(proj.join("Gemfile.lock")).unwrap(), + lock, + "{what}: the user's Gemfile.lock is left alone" + ); + let install = bundle(&proj, &["install"], true); + assert!( + install.status.success(), + "{what}: a frozen install passes after the clean-up:\n{}", + String::from_utf8_lossy(&install.stderr) + ); + let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); + assert_eq!( + code, 0, + "{what}: vendor --check is green again.\n{stdout}\n{stderr}" + ); + } +} + /// #1821: vendoring over a CRLF Gemfile keeps every line CRLF (the rewired /// `gem` line used to end in a bare LF), a real frozen install accepts the /// result, and revert restores the Gemfile byte for byte. diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 339dbf08f..494de71c4 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -6377,6 +6377,195 @@ mod tests { /// wedge in the ledger forever. #[tokio::test] async fn test_revert_converged_files_are_silent_and_still_remove() { + /// What `bundle remove rack` and a move to rack 3.2.7 leave of the + /// [`GEMFILE_DIRECT`] / [`LOCK_DIRECT`] pair: `(what, Gemfile, lock)`. + fn dropped_gem_pairs() -> [(&'static str, &'static str, &'static str); 2] { + [ + ( + "bundle remove", + "source \"https://rubygems.org\"\n\ngem \"puma\"\n", + "GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n nio4r (~> 2.0)\n\nPLATFORMS\n arm64-darwin-23\n ruby\n\nDEPENDENCIES\n puma\n\nBUNDLED WITH\n 2.5.22\n", + ), + ( + "upgrade", + "source \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"rack\", \"3.2.7\"\n", + "GEM\n remote: https://rubygems.org/\n specs:\n puma (6.4.2)\n nio4r (~> 2.0)\n rack (3.2.7)\n\nPLATFORMS\n arm64-darwin-23\n ruby\n\nDEPENDENCIES\n puma\n rack (= 3.2.7)\n\nBUNDLED WITH\n 2.5.22\n", + ), + ] + } + + /// Vendor rack into a fresh [`GEMFILE_DIRECT`] project, then leave the + /// pair as the user's `gemfile` and `lock`. + async fn vendored_then_edited( + gemfile: &str, + lock: &str, + ) -> (tempfile::TempDir, PathBuf, VendorEntry) { + let (tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let (result, entry, _w) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + tokio::fs::write(root.join(GEMFILE), gemfile).await.unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), lock) + .await + .unwrap(); + (tmp, root, entry.unwrap()) + } + + /// The pair as it stands on disk. + async fn read_pair(root: &Path) -> (String, String) { + ( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) + .await + .unwrap(), + ) + } + + /// #2325: the user dropped the vendored gem (`bundle remove`) or moved + /// it to another release, so neither file names the copy any more. That + /// is not drift: there is nothing to restore, the pair is the user's + /// and stays byte-identical, and the copy goes so the caller can drop + /// the ledger record. + #[tokio::test] + async fn revert_of_a_gem_the_project_dropped_removes_the_copy() { + for (what, gemfile, lock) in dropped_gem_pairs() { + let (_tmp, root, entry) = vendored_then_edited(gemfile, lock).await; + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{what}: {:?}", outcome.error); + assert!(!outcome.drift_skipped(), "{what}: {:?}", outcome.warnings); + assert!( + outcome.lock_entry_removed(), + "{what}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{what}"); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()), + "{what}: the user's pair is left alone" + ); + assert!( + !root.join(format!(".socket/vendor/gem/{UUID}")).exists(), + "{what}: the copy nothing references is removed" + ); + } + } + + /// #2325: a dry run and a `--preserve-state` revert of a dropped gem + /// report it the same way, and neither deletes the copy. + #[tokio::test] + async fn revert_of_a_dropped_gem_keeps_the_copy_on_a_dry_run_and_under_keep_artifact() { + for (what, gemfile, lock) in dropped_gem_pairs() { + for (mode, opts) in [ + ("dry run", RevertOpts::new(true)), + ( + "keep artifact", + RevertOpts { + keep_artifact: true, + ..RevertOpts::new(false) + }, + ), + ] { + let (_tmp, root, entry) = vendored_then_edited(gemfile, lock).await; + let outcome = revert_gem_opts(&entry, &root, opts).await; + assert!(outcome.success, "{what}, {mode}: {:?}", outcome.error); + assert!( + !outcome.drift_skipped() && outcome.lock_entry_removed(), + "{what}, {mode}: {:?}", + outcome.warnings + ); + assert!(!outcome.kept_artifact, "{what}, {mode}"); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()), + "{what}, {mode}" + ); + assert!(root.join(copy_rel()).exists(), "{what}, {mode}"); + } + } + } + + /// A record that cannot be restored stays drift while either file still + /// names the copy, in any spelling: bundler may still load the gem from + /// it, so the copy and both files are kept as found. + #[tokio::test] + async fn revert_of_a_dropped_gem_is_drift_while_a_file_names_the_copy() { + let (_, gemfile, lock) = dropped_gem_pairs()[0]; + let copy = copy_rel(); + let cases = [ + ( + "a Gemfile comment", + format!("{gemfile}# gem \"rack\", path: \"{copy}\"\n"), + lock.to_string(), + ), + ( + "a Gemfile path spelled with backslashes in another case", + format!( + "{gemfile}gem \"rack\", path: '{}'\n", + copy.replace('/', "\\").to_ascii_uppercase() + ), + lock.to_string(), + ), + ( + "a lock PATH section of another gem", + gemfile.to_string(), + format!("PATH\n remote: {copy}\n specs:\n rackup (1.0.0)\n\n{lock}"), + ), + ]; + for (what, gemfile, lock) in cases { + let (_tmp, root, entry) = vendored_then_edited(&gemfile, &lock).await; + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{what}: {:?}", outcome.error); + assert!(outcome.drift_skipped(), "{what}: {:?}", outcome.warnings); + assert!( + !outcome.lock_entry_removed(), + "{what}: {:?}", + outcome.warnings + ); + assert!(outcome.kept_artifact, "{what}"); + assert_eq!(read_pair(&root).await, (gemfile, lock), "{what}"); + assert!(root.join(copy_rel()).exists(), "{what}"); + } + } + + /// #2325 with a CHECKSUMS section: `bundle remove` drops the gem's + /// checksum line with its spec, so the checksum record has nothing to + /// restore either. + #[tokio::test] + async fn revert_of_a_dropped_gem_with_checksums_removes_the_copy() { + let (_tmp, root, installed, blobs, record) = + fixture_318(SPIKE_GEMFILE_CHECKSUMS, SPIKE_LOCK_CHECKSUMS_BEFORE).await; + let (result, entry, _w) = + unwrap_done(run_vendor_318(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.unwrap(); + assert!( + entry + .wiring + .iter() + .any(|w| w.kind == LOCK_CHECKSUM_WIRING_KIND), + "the fixture records a checksum line" + ); + let gemfile = "source \"https://rubygems.org\"\n"; + let lock = "GEM\n remote: https://rubygems.org/\n specs:\n\nPLATFORMS\n aarch64-linux\n ruby\n\nDEPENDENCIES\n\nCHECKSUMS\n\nBUNDLED WITH\n 2.7.2\n"; + tokio::fs::write(root.join(GEMFILE), gemfile).await.unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), lock) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(!outcome.drift_skipped(), "{:?}", outcome.warnings); + assert!(outcome.lock_entry_removed(), "{:?}", outcome.warnings); + assert!(!outcome.kept_artifact); + assert_eq!( + read_pair(&root).await, + (gemfile.to_string(), lock.to_string()) + ); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + } + let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; let (result, entry, _w) = From 7ee7eaa8617d6e7110e0883759952fbf97ade15b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:40:14 +0000 Subject: [PATCH 3/5] Clean up a vendored gem the project dropped The gem revert called every record it could not restore drift and kept the copy and the ledger record. After bundle remove, or a move of the gem to another release, nothing can undo that drift, so rollback, remove, vendor --revert and scan --prune kept the entry for good and vendor --check stayed red. When neither the Gemfile nor Gemfile.lock names the entry's copy directory in any spelling, such a record now warns vendor_lock_entry_removed, as the other backends do. Both files stay as the user left them and the copy is removed. A file that still names the copy, or that cannot be read, keeps it as drift. Fixes #2325. Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 7 +- crates/socket-patch-core/src/vendor/gem.rs | 124 ++++++++++++++------- 2 files changed, 87 insertions(+), 44 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc..678db6809 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1867,7 +1867,12 @@ worse, lets a warm cache silently serve unpatched bytes): * `vendor --revert` restores the originals (fragments that no longer match — a user re-resolved — are left alone with a `vendor_lock_entry_drifted` warning; the drift-kept artifact and entry stay, every backend alike — gem included as of v5.0, where a MISSING `Gemfile`/`Gemfile.lock` instead - warns `vendor_lockfile_missing` and still removes the artifact; composer / maven / nuget, whose + warns `vendor_lockfile_missing` and still removes the artifact, and where a fragment that cannot + be restored once neither `Gemfile` nor `Gemfile.lock` names the `.socket/vendor/gem/` dir + in any spelling — the gem was dropped with `bundle remove`, or moved to another release — is not + drift: it warns `vendor_lock_entry_removed`, both files stay as the user left them, and the + artifact and entry are removed, so `vendor --revert` / `rollback` / `remove` / `scan --prune` + clean up after it (a file of the two that cannot be read keeps them, as drift); composer / maven / nuget, whose whole-file wiring cannot tell a converged fragment from a drifted one, keep the artifact exactly while the live `composer.lock` / `pom.xml` / `nuget.config` still names its `.socket/vendor//` dir — a file that no longer references it is warned about and the diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 494de71c4..ce95dc1fb 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -114,6 +114,7 @@ use crate::patch::path_safety::is_safe_single_segment; use crate::patch::redirect::gem_line_tail_blocks_edit; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; use crate::utils::line_endings::{self, to_lf, LineEndings}; +use crate::utils::path_spelling::PathNeedle; use crate::utils::purl::{build_gem_purl, parse_gem_purl, purl_qualifier}; use super::common::{ @@ -2140,7 +2141,10 @@ async fn materialise_patched_copy( /// A fragment that no longer looks like what vendor wrote — a hand edit, a /// `bundle update`, a newer vendor run — gets a `vendor_lock_entry_drifted` /// warning, and then neither file is written: the Gemfile and the lock are -/// reverted together or not at all (#988). +/// reverted together or not at all (#988). When neither file names the copy +/// dir any more (`bundle remove`, a move to another release), such a +/// fragment warns `vendor_lock_entry_removed` instead: neither file is +/// written then either, and the copy is removed (#2325). pub async fn revert_gem(entry: &VendorEntry, project_root: &Path, dry_run: bool) -> RevertOutcome { revert_gem_opts(entry, project_root, RevertOpts::new(dry_run)).await } @@ -2219,7 +2223,20 @@ pub async fn revert_gem_opts( version: version.into_owned(), }; let mut files = RevertFiles::new(project_root); + // Whether either file still names the entry's copy dir, in any spelling + // and any case, read before any record is reverted so that only the + // user's own edits count. A file that cannot be read may name it. + let needle = PathNeedle::keep(&uuid_dir_rel); + let mut referenced = false; + for name in [GEMFILE_LOCK, GEMFILE] { + referenced |= match files.text(name).await { + Ok(Some(file)) => needle.found_in(file.text()), + Ok(None) => false, + Err(_) => true, + }; + } let mut drifted = false; + let mut removed = false; for w in entry.wiring.iter().rev() { let restored = match w.kind.as_str() { LOCK_WIRING_KIND => revert_lock_record(&mut files, w, &own).await, @@ -2236,6 +2253,26 @@ pub async fn revert_gem_opts( let key = w.key_label(); match restored { Ok(RecordRevert::Done) => {} + // REMOVED, not drift (#2325): the user dropped the gem (`bundle + // remove`) or moved it to another release, and bundler took + // every fragment that routed through the copy out with it. With + // neither file naming the copy dir any more there is nothing to + // restore and nothing of the user's to protect, so the revert + // converges: the pair is theirs and stays as found, and the copy + // goes. + Ok(RecordRevert::Drifted) if !referenced => { + removed = true; + warnings.push(VendorWarning::new( + super::LOCK_ENTRY_REMOVED_CODE, + format!( + "{} holds nothing vendor wrote for {key} any more, and neither \ + {GEMFILE} nor {GEMFILE_LOCK} names {uuid_dir_rel} (the gem was \ + removed from the project or moved to another release); nothing \ + to restore", + w.file + ), + )); + } Ok(RecordRevert::Drifted) => { drifted = true; warnings.push(VendorWarning::new( @@ -2270,10 +2307,11 @@ pub async fn revert_gem_opts( warnings, error: None, }; - // All-or-nothing: a drifted record leaves every file as found. A record - // of a kind this build cannot read still lets the known ones restore - // (forward compatibility); its warning keeps the artifact below. - if !drifted && !opts.dry_run { + // All-or-nothing: a drifted record, or one with nothing left to + // restore, leaves every file as found. A record of a kind this build + // cannot read still lets the known ones restore (forward + // compatibility); its warning keeps the artifact below. + if !drifted && !removed && !opts.dry_run { if let Err(e) = files.write_changed().await { return RevertOutcome { success: false, @@ -6339,44 +6377,6 @@ mod tests { } } - /// The user already put the gem back on the registry by hand, with a - /// different constraint than the original: the Gemfile no longer routes - /// through the copy, so that record has converged and the lock is - /// restored to match it instead of being kept on the PATH section. - #[tokio::test] - async fn revert_hand_restored_gemfile_converges_and_restores_lock() { - let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; - let (result, entry, _w) = - unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); - assert!(result.success); - let entry = entry.unwrap(); - let hand = GEMFILE_DIRECT.replace("\"~> 3.1\"", "\"~> 3.2\" # restored"); - tokio::fs::write(root.join(GEMFILE), &hand).await.unwrap(); - - let outcome = revert_gem(&entry, &root, false).await; - assert!(outcome.success, "{:?}", outcome.error); - assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); - assert!(!outcome.kept_artifact); - assert_eq!( - tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), - hand - ); - assert_eq!( - tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) - .await - .unwrap(), - LOCK_DIRECT - ); - assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); - } - - /// A `bundle update` regenerated both files back to their pre-vendor - /// registry form: that is CONVERGENCE (the reverted state is already on - /// disk), not drift — revert stays silent (LIVENESS CONTRACT), leaves the - /// files alone and still removes the artifact dir, so the entry can never - /// wedge in the ledger forever. - #[tokio::test] - async fn test_revert_converged_files_are_silent_and_still_remove() { /// What `bundle remove rack` and a move to rack 3.2.7 leave of the /// [`GEMFILE_DIRECT`] / [`LOCK_DIRECT`] pair: `(what, Gemfile, lock)`. fn dropped_gem_pairs() -> [(&'static str, &'static str, &'static str); 2] { @@ -6566,6 +6566,44 @@ mod tests { assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); } + /// The user already put the gem back on the registry by hand, with a + /// different constraint than the original: the Gemfile no longer routes + /// through the copy, so that record has converged and the lock is + /// restored to match it instead of being kept on the PATH section. + #[tokio::test] + async fn revert_hand_restored_gemfile_converges_and_restores_lock() { + let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let (result, entry, _w) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(result.success); + let entry = entry.unwrap(); + let hand = GEMFILE_DIRECT.replace("\"~> 3.1\"", "\"~> 3.2\" # restored"); + tokio::fs::write(root.join(GEMFILE), &hand).await.unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert!(!outcome.kept_artifact); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE)).await.unwrap(), + hand + ); + assert_eq!( + tokio::fs::read_to_string(root.join(GEMFILE_LOCK)) + .await + .unwrap(), + LOCK_DIRECT + ); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + } + + /// A `bundle update` regenerated both files back to their pre-vendor + /// registry form: that is CONVERGENCE (the reverted state is already on + /// disk), not drift — revert stays silent (LIVENESS CONTRACT), leaves the + /// files alone and still removes the artifact dir, so the entry can never + /// wedge in the ledger forever. + #[tokio::test] + async fn test_revert_converged_files_are_silent_and_still_remove() { let (_tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; let (result, entry, _w) = From 13b525ef58acf6de4c7e6c3b89e2213dd9eb9e75 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:43:52 +0000 Subject: [PATCH 4/5] Hold the dropped-gem audit to what each undo leaves rollback and vendor --revert keep the manifest's patch, so the audit that follows reports it as not vendored. Only remove leaves nothing for the audit to report. Refs #2325. Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_vendor_gem_build.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 037f746b4..f789f0a7b 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2285,8 +2285,8 @@ fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { ); } let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); - assert_eq!( - code, 1, + assert!( + code == 1 && format!("{stdout}{stderr}").contains("wiring missing"), "{what}: vendor --check reports the dead entry.\n{stdout}\n{stderr}" ); @@ -2331,11 +2331,18 @@ fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { "{what}: a frozen install passes after the clean-up:\n{}", String::from_utf8_lossy(&install.stderr) ); + // `remove` drops the manifest's patch too, so the audit has nothing + // left to hold the project to. The other two keep that patch, which + // the audit then reports as not vendored: no longer a dead entry. let (code, stdout, stderr) = run_socket(&proj, &["vendor", "--check", "--cwd", cwd]); - assert_eq!( - code, 0, - "{what}: vendor --check is green again.\n{stdout}\n{stderr}" + let audit = format!("{stdout}{stderr}"); + assert!( + !audit.contains("wiring missing") && !audit.contains(UUID), + "{what}: vendor --check no longer reports the dead entry:\n{audit}" ); + if undo[0] == "remove" { + assert_eq!(code, 0, "{what}: vendor --check is green again:\n{audit}"); + } } } From 1f3be3610c9e403bd0395a64b244a50fb70a6cc4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 17:58:48 +0000 Subject: [PATCH 5/5] Keep a gem entry wired under another patch uuid A Gemfile and lock that route the gem through a vendored copy of another patch uuid (an interrupted re-vendor, a merge that kept an older ledger) no longer read as a dropped gem: the project is still vendored and the entry may hold the only pre-vendor originals, so the revert keeps it as drift. The removed warning no longer states one cause for every case, the contract says an unreadable file fails the revert, and the end-to-end test re-locks after bundle remove, which Bundler 2.1 and older leave to the next install. Refs #2325. Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 11 +- .../tests/e2e_vendor_gem_build.rs | 12 +- crates/socket-patch-core/src/vendor/gem.rs | 104 ++++++++++++++++-- 3 files changed, 112 insertions(+), 15 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 678db6809..b30418b7d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1868,11 +1868,12 @@ worse, lets a warm cache silently serve unpatched bytes): are left alone with a `vendor_lock_entry_drifted` warning; the drift-kept artifact and entry stay, every backend alike — gem included as of v5.0, where a MISSING `Gemfile`/`Gemfile.lock` instead warns `vendor_lockfile_missing` and still removes the artifact, and where a fragment that cannot - be restored once neither `Gemfile` nor `Gemfile.lock` names the `.socket/vendor/gem/` dir - in any spelling — the gem was dropped with `bundle remove`, or moved to another release — is not - drift: it warns `vendor_lock_entry_removed`, both files stay as the user left them, and the - artifact and entry are removed, so `vendor --revert` / `rollback` / `remove` / `scan --prune` - clean up after it (a file of the two that cannot be read keeps them, as drift); composer / maven / nuget, whose + be restored once neither `Gemfile` nor `Gemfile.lock` names the `.socket/vendor/gem/` dir, + or a vendored copy of the gem under another patch uuid, in any spelling — the gem was dropped + with `bundle remove`, or moved to another release — is not drift: it warns + `vendor_lock_entry_removed`, both files stay as the user left them, and the artifact and entry + are removed, so `vendor --revert` / `rollback` / `remove` / `scan --prune` clean up after it (a + file of the two that cannot be read fails the revert, which keeps both); composer / maven / nuget, whose whole-file wiring cannot tell a converged fragment from a drifted one, keep the artifact exactly while the live `composer.lock` / `pom.xml` / `nuget.config` still names its `.socket/vendor//` dir — a file that no longer references it is warned about and the diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index f789f0a7b..ee128ceaa 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2259,7 +2259,17 @@ fn gem_vendor_dropped_gem_is_cleaned_up_by_every_undo_command() { // The user's edit, with real bundler. let edit = match how { - "remove" => bundle(&proj, &["remove", DEP], false), + // Bundler <= 2.1 edits only the Gemfile on `remove`; the + // install that follows re-locks, as it does for such a user. + "remove" => { + let remove = bundle(&proj, &["remove", DEP], false); + assert!( + remove.status.success(), + "{what}: `bundle remove` (test premise):\n{}", + String::from_utf8_lossy(&remove.stderr) + ); + bundle(&proj, &["install"], false) + } _ => { let version = purl.rsplit('@').next().unwrap(); let other = if version == "3.1.8" { "3.1.9" } else { "3.1.8" }; diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index ce95dc1fb..1209e7156 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -114,7 +114,7 @@ use crate::patch::path_safety::is_safe_single_segment; use crate::patch::redirect::gem_line_tail_blocks_edit; use crate::utils::fs::{atomic_write_bytes_preserving_mode, read_regular_to_string}; use crate::utils::line_endings::{self, to_lf, LineEndings}; -use crate::utils::path_spelling::PathNeedle; +use crate::utils::path_spelling::{canonical_path_text, PathNeedle}; use crate::utils::purl::{build_gem_purl, parse_gem_purl, purl_qualifier}; use super::common::{ @@ -2223,14 +2223,20 @@ pub async fn revert_gem_opts( version: version.into_owned(), }; let mut files = RevertFiles::new(project_root); - // Whether either file still names the entry's copy dir, in any spelling - // and any case, read before any record is reverted so that only the - // user's own edits count. A file that cannot be read may name it. + // Whether either file still names the entry's copy dir, or a copy of + // this gem under another patch uuid (a re-vendor that was interrupted, + // a merge that kept an older ledger: this entry may hold the only + // pre-vendor originals of that wiring), in any spelling and any case. + // Read before any record is reverted, so that only the user's own edits + // count. A file that cannot be read may name one. let needle = PathNeedle::keep(&uuid_dir_rel); let mut referenced = false; for name in [GEMFILE_LOCK, GEMFILE] { referenced |= match files.text(name).await { - Ok(Some(file)) => needle.found_in(file.text()), + Ok(Some(file)) => { + needle.found_in(file.text()) + || names_a_vendored_copy_of(file.text(), &own.name, &own.version) + } Ok(None) => false, Err(_) => true, }; @@ -2265,10 +2271,10 @@ pub async fn revert_gem_opts( warnings.push(VendorWarning::new( super::LOCK_ENTRY_REMOVED_CODE, format!( - "{} holds nothing vendor wrote for {key} any more, and neither \ - {GEMFILE} nor {GEMFILE_LOCK} names {uuid_dir_rel} (the gem was \ - removed from the project or moved to another release); nothing \ - to restore", + "{} no longer carries what vendor wrote for {key}, and neither \ + {GEMFILE} nor {GEMFILE_LOCK} names a vendored copy of the gem \ + any more (it was removed from the project, moved to another \ + release or pointed at another source); nothing to restore", w.file ), )); @@ -2332,6 +2338,27 @@ pub async fn revert_gem_opts( .await } +/// Whether a line of `text` (a Gemfile or a Gemfile.lock) names a +/// socket-patch copy of the gem `name` at `version` under any patch uuid: +/// a path below `.socket/vendor/gem/` with a `-` segment +/// (the copy dir, or a platform copy `--`), in any +/// spelling and any ASCII case. Errs towards `true`: the caller keeps an +/// artifact and a ledger entry while it holds. +fn names_a_vendored_copy_of(text: &str, name: &str, version: &str) -> bool { + let vendor_dir = PathNeedle::keep(".socket/vendor/gem"); + let segment = format!("/{name}-{version}").to_ascii_lowercase(); + text.split('\n') + .filter(|line| vendor_dir.found_in(line)) + .any(|line| { + let line = canonical_path_text(line).to_ascii_lowercase(); + line.match_indices(&segment).any(|(at, _)| { + // `rack-3.2.6` is not `rack-3.2.60` or `rack-3.2.6.1`. + !line[at + segment.len()..] + .starts_with(|c: char| c.is_ascii_alphanumeric() || c == '.') + }) + }) +} + // ── Gemfile editing ────────────────────────────────────────────────────────── /// The planned Gemfile edit. @@ -6529,6 +6556,65 @@ mod tests { } } + /// The files route the gem through a copy under ANOTHER patch uuid (a + /// re-vendor that was interrupted, a merge that kept an older ledger): + /// the project is still vendored and this entry may hold the only + /// pre-vendor originals, so it is drift, not a dropped gem. A copy of + /// another gem, or of another release, under that uuid is no such + /// reference. + #[tokio::test] + async fn revert_keeps_an_entry_whose_gem_is_wired_to_another_uuid() { + const OTHER: &str = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + let (tmp, root, installed, blobs, record) = fixture(GEMFILE_DIRECT, LOCK_DIRECT).await; + let (result, entry, _w) = + unwrap_done(run_vendor(&root, &blobs, &installed, &record, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.unwrap(); + let (gemfile, lock) = read_pair(&root).await; + let (gemfile, lock) = (gemfile.replace(UUID, OTHER), lock.replace(UUID, OTHER)); + assert!(gemfile.contains(OTHER) && lock.contains(OTHER)); + tokio::fs::write(root.join(GEMFILE), &gemfile) + .await + .unwrap(); + tokio::fs::write(root.join(GEMFILE_LOCK), &lock) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.drift_skipped(), "{:?}", outcome.warnings); + assert!(!outcome.lock_entry_removed(), "{:?}", outcome.warnings); + assert!(outcome.kept_artifact); + assert_eq!(read_pair(&root).await, (gemfile, lock)); + assert!(root.join(copy_rel()).exists()); + drop(tmp); + + let other = format!(".socket/vendor/gem/{OTHER}"); + for (line, names) in [ + (format!(" remote: {other}/rack-3.2.6"), true), + (format!("gem 'rack', path: '{other}/rack-3.2.6/'"), true), + (format!(" remote: {other}/rack-3.2.6-x86_64-linux"), true), + ( + format!( + "gem 'rack', path: '{}\\RACK-3.2.6'", + other.replace('/', "\\") + ), + true, + ), + (format!(" remote: {other}/rack-3.2.60"), false), + (format!(" remote: {other}/rack-3.2.6.1"), false), + (format!(" remote: {other}/rack-test-3.2.6"), false), + (format!(" remote: {other}/rackup-3.2.6"), false), + (" remote: vendor/forks/rack-3.2.6".to_string(), false), + ] { + assert_eq!( + names_a_vendored_copy_of(&line, "rack", "3.2.6"), + names, + "{line}" + ); + } + } + /// #2325 with a CHECKSUMS section: `bundle remove` drops the gem's /// checksum line with its spec, so the checksum record has nothing to /// restore either.