socket-patch-cli 3.3.0

CLI binary for socket-patch: apply, rollback, get, scan security patches
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! End-to-end tests for the `scan` subcommand against the real Socket API.
//!
//! Exercises the `scan --apply` + opt-in GC pipeline introduced in v3.0:
//!
//! * `scan --json --apply --yes` adds, updates, and skips patches based on
//!   the existing manifest, emitting the `apply.patches[]` action vocabulary
//!   (`"added"`, `"updated"`, `"skipped"`).
//! * Read-only `scan --json` emits the `updates` array (PURLs whose UUID
//!   would change) and does NOT emit a `gc` field by default.
//! * `--prune` opts into garbage collection (manifest pruning + orphan
//!   file cleanup). Without it, scan leaves the manifest alone.
//! * `--sync` is sugar for `--apply --prune` — the canonical bot mode.
//! * `--dry-run` previews `--apply` / `--prune` / `--sync` actions
//!   without mutating disk.
//!
//! Uses the same minimist@1.2.2 patch fixture as `e2e_npm.rs`. Tests are
//! marked `#[ignore]` so they only run with `--ignored`, matching the
//! existing e2e gating in `.github/workflows/ci.yml`.
//!
//! # Prerequisites
//! - `npm` on PATH
//! - Network access to `patches-api.socket.dev` and `registry.npmjs.org`
//!
//! # Running
//! ```sh
//! cargo test -p socket-patch-cli --test e2e_scan -- --ignored
//! ```

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

use sha2::{Digest, Sha256};

// ---------------------------------------------------------------------------
// Constants (shared with e2e_npm; duplicated here because Rust integration
// test binaries don't share modules without `tests/common/mod.rs` tricks
// that the existing suite explicitly avoided).
// ---------------------------------------------------------------------------

const NPM_PURL: &str = "pkg:npm/minimist@1.2.2";

/// Git SHA-256 of the *unpatched* `index.js` shipped with minimist 1.2.2.
/// Used to assert "file was patched" (no longer matches BEFORE_HASH).
/// The specific `AFTER_HASH` isn't pinned here because the upstream API
/// can serve multiple free patches over time with different fix bytes.
const BEFORE_HASH: &str = "311f1e893e6eac502693fad8617dcf5353a043ccc0f7b4ba9fe385e838b67a10";

/// 64-hex-char placeholder used for orphan-blob fixtures. Not a real
/// blob hash — picked so it can't accidentally collide with anything
/// the API would return.
const FAKE_ORPHAN_HASH: &str =
    "0000000000000000000000000000000000000000000000000000000000000000";

/// Fake UUID we plant in the manifest to force `scan --apply` into the
/// `"updated"` branch.
const FAKE_OLD_UUID: &str = "11111111-1111-4111-8111-111111111111";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn binary() -> PathBuf {
    env!("CARGO_BIN_EXE_socket-patch").into()
}

fn has_command(cmd: &str) -> bool {
    Command::new(cmd)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok()
}

fn git_sha256(content: &[u8]) -> String {
    let header = format!("blob {}\0", content.len());
    let mut hasher = Sha256::new();
    hasher.update(header.as_bytes());
    hasher.update(content);
    hex::encode(hasher.finalize())
}

fn git_sha256_file(path: &Path) -> String {
    let content = std::fs::read(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    git_sha256(&content)
}

fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) {
    let out: Output = Command::new(binary())
        .args(args)
        .current_dir(cwd)
        .env_remove("SOCKET_API_TOKEN")
        .env_remove("SOCKET_API_URL")
        .output()
        .expect("failed to execute socket-patch binary");
    let code = out.status.code().unwrap_or(-1);
    let stdout = String::from_utf8_lossy(&out.stdout).to_string();
    let stderr = String::from_utf8_lossy(&out.stderr).to_string();
    (code, stdout, stderr)
}

