From a8ab696aede6c590d27d8bb630be2edad3cd0227 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:33:56 -0500 Subject: [PATCH 1/5] Read patch files committed to `.socket/blob/` when `.socket/blobs/` lacks them A project whose patch files were committed under `.socket/blob/` (an older commit layout, as written by an integration) has every byte of its patch in the repository, in a folder the CLI never read. Each `apply` downloaded the files again, `apply --offline` failed with "no local source", and once the patch service stopped serving a superseded patch the run failed with "Blob not found on server" and exit 1. The apply source stager now looks for a blob `.socket/blobs/` lacks in `.socket/blob/` before it counts it as missing. A file found there is read into memory and used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. The verified bytes are handed to the pipeline as in-memory sources, so `apply` still writes nothing under `.socket/`, needs no API client when the folder covers the run, and `get` / `scan`'s nested apply get the same behaviour. A run that read such files says so once (`Warning:` on stderr, muted by `--silent`; run warning `legacy_blob_dir` in `--json`) and points at `socket-patch repair`, which now copies the blobs the manifest references from `.socket/blob/` into `.socket/blobs/` before any download (with `--offline` too; `--dry-run` reports the copy). The legacy folder is never modified, and no sweep reads it. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 1 + crates/socket-patch-cli/src/commands/apply.rs | 5 + .../src/commands/fetch_stage.rs | 194 ++++++++++++++- .../socket-patch-cli/src/commands/repair.rs | 55 ++++- .../tests/apply/legacy_blob_dir.rs | 226 ++++++++++++++++++ crates/socket-patch-cli/tests/apply/main.rs | 1 + .../socket-patch-core/src/api/blob_fetcher.rs | 203 ++++++++++++++++ 7 files changed, 676 insertions(+), 9 deletions(-) create mode 100644 crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fdb6df3ad8..2ece0fc98a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2799,6 +2799,7 @@ command's integration tests check its output. | `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:/` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. | | `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. | | `offline_missing_sources` / `sources_download_failed` | apply run-level `warnings[]` | apply (additive): the patch sources were unavailable — `--offline` with no local source, or the download left a patch with no source — so nothing was attempted. The envelope keeps its pinned shape (`partialFailure`, empty `events[]`, zero summary, no top-level `error`); the warning is its machine-readable reason (the human path prints the staging `Error:` line on stderr instead, even under `--silent`). | +| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. `apply` writes nothing under `.socket/`. The detail gives the count and the remedy (`socket-patch repair`); human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references that `.socket/blobs/` lacks (or holds corrupt) were copied from `.socket/blob/` before any download, with `--offline` too; `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. | | `paid_required` | `skipped` + status=`paidRequired` | get: every patch found needs a paid plan and the caller's token isn't entitled (exit 0); one `skipped` event per patch, `details.tier`. `get ` on the public proxy reports it both for a `tier: "paid"` view and for the proxy's 403 refusal, whose event then carries only `uuid` (no `purl`: the proxy never named it). `scan` never reports it: it leaves paid patches out of the selection and counts them in `paidPatches` / `canAccessPaidPatches`. | | `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. | | `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (` of packages could not be checked for patches (…): `); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. | diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 653ae7abc0..4b6f319241 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -3766,6 +3766,11 @@ async fn apply_patches_inner( .map(|d| d.stores.as_slice()) .unwrap_or(&[]); let mut run_warnings: Vec = ledger_warning.into_iter().collect(); + // Patch files read from the legacy `.socket/blob` folder: the run is + // whole, and `repair` moves them where every other command looks. + if let Some((code, detail)) = staged.legacy_blob_dir_warning() { + run_warnings.push(RunWarning::new(code, detail)); + } if let Some(value) = gem_discovery .as_ref() .and_then(|d| d.skipped_config_path.as_deref()) diff --git a/crates/socket-patch-cli/src/commands/fetch_stage.rs b/crates/socket-patch-cli/src/commands/fetch_stage.rs index 115ca21537..7bc729e694 100644 --- a/crates/socket-patch-cli/src/commands/fetch_stage.rs +++ b/crates/socket-patch-cli/src/commands/fetch_stage.rs @@ -4,12 +4,20 @@ //! persistent `.socket/blobs` cache is only ever read; downloads are //! discarded when the overlay drops (filling the cache is `repair`'s job, //! so `apply` leaves `.socket/` as it found it). - -use std::collections::HashSet; +//! +//! A blob `.socket/blobs` lacks is looked for in `.socket/blob` before it +//! is downloaded: an older commit layout kept a project's patch files +//! there, and such a project has them in its repository but nowhere the +//! cache looks. Each is read into memory, verified against its name, and +//! handed to the pipeline as an in-memory source, so nothing is written +//! and a run that finds them all needs no network. + +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use socket_patch_core::api::blob_fetcher::{ - fetch_missing_blobs, get_missing_blobs, FetchMissingBlobsResult, + fetch_blobs_by_hash, get_missing_blobs, read_legacy_blob, FetchMissingBlobsResult, + LEGACY_BLOBS_DIR, }; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::patch::apply::PatchSources; @@ -22,6 +30,9 @@ use crate::ui::{plural, StatusLine}; /// `TempDir` alive — sources become invalid when this is dropped. pub(crate) struct StagedSources { blobs: PathBuf, + /// Blobs read from the legacy `.socket/blob` folder ([`legacy_blobs`]), + /// by hash: verified bytes the pipeline reads before `blobs`. + legacy: HashMap>, _stage: Option, } @@ -30,9 +41,50 @@ impl StagedSources { pub(crate) fn as_patch_sources(&self) -> PatchSources<'_> { PatchSources { blobs_path: &self.blobs, - mem_blobs: None, + mem_blobs: (!self.legacy.is_empty()).then_some(&self.legacy), } } + + /// The advisory for a run that read patch files from the legacy + /// `.socket/blob` folder, `None` when it read none. + pub(crate) fn legacy_blob_dir_warning(&self) -> Option<(&'static str, String)> { + let n = self.legacy.len(); + (n > 0).then(|| { + ( + LEGACY_BLOB_DIR, + format!( + "read {} from `.socket/{LEGACY_BLOBS_DIR}/`; socket-patch keeps patch \ + files in `.socket/blobs/`. Run `socket-patch repair` to copy them there, \ + then commit `.socket/blobs/`", + plural(n, "patch file", "patch files") + ), + ) + }) + } +} + +/// Run-warning code: the run read patch files from the legacy +/// `.socket/blob` folder. +pub(crate) const LEGACY_BLOB_DIR: &str = "legacy_blob_dir"; + +/// The blobs of `missing` (hashes `.socket/blobs` lacks) that the legacy +/// folder `socket_dir/blob` holds, verified ([`read_legacy_blob`]). Empty, +/// after one `lstat`, for a project with no such folder. +async fn legacy_blobs(socket_dir: &Path, missing: &HashSet) -> HashMap> { + let legacy_dir = socket_dir.join(LEGACY_BLOBS_DIR); + let mut found = HashMap::new(); + if !tokio::fs::symlink_metadata(&legacy_dir) + .await + .is_ok_and(|meta| meta.is_dir()) + { + return found; + } + for hash in missing { + if let Some(bytes) = read_legacy_blob(&legacy_dir, hash).await { + found.insert(hash.clone(), bytes); + } + } + found } /// The staging outcome. @@ -159,7 +211,11 @@ pub(crate) async fn stage_patch_sources( let quiet = common.silent || common.json; let socket_blobs_path = socket_dir.join("blobs"); - let missing_blobs = get_missing_blobs(manifest, &socket_blobs_path).await; + let mut missing_blobs = get_missing_blobs(manifest, &socket_blobs_path).await; + // What the cache lacks and the legacy folder holds is not missing: it + // is neither an offline failure nor a download. + let legacy = legacy_blobs(socket_dir, &missing_blobs).await; + missing_blobs.retain(|hash| !legacy.contains_key(hash)); if common.offline { let no_source_purls = patches_without_source(manifest, &missing_blobs); @@ -186,6 +242,7 @@ pub(crate) async fn stage_patch_sources( if common.offline || missing_blobs.is_empty() { return Ok(StageOutcome::Ready(StagedSources { blobs: socket_blobs_path, + legacy, _stage: None, })); } @@ -207,6 +264,7 @@ pub(crate) async fn stage_patch_sources( .map_err(|e| e.to_string())?; let staged = StagedSources { blobs: stage.path().join("blobs"), + legacy, _stage: Some(stage), }; tokio::fs::create_dir_all(&staged.blobs) @@ -220,7 +278,9 @@ pub(crate) async fn stage_patch_sources( let client = common.api_client(client).await; let mut status = StatusLine::stderr(common.json, common.silent); status.set("Downloading missing patch artifacts..."); - let fetch_result = fetch_missing_blobs(manifest, &staged.blobs, client, None).await; + // By hash, not by manifest: the legacy folder's blobs are absent from + // the overlay too, and are not downloads. + let fetch_result = fetch_blobs_by_hash(&missing_blobs, &staged.blobs, client, None).await; status.finish(); if !quiet { for line in format_fetch_summary(&fetch_result) { @@ -232,7 +292,8 @@ pub(crate) async fn stage_patch_sources( // with no usable source at the staged path — the same coverage rule as // the offline gate. if fetch_result.failed > 0 { - let missing_blobs = get_missing_blobs(manifest, &staged.blobs).await; + let mut missing_blobs = get_missing_blobs(manifest, &staged.blobs).await; + missing_blobs.retain(|hash| !staged.legacy.contains_key(hash)); if !patches_without_source(manifest, &missing_blobs).is_empty() { // An error, so it prints even under --silent, with the per-blob // reasons the quiet summary above held back. @@ -358,6 +419,125 @@ mod tests { ); } + /// A manifest with one patch of one file whose patched bytes are + /// `after`, and that blob's hash. + fn manifest_for(after: &[u8]) -> (PatchManifest, String) { + let hash = socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes(after); + let mut manifest = manifest_with_one_patch(); + for record in manifest.patches.values_mut() { + for file in record.files.values_mut() { + file.after_hash = hash.clone(); + } + } + (manifest, hash) + } + + /// A blob `.socket/blobs` lacks and `.socket/blob` holds is a source: + /// offline or online, the run is Ready with the bytes in memory, no + /// overlay, no API client, and nothing written under `.socket/`. + #[tokio::test] + async fn stage_reads_a_missing_blob_from_the_legacy_folder() { + let tmp = tempfile::tempdir().unwrap(); + let socket_dir = tmp.path().join(".socket"); + let legacy = socket_dir.join("blob"); + std::fs::create_dir_all(&legacy).unwrap(); + let (manifest, hash) = manifest_for(b"patched"); + std::fs::write(legacy.join(&hash), b"patched").unwrap(); + + for offline in [true, false] { + let args = GlobalArgs { + offline, + ..offline_args() + }; + let client = RunApiClient::new(); + let outcome = stage_patch_sources(&args, &manifest, &socket_dir, &client) + .await + .expect("no hard failure"); + let StageOutcome::Ready(staged) = outcome else { + panic!("a legacy blob is a source (offline: {offline})"); + }; + assert!(staged._stage.is_none(), "nothing to download, no overlay"); + assert!(!client.initialized(), "nothing to download, no client"); + let sources = staged.as_patch_sources(); + assert_eq!( + sources + .mem_blobs + .and_then(|m| m.get(&hash)) + .map(Vec::as_slice), + Some(&b"patched"[..]) + ); + let (code, detail) = staged.legacy_blob_dir_warning().expect("advisory"); + assert_eq!(code, "legacy_blob_dir"); + assert!( + detail.starts_with("read 1 patch file from `.socket/blob/`"), + "{detail}" + ); + assert!(!socket_dir.join("blobs").exists(), "apply writes no cache"); + } + } + + /// A legacy file that does not hash to its name is no source: offline + /// the run is Unavailable, as without the folder. And a run with every + /// blob cached never reads the folder (no advisory). + #[tokio::test] + async fn stage_ignores_a_corrupt_legacy_blob_and_an_unneeded_folder() { + let tmp = tempfile::tempdir().unwrap(); + let socket_dir = tmp.path().join(".socket"); + let legacy = socket_dir.join("blob"); + std::fs::create_dir_all(&legacy).unwrap(); + let (manifest, hash) = manifest_for(b"patched"); + std::fs::write(legacy.join(&hash), b"patched\r\n").unwrap(); + + let client = RunApiClient::new(); + let outcome = stage_patch_sources(&offline_args(), &manifest, &socket_dir, &client) + .await + .expect("no hard failure"); + assert!(matches!(outcome, StageOutcome::Unavailable)); + + std::fs::write(legacy.join(&hash), b"patched").unwrap(); + std::fs::create_dir_all(socket_dir.join("blobs")).unwrap(); + std::fs::write(socket_dir.join("blobs").join(&hash), b"patched").unwrap(); + let outcome = stage_patch_sources(&offline_args(), &manifest, &socket_dir, &client) + .await + .expect("no hard failure"); + let StageOutcome::Ready(staged) = outcome else { + panic!("cached"); + }; + assert!(staged.as_patch_sources().mem_blobs.is_none()); + assert!(staged.legacy_blob_dir_warning().is_none()); + } + + /// The legacy folder covers one of a patch's two files: only the other + /// is asked of the server, and when that fails the patch still has no + /// whole source. + #[tokio::test] + async fn stage_downloads_only_what_the_legacy_folder_lacks() { + let tmp = tempfile::tempdir().unwrap(); + let socket_dir = tmp.path().join(".socket"); + let legacy = socket_dir.join("blob"); + std::fs::create_dir_all(&legacy).unwrap(); + let (mut manifest, hash) = manifest_for(b"patched"); + std::fs::write(legacy.join(&hash), b"patched").unwrap(); + for record in manifest.patches.values_mut() { + record.files.insert( + "other.js".to_string(), + PatchFileInfo { + before_hash: "b".repeat(64), + after_hash: "c".repeat(64), + mode: None, + }, + ); + } + + let args = dead_endpoint_args(); + let client = RunApiClient::new(); + let outcome = stage_patch_sources(&args, &manifest, &socket_dir, &client) + .await + .expect("no hard failure"); + assert!(matches!(outcome, StageOutcome::Unavailable)); + assert!(client.initialized(), "the uncovered blob is a download"); + } + /// GlobalArgs wired to a guaranteed-unreachable API endpoint: explicit /// token + org overrides keep client construction network-free, and the /// URL points at a port that was just bound and released, so every fetch diff --git a/crates/socket-patch-cli/src/commands/repair.rs b/crates/socket-patch-cli/src/commands/repair.rs index 25871f02c9..047fbbc7ce 100644 --- a/crates/socket-patch-cli/src/commands/repair.rs +++ b/crates/socket-patch-cli/src/commands/repair.rs @@ -1,7 +1,8 @@ use clap::Args; use socket_patch_core::api::blob_fetcher::{ fetch_blobs_replacing, format_fetch_failures, format_fetch_successes, get_corrupt_blobs, - get_missing_blobs, ArtifactNoun, BLOB, DIFF_ARCHIVE, PACKAGE_ARCHIVE, + get_missing_blobs, legacy_blobs_available, restore_from_legacy_dir, ArtifactNoun, BLOB, + DIFF_ARCHIVE, LEGACY_BLOBS_DIR, PACKAGE_ARCHIVE, }; use socket_patch_core::api::client::{get_api_client_with_overrides, ApiClient}; use socket_patch_core::manifest::cleanup_blobs::{ @@ -442,6 +443,16 @@ fn format_nothing_missing( } } +/// The line for blobs copied (or, in a dry run, that would be copied) from +/// the legacy `.socket/blob/` folder into `.socket/blobs/`. +fn format_legacy_copy(count: usize, dry_run: bool) -> String { + let verb = if dry_run { "Would copy" } else { "Copied" }; + format!( + "{verb} {} from `.socket/{LEGACY_BLOBS_DIR}/` to `.socket/blobs/`.", + BLOB.count(count) + ) +} + /// Why a referenced blob has to be downloaded. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum BlobFault { @@ -739,11 +750,51 @@ async fn repair_inner( ) } }; + // Step 0.5: blobs an older commit layout left under `.socket/blob/`. + // What `.socket/blobs/` lacks (or holds corrupt) and that folder holds + // intact is copied over, not downloaded: it works offline, and for a + // patch the server no longer serves. `apply` reads the folder as a + // fallback on every run; this is what makes that one-off. The folder + // itself is left as it is (it is the user's, and committed). + let legacy_dir = socket_dir.join(LEGACY_BLOBS_DIR); + let wanted: Vec = missing_artifacts + .iter() + .chain(&corrupt_artifacts) + .cloned() + .collect(); + let from_legacy = if args.common.dry_run { + legacy_blobs_available(&wanted, &legacy_dir).await + } else { + restore_from_legacy_dir(&wanted, &legacy_dir, &blobs_path).await + }; + let left = |ids: Vec| -> Vec { + ids.into_iter() + .filter(|id| !from_legacy.contains(id)) + .collect() + }; + let (missing_artifacts, corrupt_artifacts) = (left(missing_artifacts), left(corrupt_artifacts)); + if !from_legacy.is_empty() { + if !quiet { + println!( + "{}", + format_legacy_copy(from_legacy.len(), args.common.dry_run) + ); + } + env.warn( + crate::commands::fetch_stage::LEGACY_BLOB_DIR, + format!( + "{}; commit `.socket/blobs/`, after which `.socket/{LEGACY_BLOBS_DIR}/` can be \ + deleted", + format_legacy_copy(from_legacy.len(), args.common.dry_run).trim_end_matches('.') + ), + ); + } let nothing_to_fetch = missing_artifacts.is_empty() && corrupt_artifacts.is_empty(); // Whether stdout already carries a line, so the blank separators // between sections never open the output (the offline errors go to // stderr). - let mut stdout_started = !args.common.offline || nothing_to_fetch; + let mut stdout_started = + !args.common.offline || nothing_to_fetch || (!from_legacy.is_empty() && !quiet); let primary = if nothing_to_fetch { if !quiet { println!("{}", format_nothing_missing(manifest.as_ref())); diff --git a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs new file mode 100644 index 0000000000..57ed0c63aa --- /dev/null +++ b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs @@ -0,0 +1,226 @@ +//! Patch files committed under `.socket/blob/` (an older commit layout) +//! are used when `.socket/blobs/` lacks them. +//! +//! Such a project has every byte of its patch in the repository, but in a +//! folder the cache never looked in: each `apply` downloaded the files +//! again, and failed once the server no longer served that patch. The +//! fallback reads them where they are: `apply` works offline, writes +//! nothing under `.socket/`, and says where the files should live. +//! `repair` copies them into `.socket/blobs/`. + +use std::path::Path; + +use crate::apply_fixture::{ + index_js_patches, install_npm_pkg, run_apply, write_manifest, write_root_package_json, + MM_AFTER, MM_BEFORE, +}; +use crate::common::envelope::{parse_json_envelope, warning_codes}; +use crate::common::{git_sha256, run_with_env}; + +const PURL: &str = "pkg:npm/widget@1.0.0"; + +/// A project with `widget@1.0.0` installed unpatched and one manifest +/// patch for it, whose patched file is nowhere under `.socket/blobs/`. +/// Returns the installed `index.js`. +fn project(root: &Path) -> std::path::PathBuf { + write_root_package_json(root); + write_manifest( + root, + index_js_patches(&[PURL], "aaaaaaaa", MM_BEFORE, MM_AFTER), + ); + install_npm_pkg(root, "widget", "1.0.0", Some(MM_BEFORE)) +} + +/// Put `content` at `.socket/blob/`: where the older layout kept it. +fn write_legacy_blob(root: &Path, hash: &str, content: &[u8]) -> std::path::PathBuf { + let dir = root.join(".socket").join("blob"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(hash); + std::fs::write(&path, content).unwrap(); + path +} + +fn entries(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .map(|rd| { + rd.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect() + }) + .unwrap_or_default(); + names.sort(); + names +} + +/// The patch applies with no network, from the legacy folder alone, and +/// `apply` leaves `.socket/` as it found it. +#[test] +fn apply_offline_uses_blobs_committed_to_the_legacy_folder() { + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + let legacy = write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), MM_AFTER); + let socket_before = entries(&tmp.path().join(".socket")); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_AFTER); + assert!( + stderr.contains( + "Warning: read 1 patch file from `.socket/blob/`; socket-patch keeps patch files \ + in `.socket/blobs/`. Run `socket-patch repair` to copy them there" + ), + "the run says where the files belong: {stderr}" + ); + // Read-only against `.socket/`: nothing copied, moved or left behind. + assert_eq!(entries(&tmp.path().join(".socket")), socket_before); + assert!(entries(&tmp.path().join(".socket").join("blobs")).is_empty()); + assert_eq!(std::fs::read(&legacy).unwrap(), MM_AFTER); + + // A second run finds the package patched and still needs no network. + let (code, _, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "{stderr}"); +} + +/// Online, a run that finds every file in the legacy folder downloads +/// nothing: it succeeds against an endpoint that refuses every request. +#[test] +fn apply_online_does_not_download_what_the_legacy_folder_holds() { + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), MM_AFTER); + + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let url = format!("http://127.0.0.1:{port}"); + let token = format!("sktsec_{}_api", "x".repeat(44)); + let (code, stdout, stderr) = run_apply( + tmp.path(), + &[ + "--api-url", + &url, + "--proxy-url", + &url, + "--api-token", + &token, + "--org", + "test-org", + ], + &[], + ); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_AFTER); + assert!(!stderr.contains("Downloaded"), "{stderr}"); +} + +/// `--json` carries the advisory as a run warning; `--silent` prints +/// nothing for a run that succeeded. +#[test] +fn legacy_folder_advisory_is_a_run_warning_and_silent_mutes_it() { + let tmp = tempfile::tempdir().unwrap(); + project(tmp.path()); + write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), MM_AFTER); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--json", "--dry-run"], &[]); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + let env = parse_json_envelope(&stdout); + assert!( + warning_codes(&env).contains(&"legacy_blob_dir".to_string()), + "{env:#}" + ); + assert!( + stderr.trim().is_empty(), + "--json keeps stderr clean: {stderr}" + ); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline", "--silent"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!( + stdout.trim().is_empty() && stderr.trim().is_empty(), + "{stdout}{stderr}" + ); +} + +/// A legacy file whose bytes are not the blob its name says is ignored: +/// the run behaves as if the folder were not there. +#[test] +fn corrupt_legacy_blob_is_ignored() { + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), b"patched content\r\n"); + + let (code, stdout, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 1, "stdout: {stdout}\nstderr: {stderr}"); + assert!(stderr.contains("no local source"), "{stderr}"); + assert!(!stderr.contains(".socket/blob/"), "{stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_BEFORE); +} + +/// A link planted at the legacy entry, or in place of the folder, is not +/// followed: the read never leaves `.socket/`. +#[cfg(unix)] +#[test] +fn linked_legacy_entries_are_not_followed() { + let outside = tempfile::tempdir().unwrap(); + let hash = git_sha256(MM_AFTER); + std::fs::write(outside.path().join(&hash), MM_AFTER).unwrap(); + + // The entry is a link. + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + let dir = tmp.path().join(".socket").join("blob"); + std::fs::create_dir_all(&dir).unwrap(); + std::os::unix::fs::symlink(outside.path().join(&hash), dir.join(&hash)).unwrap(); + let (code, _, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 1, "{stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_BEFORE); + + // The folder is a link. + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + std::os::unix::fs::symlink(outside.path(), tmp.path().join(".socket").join("blob")).unwrap(); + let (code, _, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 1, "{stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_BEFORE); +} + +/// `repair` copies the legacy folder's files into `.socket/blobs/` (with +/// no network), leaves the legacy folder alone, and the next `apply` has +/// nothing to say about it. +#[test] +fn repair_copies_legacy_blobs_into_the_cache() { + let tmp = tempfile::tempdir().unwrap(); + let index = project(tmp.path()); + let hash = git_sha256(MM_AFTER); + let legacy = write_legacy_blob(tmp.path(), &hash, MM_AFTER); + let cached = tmp.path().join(".socket").join("blobs").join(&hash); + + // A dry run names the copy and makes none. + let (code, stdout, stderr) = + run_with_env(tmp.path(), &["repair", "--offline", "--dry-run"], &[]); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + assert!( + stdout.contains("Would copy 1 blob from `.socket/blob/` to `.socket/blobs/`."), + "{stdout}" + ); + assert!(!cached.exists()); + + let (code, stdout, stderr) = run_with_env(tmp.path(), &["repair", "--offline"], &[]); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + assert!( + stdout.contains("Copied 1 blob from `.socket/blob/` to `.socket/blobs/`."), + "{stdout}" + ); + assert_eq!(std::fs::read(&cached).unwrap(), MM_AFTER); + assert_eq!( + std::fs::read(&legacy).unwrap(), + MM_AFTER, + "the legacy folder is the user's: repair copies, it does not move" + ); + + let (code, _, stderr) = run_apply(tmp.path(), &["--offline"], &[]); + assert_eq!(code, 0, "{stderr}"); + assert!(!stderr.contains(".socket/blob/"), "{stderr}"); + assert_eq!(std::fs::read(&index).unwrap(), MM_AFTER); +} diff --git a/crates/socket-patch-cli/tests/apply/main.rs b/crates/socket-patch-cli/tests/apply/main.rs index 26193840b1..610ea9d3ec 100644 --- a/crates/socket-patch-cli/tests/apply/main.rs +++ b/crates/socket-patch-cli/tests/apply/main.rs @@ -36,6 +36,7 @@ mod in_process_gem_fallback_home; mod in_process_gem_multicopy; mod in_process_npm_multicopy; mod in_process_variant_apply_failure; +mod legacy_blob_dir; mod lockfile_only_skip; mod nuget_output_and_signing; mod pnpm_global_virtual_store; diff --git a/crates/socket-patch-core/src/api/blob_fetcher.rs b/crates/socket-patch-core/src/api/blob_fetcher.rs index a991bc2400..772db8e2c2 100644 --- a/crates/socket-patch-core/src/api/blob_fetcher.rs +++ b/crates/socket-patch-core/src/api/blob_fetcher.rs @@ -104,6 +104,93 @@ pub(crate) async fn blob_file_is_intact(path: &Path, hash: &str) -> bool { } } +/// The `.socket/` folder an older commit layout kept patch blobs in. Some +/// projects still have their patch's files committed there by an +/// integration, and nothing under `.socket/blobs/`. The CLI writes only +/// `blobs/`; this folder is read as a fallback and never written. +pub const LEGACY_BLOBS_DIR: &str = "blob"; + +/// The bytes of blob `hash` as the legacy folder `legacy_dir` +/// (`.socket/blob/`) holds them, or `None` when it has no usable entry. +/// +/// Usable means what [`crate::patch::apply`] asks of a `.socket/blobs/` +/// entry, checked before a byte is trusted: `hash` is a blob hash (never a +/// path), neither the folder nor the entry is a link (lstat, so a planted +/// link cannot carry the read out of `.socket/`), the entry is a regular +/// file, and its bytes hash to the git-sha256 it is named for. The bytes +/// returned are the ones that were hashed, so a caller that stores them +/// stores verified content. Anything else is `None`, and the caller falls +/// back to what it did before this folder was read (a download). +pub async fn read_legacy_blob(legacy_dir: &Path, hash: &str) -> Option> { + if !is_valid_blob_hash(hash) { + return None; + } + let entry = legacy_dir.join(hash); + let root = legacy_dir.parent().unwrap_or(legacy_dir); + // Fail closed on a level that cannot be probed, as on a linked one. + if !matches!( + crate::utils::containment::try_linked_level(root, &entry), + Ok(None) + ) { + return None; + } + let bytes = crate::patch::apply::read_blob_entry(&entry).await.ok()?; + blob_hash_matches(hash, &compute_git_sha256_from_bytes(&bytes)).then_some(bytes) +} + +/// Copy each blob of `hashes` that the legacy folder holds +/// ([`read_legacy_blob`]) into `blobs_dir`, through the one verified +/// writer ([`store_verified_blob`]): an entry that is missing is created, +/// one that is corrupt is replaced whole, one that already verifies is +/// left alone. Returns the hashes `blobs_dir` now holds because of it, in +/// the order given. A blob the legacy folder does not hold, or that could +/// not be written, is left out: the caller downloads it as before. +/// +/// One `lstat` when the legacy folder does not exist, which is every +/// project that never had one. +pub async fn restore_from_legacy_dir( + hashes: &[String], + legacy_dir: &Path, + blobs_dir: &Path, +) -> Vec { + if !legacy_dir_exists(legacy_dir).await { + return Vec::new(); + } + let mut restored = Vec::new(); + for hash in hashes { + let Some(bytes) = read_legacy_blob(legacy_dir, hash).await else { + continue; + }; + if store_verified_blob(blobs_dir, hash, &bytes).await.is_ok() { + restored.push(hash.clone()); + } + } + restored +} + +/// The blobs of `hashes` the legacy folder holds intact +/// ([`read_legacy_blob`]), in the order given: what +/// [`restore_from_legacy_dir`] would copy, without writing anything. +pub async fn legacy_blobs_available(hashes: &[String], legacy_dir: &Path) -> Vec { + if !legacy_dir_exists(legacy_dir).await { + return Vec::new(); + } + let mut available = Vec::new(); + for hash in hashes { + if read_legacy_blob(legacy_dir, hash).await.is_some() { + available.push(hash.clone()); + } + } + available +} + +/// Whether `legacy_dir` is a real directory (lstat: a link is not). +async fn legacy_dir_exists(legacy_dir: &Path) -> bool { + tokio::fs::symlink_metadata(legacy_dir) + .await + .is_ok_and(|meta| meta.is_dir()) +} + /// Download all missing `afterHash` blobs referenced in the manifest. /// `on_progress` is called before each download with /// `(hash, 1-based index, total)`. @@ -1083,4 +1170,120 @@ mod tests { "Network error fetching " ); } + + /// A blob named for the git-sha256 of `bytes`, written into `dir`. + async fn write_named_blob(dir: &Path, bytes: &[u8]) -> String { + tokio::fs::create_dir_all(dir).await.unwrap(); + let hash = compute_git_sha256_from_bytes(bytes); + tokio::fs::write(dir.join(&hash), bytes).await.unwrap(); + hash + } + + #[tokio::test] + async fn legacy_blob_is_read_only_when_it_hashes_to_its_name() { + let socket = tempfile::tempdir().unwrap(); + let legacy = socket.path().join(LEGACY_BLOBS_DIR); + let good = write_named_blob(&legacy, b"patched bytes").await; + assert_eq!( + read_legacy_blob(&legacy, &good).await.as_deref(), + Some(&b"patched bytes"[..]) + ); + + // Rewritten content (a line-ending-converting checkout, a truncated + // file) is not the blob its name says. + let torn = "c".repeat(64); + tokio::fs::write(legacy.join(&torn), b"not that content") + .await + .unwrap(); + assert_eq!(read_legacy_blob(&legacy, &torn).await, None); + + // Absent, a directory, and a name that is not a blob hash. + assert_eq!(read_legacy_blob(&legacy, &"d".repeat(64)).await, None); + let dir_entry = "e".repeat(64); + tokio::fs::create_dir(legacy.join(&dir_entry)) + .await + .unwrap(); + assert_eq!(read_legacy_blob(&legacy, &dir_entry).await, None); + assert_eq!(read_legacy_blob(&legacy, "../manifest.json").await, None); + assert_eq!(read_legacy_blob(&legacy, "").await, None); + } + + /// Neither a linked entry nor a linked folder is followed: the read + /// must not leave `.socket/`. + #[cfg(unix)] + #[tokio::test] + async fn legacy_blob_read_never_follows_a_link() { + let outside = tempfile::tempdir().unwrap(); + let hash = write_named_blob(outside.path(), b"elsewhere").await; + + let socket = tempfile::tempdir().unwrap(); + let legacy = socket.path().join(LEGACY_BLOBS_DIR); + tokio::fs::create_dir_all(&legacy).await.unwrap(); + std::os::unix::fs::symlink(outside.path().join(&hash), legacy.join(&hash)).unwrap(); + assert_eq!(read_legacy_blob(&legacy, &hash).await, None); + + let socket = tempfile::tempdir().unwrap(); + let legacy = socket.path().join(LEGACY_BLOBS_DIR); + std::os::unix::fs::symlink(outside.path(), &legacy).unwrap(); + assert_eq!(read_legacy_blob(&legacy, &hash).await, None); + assert!(legacy_blobs_available(std::slice::from_ref(&hash), &legacy) + .await + .is_empty()); + let blobs = socket.path().join("blobs"); + assert!(restore_from_legacy_dir(&[hash], &legacy, &blobs) + .await + .is_empty()); + assert!(!blobs.exists()); + } + + #[tokio::test] + async fn restore_from_legacy_dir_copies_what_verifies_and_nothing_else() { + let socket = tempfile::tempdir().unwrap(); + let legacy = socket.path().join(LEGACY_BLOBS_DIR); + let blobs = socket.path().join("blobs"); + let missing = write_named_blob(&legacy, b"one").await; + let corrupt = write_named_blob(&legacy, b"two").await; + // `blobs/` holds a torn copy of the second one. + tokio::fs::create_dir_all(&blobs).await.unwrap(); + tokio::fs::write(blobs.join(&corrupt), b"t").await.unwrap(); + let torn_legacy = "c".repeat(64); + tokio::fs::write(legacy.join(&torn_legacy), b"wrong") + .await + .unwrap(); + let absent = "d".repeat(64); + let wanted = vec![ + missing.clone(), + corrupt.clone(), + torn_legacy.clone(), + absent.clone(), + ]; + + assert_eq!( + legacy_blobs_available(&wanted, &legacy).await, + vec![missing.clone(), corrupt.clone()] + ); + assert_eq!( + restore_from_legacy_dir(&wanted, &legacy, &blobs).await, + vec![missing.clone(), corrupt.clone()] + ); + assert_eq!(tokio::fs::read(blobs.join(&missing)).await.unwrap(), b"one"); + assert_eq!(tokio::fs::read(blobs.join(&corrupt)).await.unwrap(), b"two"); + assert!(!blobs.join(&torn_legacy).exists()); + assert!(!blobs.join(&absent).exists()); + // The legacy folder is read, never changed. + assert_eq!( + tokio::fs::read(legacy.join(&missing)).await.unwrap(), + b"one" + ); + + // No legacy folder: nothing to copy, and `blobs/` is not created. + let bare = tempfile::tempdir().unwrap(); + let bare_blobs = bare.path().join("blobs"); + assert!( + restore_from_legacy_dir(&wanted, &bare.path().join(LEGACY_BLOBS_DIR), &bare_blobs) + .await + .is_empty() + ); + assert!(!bare_blobs.exists()); + } } From 42ae7e25dbe5b951e1d9ebdb85777ed02784951d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:41:56 -0500 Subject: [PATCH 2/5] Keep the apply download step as it was, and test the partial and nested cases The stager asked the server by hash for what `.socket/blobs/` lacked, which skips an entry the overlay holds in any form. It now asks, as before this branch, for what the overlay lacks by the cache's own rule, less the blobs read from `.socket/blob/`. Tests: a run with one patch's file in the legacy folder and another's nowhere downloads only the second and applies both; `get`'s nested apply reads the legacy folder, makes no blob request and carries the `legacy_blob_dir` warning in both output modes. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/fetch_stage.rs | 11 ++- .../tests/apply/legacy_blob_dir.rs | 79 ++++++++++++++++++- .../get/get_nested_apply_api_flags_e2e.rs | 74 +++++++++++++++++ 3 files changed, 158 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/fetch_stage.rs b/crates/socket-patch-cli/src/commands/fetch_stage.rs index 7bc729e694..c4fa19bbf5 100644 --- a/crates/socket-patch-cli/src/commands/fetch_stage.rs +++ b/crates/socket-patch-cli/src/commands/fetch_stage.rs @@ -16,7 +16,7 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use socket_patch_core::api::blob_fetcher::{ - fetch_blobs_by_hash, get_missing_blobs, read_legacy_blob, FetchMissingBlobsResult, + fetch_blobs_replacing, get_missing_blobs, read_legacy_blob, FetchMissingBlobsResult, LEGACY_BLOBS_DIR, }; use socket_patch_core::manifest::schema::PatchManifest; @@ -278,9 +278,12 @@ pub(crate) async fn stage_patch_sources( let client = common.api_client(client).await; let mut status = StatusLine::stderr(common.json, common.silent); status.set("Downloading missing patch artifacts..."); - // By hash, not by manifest: the legacy folder's blobs are absent from - // the overlay too, and are not downloads. - let fetch_result = fetch_blobs_by_hash(&missing_blobs, &staged.blobs, client, None).await; + // What the overlay lacks, less the legacy folder's blobs: those are + // absent from the overlay too, and are not downloads. + let mut to_fetch = get_missing_blobs(manifest, &staged.blobs).await; + to_fetch.retain(|hash| !staged.legacy.contains_key(hash)); + let to_fetch: Vec = to_fetch.into_iter().collect(); + let fetch_result = fetch_blobs_replacing(&to_fetch, &staged.blobs, client, None).await; status.finish(); if !quiet { for line in format_fetch_summary(&fetch_result) { diff --git a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs index 57ed0c63aa..fe9263ee93 100644 --- a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs +++ b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs @@ -11,8 +11,8 @@ use std::path::Path; use crate::apply_fixture::{ - index_js_patches, install_npm_pkg, run_apply, write_manifest, write_root_package_json, - MM_AFTER, MM_BEFORE, + index_js_patches, install_npm_pkg, one_file, patch_record, run_apply, write_manifest, + write_root_package_json, MM_AFTER, MM_BEFORE, }; use crate::common::envelope::{parse_json_envelope, warning_codes}; use crate::common::{git_sha256, run_with_env}; @@ -114,6 +114,81 @@ fn apply_online_does_not_download_what_the_legacy_folder_holds() { assert!(!stderr.contains("Downloaded"), "{stderr}"); } +/// With one patch's file in the legacy folder and another's nowhere, the +/// run downloads only the second, and applies both. +#[tokio::test] +async fn apply_downloads_only_what_the_legacy_folder_lacks() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let other_after = b"module.exports = 'gadget, patched';\n"; + let tmp = tempfile::tempdir().unwrap(); + write_root_package_json(tmp.path()); + write_manifest( + tmp.path(), + serde_json::json!({ + PURL: patch_record( + "aaaaaaaa-0000-4000-8000-000000000001", + one_file("package/index.js", MM_BEFORE, MM_AFTER), + ), + "pkg:npm/gadget@1.0.0": patch_record( + "aaaaaaaa-0000-4000-8000-000000000002", + one_file("package/index.js", MM_BEFORE, other_after), + ), + }), + ); + let widget = install_npm_pkg(tmp.path(), "widget", "1.0.0", Some(MM_BEFORE)); + let gadget = install_npm_pkg(tmp.path(), "gadget", "1.0.0", Some(MM_BEFORE)); + write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), MM_AFTER); + + // Every blob request is answered with the second patch's bytes: a + // request for the first would fail its hash check, and is counted. + let mock = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(other_after.to_vec())) + .mount(&mock) + .await; + let uri = mock.uri(); + let root = tmp.path().to_path_buf(); + let (code, stdout, stderr) = tokio::task::spawn_blocking(move || { + run_apply( + &root, + &[], + &[ + ("SOCKET_API_URL", uri.as_str()), + ("SOCKET_API_TOKEN", "fake-token-for-test"), + ("SOCKET_ORG_SLUG", "test-org"), + ], + ) + }) + .await + .unwrap(); + assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); + assert_eq!(std::fs::read(&widget).unwrap(), MM_AFTER); + assert_eq!(std::fs::read(&gadget).unwrap(), other_after); + assert!(stderr.contains("Downloaded 1 blob"), "{stderr}"); + assert!( + stderr.contains("read 1 patch file from `.socket/blob/`"), + "{stderr}" + ); + let blob_requests: Vec = mock + .received_requests() + .await + .unwrap() + .iter() + .map(|r| r.url.path().to_string()) + .filter(|path| path.contains("/patches/blob/")) + .collect(); + assert_eq!( + blob_requests, + [format!( + "/v0/orgs/test-org/patches/blob/{}", + git_sha256(other_after) + )], + "the legacy folder's blob is not a download" + ); +} + /// `--json` carries the advisory as a run warning; `--silent` prints /// nothing for a run that succeeded. #[test] diff --git a/crates/socket-patch-cli/tests/get/get_nested_apply_api_flags_e2e.rs b/crates/socket-patch-cli/tests/get/get_nested_apply_api_flags_e2e.rs index 2fc1046f44..f5578c92f0 100644 --- a/crates/socket-patch-cli/tests/get/get_nested_apply_api_flags_e2e.rs +++ b/crates/socket-patch-cli/tests/get/get_nested_apply_api_flags_e2e.rs @@ -327,3 +327,77 @@ async fn get_by_uuid_nested_apply_uses_proxy_url_flag_when_tokenless() { .collect::>() ); } + +/// The nested apply reads a blob the patch view did not embed from the +/// legacy `.socket/blob/` folder (an older commit layout), like a direct +/// `apply`: no blob request is made, the patch applies, and `get` carries +/// the nested run's `legacy_blob_dir` warning (JSON: in `warnings[]`; +/// human: a `Warning:` line on stderr). +#[tokio::test] +async fn get_nested_apply_reads_the_legacy_blob_folder() { + let before_hash = common::git_sha256(BEFORE); + let after_hash = common::git_sha256(AFTER); + + for json in [true, false] { + let mock = MockServer::start().await; + mount_view_without_blob(&mock, &before_hash, &after_hash).await; + // No blob endpoint: a request for the blob would be a 404 and a + // failed run. + + let tmp = tempfile::tempdir().expect("tempdir"); + install_npm_package(tmp.path()); + let legacy = tmp.path().join(".socket").join("blob"); + std::fs::create_dir_all(&legacy).expect("create legacy folder"); + std::fs::write(legacy.join(&after_hash), AFTER).expect("write legacy blob"); + + let uri = mock.uri(); + let mut argv = vec![ + "get", + UUID, + "--mode", + "agent", + "--yes", + "--api-url", + &uri, + "--api-token", + "flag-token", + "--org", + ORG, + ]; + if json { + argv.push("--json"); + } + let (code, stdout, stderr) = common::run_with_env(tmp.path(), &argv, &dead_env()); + assert_eq!(code, 0, "json={json}\nstdout={stdout}\nstderr={stderr}"); + + let patched = tmp.path().join("node_modules").join(PKG).join("index.js"); + assert_eq!(std::fs::read(&patched).expect("read patched file"), AFTER); + if json { + let v: serde_json::Value = serde_json::from_str(stdout.trim()) + .unwrap_or_else(|e| panic!("valid JSON expected: {e}\nstdout={stdout}")); + assert_eq!(v["summary"]["applied"], 1, "stdout={stdout}"); + assert!( + v["warnings"] + .as_array() + .is_some_and(|w| w.iter().any(|w| w["code"] == "legacy_blob_dir")), + "stdout={stdout}" + ); + } else { + assert!( + stderr.contains("Warning: read 1 patch file from `.socket/blob/`"), + "stderr={stderr}" + ); + } + let blob_requests = mock + .received_requests() + .await + .expect("wiremock records requests") + .iter() + .filter(|r| r.url.path().contains("/patches/blob/")) + .count(); + assert_eq!( + blob_requests, 0, + "the legacy folder's blob is not a download" + ); + } +} From 29a4beb9182aa4a1577bd37e750253042a9ed0c2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:51:53 -0500 Subject: [PATCH 3/5] Review fixes for the `.socket/blob/` fallback - `repair` copies from the legacy folder by the whole manifest, not the one scoped to non-vendored records: `apply` stages for vendored records too, so its advisory named files `repair` never copied and never cleared. - `repair` tells a person what is left to do (commit `.socket/blobs/`), which only the `--json` warning said. A dry run, which copied nothing, no longer says to commit, nor that every blob is present. - The "no download" test counts requests on a listening server: against a dead endpoint it could not fail. - Say why the stager reads the legacy blobs up front. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/fetch_stage.rs | 16 ++-- .../socket-patch-cli/src/commands/repair.rs | 74 +++++++++++------- .../tests/apply/legacy_blob_dir.rs | 75 ++++++++++++------- .../socket-patch-core/src/api/blob_fetcher.rs | 2 +- 5 files changed, 106 insertions(+), 63 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 2ece0fc98a..bb8edba0cf 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2799,7 +2799,7 @@ command's integration tests check its output. | `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:/` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. | | `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. | | `offline_missing_sources` / `sources_download_failed` | apply run-level `warnings[]` | apply (additive): the patch sources were unavailable — `--offline` with no local source, or the download left a patch with no source — so nothing was attempted. The envelope keeps its pinned shape (`partialFailure`, empty `events[]`, zero summary, no top-level `error`); the warning is its machine-readable reason (the human path prints the staging `Error:` line on stderr instead, even under `--silent`). | -| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. `apply` writes nothing under `.socket/`. The detail gives the count and the remedy (`socket-patch repair`); human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references that `.socket/blobs/` lacks (or holds corrupt) were copied from `.socket/blob/` before any download, with `--offline` too; `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. | +| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch; the nested apply of `get` and `scan` does the same and the caller carries the warning. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. Only a blob absent from `.socket/blobs/` is looked for: an entry there that is corrupt fails the apply as before, and is `repair`'s to restore. `apply` writes nothing under `.socket/`. The detail gives the count and the remedy (`socket-patch repair`); human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references (the whole manifest, vendored records included, as `apply` stages them) that `.socket/blobs/` lacks or holds corrupt were copied from `.socket/blob/` before any download, with `--offline` too; human mode prints the count and that `.socket/blobs/` is to be committed. `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. | | `paid_required` | `skipped` + status=`paidRequired` | get: every patch found needs a paid plan and the caller's token isn't entitled (exit 0); one `skipped` event per patch, `details.tier`. `get ` on the public proxy reports it both for a `tier: "paid"` view and for the proxy's 403 refusal, whose event then carries only `uuid` (no `purl`: the proxy never named it). `scan` never reports it: it leaves paid patches out of the selection and counts them in `paidPatches` / `canAccessPaidPatches`. | | `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. | | `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (` of packages could not be checked for patches (…): `); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. | diff --git a/crates/socket-patch-cli/src/commands/fetch_stage.rs b/crates/socket-patch-cli/src/commands/fetch_stage.rs index c4fa19bbf5..5eafd93a72 100644 --- a/crates/socket-patch-cli/src/commands/fetch_stage.rs +++ b/crates/socket-patch-cli/src/commands/fetch_stage.rs @@ -16,8 +16,8 @@ use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use socket_patch_core::api::blob_fetcher::{ - fetch_blobs_replacing, get_missing_blobs, read_legacy_blob, FetchMissingBlobsResult, - LEGACY_BLOBS_DIR, + fetch_blobs_replacing, get_missing_blobs, legacy_dir_exists, read_legacy_blob, + FetchMissingBlobsResult, LEGACY_BLOBS_DIR, }; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::patch::apply::PatchSources; @@ -70,13 +70,17 @@ pub(crate) const LEGACY_BLOB_DIR: &str = "legacy_blob_dir"; /// The blobs of `missing` (hashes `.socket/blobs` lacks) that the legacy /// folder `socket_dir/blob` holds, verified ([`read_legacy_blob`]). Empty, /// after one `lstat`, for a project with no such folder. +/// +/// All of them are read up front, on every run, a no-op run included: the +/// offline gate and the download plan need to know now which hashes have a +/// usable source, and only a read can tell (a file is one only when its +/// bytes hash to its name). Holding the verified bytes is also what makes +/// the bytes checked the bytes written. It replaces a download of the same +/// blobs on every run; `repair` ends it. async fn legacy_blobs(socket_dir: &Path, missing: &HashSet) -> HashMap> { let legacy_dir = socket_dir.join(LEGACY_BLOBS_DIR); let mut found = HashMap::new(); - if !tokio::fs::symlink_metadata(&legacy_dir) - .await - .is_ok_and(|meta| meta.is_dir()) - { + if !legacy_dir_exists(&legacy_dir).await { return found; } for hash in missing { diff --git a/crates/socket-patch-cli/src/commands/repair.rs b/crates/socket-patch-cli/src/commands/repair.rs index 047fbbc7ce..f432dfa8a8 100644 --- a/crates/socket-patch-cli/src/commands/repair.rs +++ b/crates/socket-patch-cli/src/commands/repair.rs @@ -1,8 +1,8 @@ use clap::Args; use socket_patch_core::api::blob_fetcher::{ fetch_blobs_replacing, format_fetch_failures, format_fetch_successes, get_corrupt_blobs, - get_missing_blobs, legacy_blobs_available, restore_from_legacy_dir, ArtifactNoun, BLOB, - DIFF_ARCHIVE, LEGACY_BLOBS_DIR, PACKAGE_ARCHIVE, + get_missing_blobs, legacy_blobs_available, legacy_dir_exists, restore_from_legacy_dir, + ArtifactNoun, BLOB, DIFF_ARCHIVE, LEGACY_BLOBS_DIR, PACKAGE_ARCHIVE, }; use socket_patch_core::api::client::{get_api_client_with_overrides, ApiClient}; use socket_patch_core::manifest::cleanup_blobs::{ @@ -443,14 +443,20 @@ fn format_nothing_missing( } } -/// The line for blobs copied (or, in a dry run, that would be copied) from -/// the legacy `.socket/blob/` folder into `.socket/blobs/`. +/// What `repair` says about blobs copied (or, in a dry run, that would be +/// copied) from the legacy `.socket/blob/` folder into `.socket/blobs/`. +/// A real run adds what is left to the user: commit the new folder. A dry +/// run copied nothing, so it has nothing to commit. fn format_legacy_copy(count: usize, dry_run: bool) -> String { - let verb = if dry_run { "Would copy" } else { "Copied" }; - format!( - "{verb} {} from `.socket/{LEGACY_BLOBS_DIR}/` to `.socket/blobs/`.", - BLOB.count(count) - ) + let blobs = BLOB.count(count); + if dry_run { + format!("Would copy {blobs} from `.socket/{LEGACY_BLOBS_DIR}/` to `.socket/blobs/`.") + } else { + format!( + "Copied {blobs} from `.socket/{LEGACY_BLOBS_DIR}/` to `.socket/blobs/`. Commit \ + `.socket/blobs/`; `.socket/{LEGACY_BLOBS_DIR}/` can then be deleted." + ) + } } /// Why a referenced blob has to be downloaded. @@ -756,17 +762,32 @@ async fn repair_inner( // patch the server no longer serves. `apply` reads the folder as a // fallback on every run; this is what makes that one-off. The folder // itself is left as it is (it is the user's, and committed). + // + // By the FULL manifest, not the scoped one: `apply` stages (and so + // reads from the legacy folder) for vendored records too, and its + // advisory must clear once this has run. These are the user's own + // committed files moving to the folder the CLI reads, not sources + // fetched for a vendored project, and the sweep below keeps them (it + // goes by the full manifest as well). let legacy_dir = socket_dir.join(LEGACY_BLOBS_DIR); - let wanted: Vec = missing_artifacts - .iter() - .chain(&corrupt_artifacts) - .cloned() - .collect(); - let from_legacy = if args.common.dry_run { - legacy_blobs_available(&wanted, &legacy_dir).await - } else { - restore_from_legacy_dir(&wanted, &legacy_dir, &blobs_path).await + let from_legacy = match manifest.as_ref() { + Some(m) if legacy_dir_exists(&legacy_dir).await => { + let mut wanted: Vec = get_missing_blobs(m, &blobs_path) + .await + .into_iter() + .chain(get_corrupt_blobs(m, &blobs_path).await) + .collect(); + wanted.sort(); + if args.common.dry_run { + legacy_blobs_available(&wanted, &legacy_dir).await + } else { + restore_from_legacy_dir(&wanted, &legacy_dir, &blobs_path).await + } + } + _ => Vec::new(), }; + // A dry run copied nothing: what it would copy is still neither a + // download nor an offline failure. let left = |ids: Vec| -> Vec { ids.into_iter() .filter(|id| !from_legacy.contains(id)) @@ -774,19 +795,13 @@ async fn repair_inner( }; let (missing_artifacts, corrupt_artifacts) = (left(missing_artifacts), left(corrupt_artifacts)); if !from_legacy.is_empty() { + let line = format_legacy_copy(from_legacy.len(), args.common.dry_run); if !quiet { - println!( - "{}", - format_legacy_copy(from_legacy.len(), args.common.dry_run) - ); + println!("{line}"); } env.warn( crate::commands::fetch_stage::LEGACY_BLOB_DIR, - format!( - "{}; commit `.socket/blobs/`, after which `.socket/{LEGACY_BLOBS_DIR}/` can be \ - deleted", - format_legacy_copy(from_legacy.len(), args.common.dry_run).trim_end_matches('.') - ), + line.trim_end_matches('.'), ); } let nothing_to_fetch = missing_artifacts.is_empty() && corrupt_artifacts.is_empty(); @@ -796,7 +811,10 @@ async fn repair_inner( let mut stdout_started = !args.common.offline || nothing_to_fetch || (!from_legacy.is_empty() && !quiet); let primary = if nothing_to_fetch { - if !quiet { + // A dry run that would copy from the legacy folder has said so: + // "all present" is not true until a real run. + let would_copy = args.common.dry_run && !from_legacy.is_empty(); + if !quiet && !would_copy { println!("{}", format_nothing_missing(manifest.as_ref())); } DownloadPass::default() diff --git a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs index fe9263ee93..b2b5cfabdf 100644 --- a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs +++ b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs @@ -80,38 +80,51 @@ fn apply_offline_uses_blobs_committed_to_the_legacy_folder() { assert_eq!(code, 0, "{stderr}"); } -/// Online, a run that finds every file in the legacy folder downloads -/// nothing: it succeeds against an endpoint that refuses every request. -#[test] -fn apply_online_does_not_download_what_the_legacy_folder_holds() { +/// Online, a run that finds every file in the legacy folder asks the +/// server for nothing. +#[tokio::test] +async fn apply_online_does_not_download_what_the_legacy_folder_holds() { + use wiremock::matchers::method; + use wiremock::{Mock, MockServer, ResponseTemplate}; + let tmp = tempfile::tempdir().unwrap(); let index = project(tmp.path()); write_legacy_blob(tmp.path(), &git_sha256(MM_AFTER), MM_AFTER); - let port = std::net::TcpListener::bind("127.0.0.1:0") - .unwrap() - .local_addr() - .unwrap() - .port(); - let url = format!("http://127.0.0.1:{port}"); - let token = format!("sktsec_{}_api", "x".repeat(44)); - let (code, stdout, stderr) = run_apply( - tmp.path(), - &[ - "--api-url", - &url, - "--proxy-url", - &url, - "--api-token", - &token, - "--org", - "test-org", - ], - &[], - ); + let mock = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(MM_AFTER.to_vec())) + .mount(&mock) + .await; + let uri = mock.uri(); + let root = tmp.path().to_path_buf(); + let (code, stdout, stderr) = tokio::task::spawn_blocking(move || { + run_apply( + &root, + &[], + &[ + ("SOCKET_API_URL", uri.as_str()), + ("SOCKET_API_TOKEN", "fake-token-for-test"), + ("SOCKET_ORG_SLUG", "test-org"), + ], + ) + }) + .await + .unwrap(); assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); assert_eq!(std::fs::read(&index).unwrap(), MM_AFTER); - assert!(!stderr.contains("Downloaded"), "{stderr}"); + assert!(!stderr.contains("ownload"), "{stderr}"); + let blob_requests = mock + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path().contains("/patches/blob/")) + .count(); + assert_eq!( + blob_requests, 0, + "the legacy folder's blob is not a download" + ); } /// With one patch's file in the legacy folder and another's nowhere, the @@ -279,12 +292,20 @@ fn repair_copies_legacy_blobs_into_the_cache() { stdout.contains("Would copy 1 blob from `.socket/blob/` to `.socket/blobs/`."), "{stdout}" ); + // Nothing was copied: nothing to commit, and not "all present" yet. + assert!( + !stdout.contains("Commit") && !stdout.contains("present locally"), + "{stdout}" + ); assert!(!cached.exists()); let (code, stdout, stderr) = run_with_env(tmp.path(), &["repair", "--offline"], &[]); assert_eq!(code, 0, "stdout: {stdout}\nstderr: {stderr}"); assert!( - stdout.contains("Copied 1 blob from `.socket/blob/` to `.socket/blobs/`."), + stdout.contains( + "Copied 1 blob from `.socket/blob/` to `.socket/blobs/`. Commit `.socket/blobs/`; \ + `.socket/blob/` can then be deleted." + ), "{stdout}" ); assert_eq!(std::fs::read(&cached).unwrap(), MM_AFTER); diff --git a/crates/socket-patch-core/src/api/blob_fetcher.rs b/crates/socket-patch-core/src/api/blob_fetcher.rs index 772db8e2c2..925815a4cf 100644 --- a/crates/socket-patch-core/src/api/blob_fetcher.rs +++ b/crates/socket-patch-core/src/api/blob_fetcher.rs @@ -185,7 +185,7 @@ pub async fn legacy_blobs_available(hashes: &[String], legacy_dir: &Path) -> Vec } /// Whether `legacy_dir` is a real directory (lstat: a link is not). -async fn legacy_dir_exists(legacy_dir: &Path) -> bool { +pub async fn legacy_dir_exists(legacy_dir: &Path) -> bool { tokio::fs::symlink_metadata(legacy_dir) .await .is_ok_and(|meta| meta.is_dir()) From 999cce7559905b2415fdde5a075c9d51adce8519 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 14:56:27 -0500 Subject: [PATCH 4/5] Note the legacy-folder exception in the contract's vendored repair rule Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index bb8edba0cf..3d9b4ec8b5 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2008,7 +2008,7 @@ writes nothing) and `gc.removedRegistryEntries` counts them; in a hosted-only pr has zeros for the `.socket/` sweeps, which did not run, and is absent when the project holds nothing of a route. A hosted-only project takes the apply lock only when there is an entry to remove on a wet run, so `.socket/` is never left behind. A file a routed scan created is deleted -once it holds nothing else; a file of the user's keeps their bytes. Agent blob acquisition skips vendored records and lockfile-referenced UUIDs, so repairing a vendored project does not populate `.socket/blobs`. +once it holds nothing else; a file of the user's keeps their bytes. Agent blob acquisition skips vendored records and lockfile-referenced UUIDs, so repairing a vendored project does not populate `.socket/blobs`. The one exception is a project that has such blobs committed under `.socket/blob/`: `repair` copies them (nothing is downloaded), see `legacy_blob_dir`. ### Path convention + patch-UUID recovery (stable) From c359dbb54b116bb735801aa64f21a6072182a933 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 4 Dec 2026 15:00:03 -0500 Subject: [PATCH 5/5] Name `scan` as the first remedy in the `.socket/blob/` notice A project in the older layout was set up long ago and often holds a patch that has since been replaced. Now that its `apply` runs offline, this notice is the only one it gets, and `repair` only copies the old files as they are. `scan` moves the manifest to the current patches and stores their files in `.socket/blobs/`, so the notice names it first and `repair` second, and says to commit `.socket/`. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/fetch_stage.rs | 21 ++++++++++++++----- .../tests/apply/legacy_blob_dir.rs | 4 +++- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 3d9b4ec8b5..c0012698e5 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2799,7 +2799,7 @@ command's integration tests check its output. | `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:/` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. | | `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. | | `offline_missing_sources` / `sources_download_failed` | apply run-level `warnings[]` | apply (additive): the patch sources were unavailable — `--offline` with no local source, or the download left a patch with no source — so nothing was attempted. The envelope keeps its pinned shape (`partialFailure`, empty `events[]`, zero summary, no top-level `error`); the warning is its machine-readable reason (the human path prints the staging `Error:` line on stderr instead, even under `--silent`). | -| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch; the nested apply of `get` and `scan` does the same and the caller carries the warning. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. Only a blob absent from `.socket/blobs/` is looked for: an entry there that is corrupt fails the apply as before, and is `repair`'s to restore. `apply` writes nothing under `.socket/`. The detail gives the count and the remedy (`socket-patch repair`); human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references (the whole manifest, vendored records included, as `apply` stages them) that `.socket/blobs/` lacks or holds corrupt were copied from `.socket/blob/` before any download, with `--offline` too; human mode prints the count and that `.socket/blobs/` is to be committed. `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. | +| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch; the nested apply of `get` and `scan` does the same and the caller carries the warning. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. Only a blob absent from `.socket/blobs/` is looked for: an entry there that is corrupt fails the apply as before, and is `repair`'s to restore. `apply` writes nothing under `.socket/`. The detail gives the count and the remedies, in this order: `socket-patch scan`, which updates the patches (a project in this layout often holds one that has since been replaced) and stores their files in `.socket/blobs/`, or `socket-patch repair`, which copies the files as they are; then commit `.socket/`. Human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references (the whole manifest, vendored records included, as `apply` stages them) that `.socket/blobs/` lacks or holds corrupt were copied from `.socket/blob/` before any download, with `--offline` too; human mode prints the count and that `.socket/blobs/` is to be committed. `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. | | `paid_required` | `skipped` + status=`paidRequired` | get: every patch found needs a paid plan and the caller's token isn't entitled (exit 0); one `skipped` event per patch, `details.tier`. `get ` on the public proxy reports it both for a `tier: "paid"` view and for the proxy's 403 refusal, whose event then carries only `uuid` (no `purl`: the proxy never named it). `scan` never reports it: it leaves paid patches out of the selection and counts them in `paidPatches` / `canAccessPaidPatches`. | | `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. | | `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (` of packages could not be checked for patches (…): `); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. | diff --git a/crates/socket-patch-cli/src/commands/fetch_stage.rs b/crates/socket-patch-cli/src/commands/fetch_stage.rs index 5eafd93a72..8a9c5a6531 100644 --- a/crates/socket-patch-cli/src/commands/fetch_stage.rs +++ b/crates/socket-patch-cli/src/commands/fetch_stage.rs @@ -47,6 +47,13 @@ impl StagedSources { /// The advisory for a run that read patch files from the legacy /// `.socket/blob` folder, `None` when it read none. + /// + /// `scan` is the first remedy: a project in that layout was set up long + /// ago and often holds a patch that has since been replaced, and now + /// that its `apply` runs offline this line is the only notice it gets. + /// `scan` moves the manifest to the current patches and stores their + /// files in `.socket/blobs`; `repair` only copies the files as they + /// are. pub(crate) fn legacy_blob_dir_warning(&self) -> Option<(&'static str, String)> { let n = self.legacy.len(); (n > 0).then(|| { @@ -54,8 +61,9 @@ impl StagedSources { LEGACY_BLOB_DIR, format!( "read {} from `.socket/{LEGACY_BLOBS_DIR}/`; socket-patch keeps patch \ - files in `.socket/blobs/`. Run `socket-patch repair` to copy them there, \ - then commit `.socket/blobs/`", + files in `.socket/blobs/`. Run `socket-patch scan` to update the patches \ + and store their files there (or `socket-patch repair` to copy them as \ + they are), then commit `.socket/`", plural(n, "patch file", "patch files") ), ) @@ -475,9 +483,12 @@ mod tests { ); let (code, detail) = staged.legacy_blob_dir_warning().expect("advisory"); assert_eq!(code, "legacy_blob_dir"); - assert!( - detail.starts_with("read 1 patch file from `.socket/blob/`"), - "{detail}" + assert_eq!( + detail, + "read 1 patch file from `.socket/blob/`; socket-patch keeps patch files in \ + `.socket/blobs/`. Run `socket-patch scan` to update the patches and store \ + their files there (or `socket-patch repair` to copy them as they are), then \ + commit `.socket/`" ); assert!(!socket_dir.join("blobs").exists(), "apply writes no cache"); } diff --git a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs index b2b5cfabdf..039d9aee48 100644 --- a/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs +++ b/crates/socket-patch-cli/tests/apply/legacy_blob_dir.rs @@ -66,7 +66,9 @@ fn apply_offline_uses_blobs_committed_to_the_legacy_folder() { assert!( stderr.contains( "Warning: read 1 patch file from `.socket/blob/`; socket-patch keeps patch files \ - in `.socket/blobs/`. Run `socket-patch repair` to copy them there" + in `.socket/blobs/`. Run `socket-patch scan` to update the patches and store their \ + files there (or `socket-patch repair` to copy them as they are), then commit \ + `.socket/`" ), "the run says where the files belong: {stderr}" );