fn assert_run_ok(cwd: &Path, args: &[&str], context: &str) -> (String, String) {
    let (code, stdout, stderr) = run(cwd, args);
    assert_eq!(
        code, 0,
        "{context} failed (exit {code}).\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    (stdout, stderr)
}

fn npm_run(cwd: &Path, args: &[&str]) {
    let out = Command::new("npm")
        .args(args)
        .current_dir(cwd)
        .output()
        .expect("failed to run npm");
    assert!(
        out.status.success(),
        "npm {args:?} failed (exit {:?}).\nstdout:\n{}\nstderr:\n{}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
}

fn write_package_json(cwd: &Path) {
    std::fs::write(
        cwd.join("package.json"),
        r#"{"name":"e2e-scan-test","version":"0.0.0","private":true}"#,
    )
    .expect("write package.json");
}

fn parse_scan_json(stdout: &str) -> serde_json::Value {
    serde_json::from_str(stdout)
        .unwrap_or_else(|e| panic!("scan emitted invalid JSON: {e}\nstdout:\n{stdout}"))
}

/// Parse the persisted `.socket/manifest.json`. Panics with a useful
/// message if it doesn't exist or is malformed.
fn read_manifest_file(cwd: &Path) -> serde_json::Value {
    let path = cwd.join(".socket/manifest.json");
    let content = std::fs::read_to_string(&path)
        .unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    serde_json::from_str(&content)
        .unwrap_or_else(|e| panic!("manifest is not valid JSON: {e}\n{content}"))
}

/// Write a manifest with the given (PURL → UUID) entries. Used to seed
/// the "updated" and "prune" test scenarios. Mimics the shape produced
/// by `download_and_apply_patches` — only the keys we care about.
fn write_seed_manifest(cwd: &Path, purl: &str, uuid: &str) {
    let socket_dir = cwd.join(".socket");
    std::fs::create_dir_all(&socket_dir).expect("create .socket");
    let manifest = serde_json::json!({
        "version": 1,
        "patches": {
            purl: {
                "uuid": uuid,
                "exportedAt": "2024-01-01T00:00:00Z",
                "files": {},
                "vulnerabilities": {},
                "description": "",
                "license": "",
                "tier": "free",
            }
        }
    });
    std::fs::write(
        socket_dir.join("manifest.json"),
        serde_json::to_string_pretty(&manifest).expect("serialize manifest"),
    )
    .expect("write seed manifest");
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// `scan --json --apply --yes` against a fresh install should report a
/// single `action: "added"` entry for the minimist patch, write the
/// manifest, and patch the file on disk. The specific UUID/afterHash
/// the upstream API serves can change over time (multiple free patches
/// may exist for the same PURL), so the test asserts the contract
/// shape rather than exact bytes — action vocabulary, PURL match, and
/// "file was patched" (i.e. no longer matches BEFORE_HASH).
#[test]
#[ignore]
fn test_scan_apply_json_adds_new_patch() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }

    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    let index_js = cwd.join("node_modules/minimist/index.js");
    assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes"],
        "scan --json --apply --yes (fresh)",
    );
    let v = parse_scan_json(&stdout);

    assert_eq!(v["status"], "success");
    let patches = v["apply"]["patches"].as_array().expect("apply.patches array");
    let minimist = patches
        .iter()
        .find(|p| p["purl"] == NPM_PURL)
        .expect("apply.patches should include minimist");
    assert_eq!(minimist["action"], "added");
    assert!(minimist["uuid"].is_string(), "uuid must be present");

    assert_ne!(
        git_sha256_file(&index_js),
        BEFORE_HASH,
        "file should have been patched (no longer BEFORE_HASH)",
    );
    let manifest = read_manifest_file(cwd);
    assert!(
        manifest["patches"][NPM_PURL].is_object(),
        "manifest must record an entry for {NPM_PURL}"
    );
}

/// Re-running `scan --json --apply --yes` after the patch is already in
/// the manifest reports `action: "skipped"` and leaves the file alone.
#[test]
#[ignore]
fn test_scan_apply_json_skips_existing() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "first run");
    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes"],
        "second run",
    );
    let v = parse_scan_json(&stdout);

    let patches = v["apply"]["patches"].as_array().expect("apply.patches array");
    let minimist = patches
        .iter()
        .find(|p| p["purl"] == NPM_PURL)
        .expect("apply.patches should include minimist on re-run");
    assert_eq!(minimist["action"], "skipped");
    // The first run already patched the file — second run shouldn't
    // touch it, so the hash should still differ from BEFORE_HASH.
    assert_ne!(
        git_sha256_file(&cwd.join("node_modules/minimist/index.js")),
        BEFORE_HASH,
        "file should still be patched after a no-op re-run",
    );
}

/// Seeding a manifest with a fake old UUID for the minimist PURL forces
/// `scan --apply` into the `"updated"` branch — the per-patch record
/// carries `oldUuid` matching the fake.
#[test]
#[ignore]
fn test_scan_apply_json_updates_existing() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);
    write_seed_manifest(cwd, NPM_PURL, FAKE_OLD_UUID);

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes"],
        "scan with seeded fake UUID",
    );
    let v = parse_scan_json(&stdout);

    let patches = v["apply"]["patches"].as_array().expect("apply.patches array");
    let minimist = patches
        .iter()
        .find(|p| p["purl"] == NPM_PURL)
        .expect("apply.patches should include minimist");
    assert_eq!(minimist["action"], "updated");
    assert_eq!(minimist["oldUuid"], FAKE_OLD_UUID);
    assert!(
        minimist["uuid"].is_string(),
        "uuid must be present (specific value can drift as API serves multiple patches)",
    );
    assert_ne!(
        minimist["uuid"], FAKE_OLD_UUID,
        "new uuid must differ from the seeded fake oldUuid",
    );

    let manifest = read_manifest_file(cwd);
    let new_uuid = manifest["patches"][NPM_PURL]["uuid"]
        .as_str()
        .expect("manifest must record a new uuid");
    assert_ne!(new_uuid, FAKE_OLD_UUID, "manifest must reflect the update");
}

/// `scan --json` (without `--apply`) is read-only: it lists available
/// patches and an `updates` array reflecting manifest-vs-API drift, but
/// does not mutate `.socket/manifest.json` or the file on disk.
#[test]
#[ignore]
fn test_scan_json_read_only_emits_updates_array() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);
    write_seed_manifest(cwd, NPM_PURL, FAKE_OLD_UUID);

    let index_js = cwd.join("node_modules/minimist/index.js");
    assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);

    let (stdout, _) = assert_run_ok(cwd, &["scan", "--json"], "scan --json (read-only)");
    let v = parse_scan_json(&stdout);

    let updates = v["updates"].as_array().expect("updates array");
    assert_eq!(updates.len(), 1, "expected exactly one update for minimist");
    assert_eq!(updates[0]["purl"], NPM_PURL);
    assert_eq!(updates[0]["oldUuid"], FAKE_OLD_UUID);
    assert!(updates[0]["newUuid"].is_string(), "newUuid must be present");
    assert_ne!(
        updates[0]["newUuid"], FAKE_OLD_UUID,
        "newUuid must differ from the seeded oldUuid",
    );

    // No mutation: seeded manifest UUID stays put, file stays unpatched.
    let manifest = read_manifest_file(cwd);
    assert_eq!(manifest["patches"][NPM_PURL]["uuid"], FAKE_OLD_UUID);
    assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);
}

/// `scan --json` against a project with no existing manifest does NOT
/// create one — read-only is read-only.
#[test]
#[ignore]
fn test_scan_json_read_only_no_mutation() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    let index_js = cwd.join("node_modules/minimist/index.js");
    let (_, _) = assert_run_ok(cwd, &["scan", "--json"], "scan --json (no manifest)");

    assert!(
        !cwd.join(".socket/manifest.json").exists(),
        "scan --json must not create a manifest"
    );
    assert_eq!(
        git_sha256_file(&index_js),
        BEFORE_HASH,
        "scan --json must not patch files"
    );
}

/// When a previously-patched package is uninstalled, passing `--prune`
/// (or `--sync`) on the next `scan --apply --yes` prunes its manifest
/// entry and sweeps the orphan blobs. JSON output reports it in
/// `gc.prunedManifestEntries`.
#[test]
#[ignore]
fn test_scan_apply_prune_prunes_uninstalled_package() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    // First run — patch is added (no --prune needed for the apply step).
    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "initial apply");
    assert!(cwd.join(".socket/manifest.json").exists());

    npm_run(cwd, &["uninstall", "minimist"]);
    // Reinstall a placeholder package so the crawl still finds *something*
    // (scan with zero scanned packages skips GC entirely).
    npm_run(cwd, &["install", "left-pad@1.3.0"]);

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes", "--prune"],
        "scan with --prune after uninstall",
    );
    let v = parse_scan_json(&stdout);

    let pruned = v["gc"]["prunedManifestEntries"]
        .as_array()
        .expect("gc.prunedManifestEntries array");
    assert!(
        pruned.iter().any(|p| p == NPM_PURL),
        "minimist should be pruned from manifest after uninstall; got {pruned:?}"
    );

    let manifest = read_manifest_file(cwd);
    assert!(
        manifest["patches"][NPM_PURL].is_null(),
        "minimist entry should be removed from manifest"
    );
}

/// Default `scan --apply --yes` (no `--prune`) leaves manifest entries
/// for uninstalled packages alone. The `gc` field is omitted entirely
/// from JSON output — users wanting cleanup must opt in.
#[test]
#[ignore]
fn test_scan_apply_default_keeps_uninstalled_entries() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "initial apply");
    npm_run(cwd, &["uninstall", "minimist"]);
    npm_run(cwd, &["install", "left-pad@1.3.0"]);

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes"],
        "scan without --prune",
    );
    let v = parse_scan_json(&stdout);

    assert!(
        v.get("gc").is_none() || v["gc"].is_null(),
        "gc field must be omitted when --prune is not set; got {}",
        v["gc"]
    );

    let manifest = read_manifest_file(cwd);
    assert!(
        !manifest["patches"][NPM_PURL].is_null(),
        "minimist entry must survive when --prune is not set"
    );
}

/// Even without manifest changes, a stray orphan blob file in
/// `.socket/blobs/` is removed by the next `scan --apply --yes --prune`
/// (GC must be opt-in via `--prune` or `--sync`).
#[test]
#[ignore]
fn test_scan_apply_prune_cleans_orphan_blobs() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);
    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "initial apply");

    // Plant an orphan blob. Not referenced by any manifest entry, so the
    // GC pass must reap it.
    let blobs_dir = cwd.join(".socket/blobs");
    std::fs::create_dir_all(&blobs_dir).expect("create blobs dir");
    let orphan = blobs_dir.join(FAKE_ORPHAN_HASH);
    std::fs::write(&orphan, b"junk").expect("plant orphan");
    assert!(orphan.exists());

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--apply", "--yes", "--prune"],
        "scan --prune with orphan blob present",
    );
    let v = parse_scan_json(&stdout);

    let removed = v["gc"]["removedBlobs"]
        .as_u64()
        .expect("gc.removedBlobs should be a number");
    assert!(
        removed >= 1,
        "gc should report at least 1 removed blob, got {removed}"
    );
    assert!(!orphan.exists(), "orphan blob should be deleted");
}

/// `scan --json --dry-run --sync --yes` previews the full sync action:
/// `apply.patches[]` is populated with would-be actions and `gc`
/// reports `prunable*`/`orphan*` counts, but nothing on disk changes.
#[test]
#[ignore]
fn test_scan_dry_run_sync_previews_apply_and_gc() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);
    // Set up: apply once to create a manifest, then uninstall + plant
    // an orphan so there's prune + cleanup work to preview.
    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "initial apply");

    npm_run(cwd, &["uninstall", "minimist"]);
    npm_run(cwd, &["install", "left-pad@1.3.0"]);

    let blobs_dir = cwd.join(".socket/blobs");
    let orphan = blobs_dir.join(FAKE_ORPHAN_HASH);
    std::fs::write(&orphan, b"junk").expect("plant orphan");

    // Capture pre-state to verify dry-run is non-mutating.
    let pre_manifest = read_manifest_file(cwd);

    let (stdout, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--dry-run", "--sync", "--yes"],
        "scan --dry-run --sync",
    );
    let v = parse_scan_json(&stdout);

    // Preview output present.
    let prunable = v["gc"]["prunableManifestEntries"]
        .as_array()
        .expect("gc.prunableManifestEntries array");
    assert!(
        prunable.iter().any(|p| p == NPM_PURL),
        "preview should list minimist as prunable; got {prunable:?}"
    );
    assert!(
        v["gc"]["orphanBlobs"].as_u64().unwrap_or(0) >= 1,
        "preview should count at least 1 orphan blob"
    );
    assert_eq!(v["apply"]["dryRun"], true);

    // Verify non-mutation.
    assert!(orphan.exists(), "dry-run must not delete orphan blob");
    let post_manifest = read_manifest_file(cwd);
    assert_eq!(
        pre_manifest, post_manifest,
        "dry-run must leave manifest exactly as it was"
    );
}

/// `scan --json` (no `--prune`/`--sync`) emits NO `gc` field, even when
/// the manifest has prunable entries and there are orphan files on
/// disk. GC information is opt-in per the v3.0 contract.
#[test]
#[ignore]
fn test_scan_json_no_gc_field_without_prune() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);
    assert_run_ok(cwd, &["scan", "--json", "--apply", "--yes"], "initial apply");

    npm_run(cwd, &["uninstall", "minimist"]);
    npm_run(cwd, &["install", "left-pad@1.3.0"]);

    let blobs_dir = cwd.join(".socket/blobs");
    let orphan = blobs_dir.join(FAKE_ORPHAN_HASH);
    std::fs::write(&orphan, b"junk").expect("plant orphan");

    let (stdout, _) = assert_run_ok(cwd, &["scan", "--json"], "scan --json (no prune)");
    let v = parse_scan_json(&stdout);

    assert!(
        v.get("gc").is_none() || v["gc"].is_null(),
        "scan --json must NOT emit gc when --prune is not set; got {}",
        v["gc"]
    );
}

/// `scan --json --sync --yes` does the full sync — discover + apply +
/// prune + sweep — in one invocation. Mirrors what an auto-update bot
/// would run as the single command.
#[test]
#[ignore]
fn test_scan_sync_yes_full_lifecycle() {
    if !has_command("npm") {
        eprintln!("SKIP: npm not found on PATH");
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    let cwd = dir.path();
    write_package_json(cwd);
    npm_run(cwd, &["install", "minimist@1.2.2"]);

    // Run 1: --sync adds the patch (no prior state to prune).
    let (stdout1, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--sync", "--yes"],
        "first --sync apply",
    );
    let v1 = parse_scan_json(&stdout1);
    let patches = v1["apply"]["patches"]
        .as_array()
        .expect("first sync should populate apply.patches");
    assert!(
        patches.iter().any(|p| p["purl"] == NPM_PURL && p["action"] == "added"),
        "first sync should add the minimist patch"
    );
    // gc field should be present (--sync implies --prune) but empty.
    assert!(v1["gc"].is_object(), "gc must be emitted under --sync");

    // Uninstall + plant orphan, then run --sync again.
    npm_run(cwd, &["uninstall", "minimist"]);
    npm_run(cwd, &["install", "left-pad@1.3.0"]);
    let blobs_dir = cwd.join(".socket/blobs");
    let orphan = blobs_dir.join(FAKE_ORPHAN_HASH);
    std::fs::write(&orphan, b"junk").expect("plant orphan");

    // Run 2: --sync prunes minimist + sweeps the orphan.
    let (stdout2, _) = assert_run_ok(
        cwd,
        &["scan", "--json", "--sync", "--yes"],
        "second --sync after uninstall",
    );
    let v2 = parse_scan_json(&stdout2);
    let pruned = v2["gc"]["prunedManifestEntries"]
        .as_array()
        .expect("gc.prunedManifestEntries array");
    assert!(
        pruned.iter().any(|p| p == NPM_PURL),
        "minimist should be pruned by --sync after uninstall; got {pruned:?}"
    );
    assert!(!orphan.exists(), "orphan should be reaped");
    let manifest = read_manifest_file(cwd);
    assert!(
        manifest["patches"][NPM_PURL].is_null(),
        "manifest must not retain minimist after --sync prune"
    );
}