claude-profiles 0.7.0

Launch claude with only the plugins, skills, and MCP servers a profile defines
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use crate::fs_paths::Paths;
use crate::git::{parse_repo_ref, GitCli};
use crate::lock::{Lockfile, LockedMarketplace};
use crate::profile::Profile;
use crate::vendor::{self, PluginSource};
use crate::vendor_fs;
use anyhow::Context;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Clone any marketplace referenced by `profile` that isn't already cloned into
/// claude-profile's own store. Idempotent: existing clones are left alone (`update`
/// advances them separately via `pin_marketplaces`' checkout).
pub fn ensure_marketplace_clones<G: GitCli>(git: &G, profile: &Profile, paths: &Paths) -> anyhow::Result<()> {
    for (name, source) in &profile.marketplaces {
        let dir = paths.marketplace_clone_dir(name);
        if dir.is_dir() {
            continue;
        }
        let repo_ref = parse_repo_ref(source)?;
        crate::progress::step(&format!("cloning marketplace {name}"));
        git.clone(&repo_ref.clone_url(), &dir).with_context(|| {
            format!("cloning marketplace '{name}' from {} into {}", repo_ref.clone_url(), dir.display())
        })?;
        crate::progress::done(&format!("cloned {name}"));
    }
    Ok(())
}

/// Vendor every plugin/skill `profile.plugins` references into
/// `store/<profile_key>/vendor/<plugin_id>/`. Already-vendored entries are left
/// alone unless `force` is set (used by `update` after a pin moves).
pub fn vendor_plugins<G: GitCli>(
    git: &G,
    profile: &Profile,
    profile_key: &str,
    cwd: &Path,
    paths: &Paths,
    force: bool,
    lock: &mut Lockfile,
) -> anyhow::Result<()> {
    let total = profile.plugins.len();
    let mut vendored = 0usize;
    for (i, plugin_id) in profile.plugins.iter().enumerate() {
        let dest = paths.profile_vendor_dir(profile_key).join(plugin_id);
        if dest.exists() {
            if !force {
                continue;
            }
            std::fs::remove_dir_all(&dest)?;
        }

        let (name, marketplace) = plugin_id
            .rsplit_once('@')
            .ok_or_else(|| anyhow::anyhow!("plugin id '{plugin_id}' is missing '@marketplace'"))?;

        crate::progress::step(&format!("vendoring {plugin_id} ({}/{total})", i + 1));
        if marketplace == "skills-dir" {
            vendor_loose_skill(name, cwd, paths, &dest)?;
        } else {
            vendor_marketplace_entry(git, paths, marketplace, name, plugin_id, force, &dest, lock)?;
        }
        vendored += 1;
    }
    if vendored > 0 {
        let plural = if vendored == 1 { "plugin" } else { "plugins" };
        crate::progress::done(&format!("vendored {vendored} {plural}"));
    }
    Ok(())
}

/// Vendor a personal loose skill (the `<name>@skills-dir` convention) as a copy,
/// generating a manifest on the copy if the original lacks one.
fn vendor_loose_skill(name: &str, cwd: &Path, paths: &Paths, dest: &Path) -> anyhow::Result<()> {
    let src = locate_loose_skill(name, cwd, paths)?;
    vendor_fs::copy_dir_atomic(&src, dest)?;
    vendor_fs::ensure_manifest(dest, name)
}

/// Vendor a marketplace-listed plugin: resolve its source from the marketplace's
/// `marketplace.json`, then copy it in from either the marketplace clone
/// (relative path) or a separately-cloned external repo (recording/refreshing its
/// SHA in `lock.plugins` so it's tracked the same way marketplaces are).
fn vendor_marketplace_entry<G: GitCli>(
    git: &G,
    paths: &Paths,
    marketplace: &str,
    name: &str,
    plugin_id: &str,
    force: bool,
    dest: &Path,
    lock: &mut Lockfile,
) -> anyhow::Result<()> {
    let mkt_dir = paths.marketplace_clone_dir(marketplace);
    let manifest_body = std::fs::read_to_string(mkt_dir.join(".claude-plugin").join("marketplace.json"))
        .map_err(|e| anyhow::anyhow!("reading marketplace.json for '{marketplace}': {e}"))?;
    let plugins = vendor::parse_marketplace_json(&manifest_body)?;
    let entry = vendor::find_plugin(&plugins, name)?;

    match &entry.source {
        PluginSource::RelativePath(rel) => {
            let src = mkt_dir.join(rel.trim_start_matches("./"));
            vendor_fs::copy_dir_atomic(&src, dest)
        }
        PluginSource::ExternalRepo { repo } => vendor_external_repo(git, paths, repo, plugin_id, force, dest, lock),
        PluginSource::GitSubdir { url, path, git_ref, sha } => vendor_git_subdir(
            git, paths, url, path, git_ref.as_deref(), sha.as_deref(), plugin_id, force, dest, lock,
        ),
    }
}

/// Vendor a plugin sourced from a separate repo: clone it once, refresh it on
/// `force` (so `update` actually moves it forward, not just re-copies stale
/// content), then record its resolved SHA in `lock.plugins` for reproducibility.
fn vendor_external_repo<G: GitCli>(
    git: &G,
    paths: &Paths,
    repo: &str,
    plugin_id: &str,
    force: bool,
    dest: &Path,
    lock: &mut Lockfile,
) -> anyhow::Result<()> {
    let repo_ref = parse_repo_ref(repo)?;
    let ext_dir = paths.external_marketplace_dir(&repo_ref.owner, &repo_ref.repo);
    if !ext_dir.is_dir() {
        git.clone(&repo_ref.clone_url(), &ext_dir).with_context(|| {
            format!("cloning plugin '{plugin_id}' from {} into {}", repo_ref.clone_url(), ext_dir.display())
        })?;
    } else if force {
        git.pull(&ext_dir).with_context(|| {
            format!("pulling plugin '{plugin_id}' ({repo}) at {}", ext_dir.display())
        })?;
    }
    let sha = git.head_sha(&ext_dir)?;
    lock.plugins.insert(plugin_id.to_string(), LockedMarketplace { source: repo.to_string(), sha });
    vendor_fs::copy_dir_atomic(&ext_dir, dest)
}

/// Vendor a plugin living in a subdirectory of a separate repo, pinned to an
/// explicit `sha` and/or floating `ref`. Unlike `vendor_external_repo`, only
/// `subpath` is copied out, and the checkout always moves to the pinned target
/// (not gated by `force`) since each `git-subdir` entry names its own commit —
/// the shared repo clone can't just be left wherever a previous plugin left it.
#[allow(clippy::too_many_arguments)]
fn vendor_git_subdir<G: GitCli>(
    git: &G,
    paths: &Paths,
    url: &str,
    subpath: &str,
    git_ref: Option<&str>,
    pinned_sha: Option<&str>,
    plugin_id: &str,
    force: bool,
    dest: &Path,
    lock: &mut Lockfile,
) -> anyhow::Result<()> {
    let repo_ref = parse_repo_ref(url)?;
    let ext_dir = paths.external_marketplace_dir(&repo_ref.owner, &repo_ref.repo);
    if !ext_dir.is_dir() {
        git.clone(&repo_ref.clone_url(), &ext_dir).with_context(|| {
            format!("cloning plugin '{plugin_id}' from {} into {}", repo_ref.clone_url(), ext_dir.display())
        })?;
    } else if force {
        git.pull(&ext_dir).with_context(|| {
            format!("pulling plugin '{plugin_id}' ({url}) at {}", ext_dir.display())
        })?;
    }
    if let Some(target) = pinned_sha.or(git_ref) {
        git.checkout(&ext_dir, target).with_context(|| {
            format!("checking out '{target}' for plugin '{plugin_id}' at {}", ext_dir.display())
        })?;
    }
    let sha = git.head_sha(&ext_dir)?;
    lock.plugins.insert(plugin_id.to_string(), LockedMarketplace { source: url.to_string(), sha });
    vendor_fs::copy_dir_atomic(&ext_dir.join(subpath), dest)
}

/// Find a personal skill's source folder: project-local `.claude/skills/<name>`
/// first, then the user's personal `~/.claude/skills/<name>`. The result is only
/// ever *read* — vendoring always copies, never modifies the original.
fn locate_loose_skill(name: &str, cwd: &Path, paths: &Paths) -> anyhow::Result<PathBuf> {
    let project = cwd.join(".claude").join("skills").join(name);
    if project.is_dir() {
        return Ok(project);
    }
    let personal = paths.claude_skills_dir().join(name);
    if personal.is_dir() {
        return Ok(personal);
    }
    anyhow::bail!("loose skill '{name}' not found under .claude/skills or ~/.claude/skills")
}

fn confirm(profile: &Profile, missing_marketplaces: &[String], missing_plugins: &[String]) -> bool {
    println!("claude-profile will vendor the following into ~/.claude-profiles/store/{}/:", profile.name);
    for name in missing_marketplaces {
        println!("  marketplace clone: {name}");
    }
    for id in missing_plugins {
        println!("  plugin/skill:      {id}");
    }
    print!("Proceed? [y/N] ");
    std::io::stdout().flush().ok();
    let mut line = String::new();
    if std::io::stdin().read_line(&mut line).is_err() {
        return false;
    }
    matches!(line.trim(), "y" | "Y" | "yes")
}

/// Top-level provisioning entry point: clone missing marketplaces, pin them to
/// their target SHA, then vendor every plugin/skill the profile references.
/// Prompts for confirmation before doing anything new (`assume_yes` skips it).
pub fn provision<G: GitCli>(
    git: &G,
    profile: &Profile,
    profile_key: &str,
    _cwd: &Path,
    paths: &Paths,
    assume_yes: bool,
) -> anyhow::Result<()> {
    let missing_marketplaces: Vec<String> = profile
        .marketplaces
        .keys()
        .filter(|name| !paths.marketplace_clone_dir(name).is_dir())
        .cloned()
        .collect();
    let missing_plugins: Vec<String> = profile
        .plugins
        .iter()
        .filter(|id| !paths.profile_vendor_dir(profile_key).join(id).exists())
        .cloned()
        .collect();

    if !missing_marketplaces.is_empty() || !missing_plugins.is_empty() {
        let approved = assume_yes
            || crate::progress::suspend(|| confirm(profile, &missing_marketplaces, &missing_plugins));
        if !approved {
            anyhow::bail!("provisioning declined by user");
        }
    }

    ensure_marketplace_clones(git, profile, paths)
}

/// Which commit-ish to check out before recording a marketplace's SHA (None = leave at HEAD).
/// On update, floating marketplaces move to HEAD while explicit `#ref`s stay pinned; otherwise
/// a previously-locked SHA is reproduced, falling back to the profile's explicit `#ref`.
fn checkout_target(
    update_floating: bool,
    locked: Option<&LockedMarketplace>,
    explicit_ref: &Option<String>,
) -> Option<String> {
    if update_floating {
        return explicit_ref.clone();
    }
    match locked {
        // An empty sha means a previous run found this marketplace wasn't a git checkout
        // (see the `is_repo` guard in `pin_marketplaces`); it's not a real pin to reproduce.
        Some(l) if !l.sha.is_empty() => Some(l.sha.clone()),
        _ => explicit_ref.clone(),
    }
}

pub fn pin_marketplaces<G: GitCli>(
    git: &G,
    profile: &Profile,
    mkt_install_dir: &dyn Fn(&str) -> PathBuf,
    lock: &mut Lockfile,
    update_floating: bool,
) -> anyhow::Result<()> {
    for (name, source) in &profile.marketplaces {
        let resolved = resolve_marketplace_sha(git, name, source, mkt_install_dir, lock, update_floating)?;
        lock.marketplaces
            .insert(name.clone(), LockedMarketplace { source: source.clone(), sha: resolved });
    }
    Ok(())
}

/// Resolve the commit SHA to lock for a single marketplace, advancing its checkout
/// first if needed: floating marketplaces are pulled to the remote HEAD on `update`,
/// pinned `#ref`s (or a previously-locked SHA) are checked out and left there. A
/// marketplace that isn't a git checkout is recorded unpinned (empty SHA).
fn resolve_marketplace_sha<G: GitCli>(
    git: &G,
    name: &str,
    source: &str,
    mkt_install_dir: &dyn Fn(&str) -> PathBuf,
    lock: &Lockfile,
    update_floating: bool,
) -> anyhow::Result<String> {
    let repo_ref = parse_repo_ref(source)?;
    let dir = mkt_install_dir(name);

    if !git.is_repo(&dir) {
        eprintln!(
            "WARNING: marketplace '{name}' at {} is not a git checkout; recording unpinned (not reproducible)",
            dir.display()
        );
        return Ok(String::new());
    }

    let target = checkout_target(update_floating, lock.marketplaces.get(name), &repo_ref.git_ref);
    if let Some(ref t) = target {
        git.checkout(&dir, t).with_context(|| {
            format!("checking out '{t}' for marketplace '{name}' ({source}) at {}", dir.display())
        })?;
    } else if update_floating {
        // Floating marketplace on `update`: advance the local checkout to the
        // remote default-branch HEAD before recording its SHA. Without this,
        // `head_sha` just re-reads whatever commit the checkout was first cloned
        // at, so a floating marketplace would never move. (Explicit `#ref`s take
        // the `checkout` branch above and are never advanced — they stay pinned.)
        git.advance_to_remote_head(&dir).with_context(|| {
            format!("advancing floating marketplace '{name}' ({source}) at {}", dir.display())
        })?;
    }
    git.head_sha(&dir)
        .with_context(|| format!("reading HEAD of marketplace '{name}' at {}", dir.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::GitCli;
    use std::cell::RefCell;
    use std::fs;
    use std::path::{Path, PathBuf};

    struct MockGit {
        cloned: RefCell<Vec<(String, PathBuf)>>,
        pulled: RefCell<Vec<PathBuf>>,
        advanced: RefCell<Vec<PathBuf>>,
        checkouts: RefCell<Vec<(PathBuf, String)>>,
        head: String,
        present: bool,
    }
    impl MockGit {
        fn new(head: &str) -> Self {
            MockGit {
                cloned: RefCell::new(vec![]), pulled: RefCell::new(vec![]),
                advanced: RefCell::new(vec![]),
                checkouts: RefCell::new(vec![]), head: head.into(), present: true,
            }
        }
    }
    impl GitCli for MockGit {
        fn advance_to_remote_head(&self, r: &Path) -> anyhow::Result<()> {
            self.advanced.borrow_mut().push(r.to_path_buf());
            Ok(())
        }
        fn clone(&self, url: &str, dest: &Path) -> anyhow::Result<()> {
            self.cloned.borrow_mut().push((url.to_string(), dest.to_path_buf()));
            fs::create_dir_all(dest)?;
            Ok(())
        }
        fn pull(&self, r: &Path) -> anyhow::Result<()> {
            self.pulled.borrow_mut().push(r.to_path_buf());
            Ok(())
        }
        fn head_sha(&self, _r: &Path) -> anyhow::Result<String> { Ok(self.head.clone()) }
        fn checkout(&self, r: &Path, gr: &str) -> anyhow::Result<()> {
            self.checkouts.borrow_mut().push((r.to_path_buf(), gr.to_string()));
            Ok(())
        }
        fn is_repo(&self, _r: &Path) -> bool { self.present }
        fn sparse_fetch(&self, _u: &str, _d: &Path, _s: &str) -> anyhow::Result<()> { Ok(()) }
    }

    fn profile(json: &str) -> crate::profile::Profile {
        crate::profile::Profile::from_json_str(json).unwrap()
    }

    #[test]
    fn reports_a_step_per_missing_marketplace_clone_only() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        // Pre-create m1's clone so only m2 is missing.
        fs::create_dir_all(paths.marketplace_clone_dir("m1")).unwrap();
        let p = profile(r#"{"name":"p","marketplaces":{"m1":"o/r","m2":"o/s"}}"#);
        let git = MockGit::new("sha1");

        let (rec, _g) = crate::progress::record();
        ensure_marketplace_clones(&git, &p, &paths).unwrap();

        assert_eq!(
            rec.events().as_slice(),
            &["step: cloning marketplace m2", "done: cloned m2"]
        );
    }

    #[test]
    fn reports_vendoring_progress_and_skips_already_vendored() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"a","source":"./a"},{"name":"b","source":"./b"}]}"#,
        ).unwrap();
        for name in ["a", "b"] {
            fs::create_dir_all(mkt_dir.join(name)).unwrap();
            fs::write(mkt_dir.join(name).join("f.txt"), "x").unwrap();
        }
        // a@m is already vendored, so only b@m should be reported.
        fs::create_dir_all(paths.profile_vendor_dir("p").join("a@m")).unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["a@m","b@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");

        let (rec, _g) = crate::progress::record();
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        assert_eq!(
            rec.events().as_slice(),
            &["step: vendoring b@m (2/2)", "done: vendored 1 plugin"]
        );
    }

    #[test]
    fn ensure_marketplace_clones_clones_missing_marketplaces_only() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"}}"#);
        let git = MockGit::new("sha1");

        ensure_marketplace_clones(&git, &p, &paths).unwrap();
        assert_eq!(git.cloned.borrow().len(), 1);
        assert!(paths.marketplace_clone_dir("m").is_dir());

        // Second call: already cloned, no-op.
        ensure_marketplace_clones(&git, &p, &paths).unwrap();
        assert_eq!(git.cloned.borrow().len(), 1);
    }

    #[test]
    fn vendors_relative_path_plugin_from_marketplace_clone() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"foo","source":"./skills/foo"}]}"#,
        ).unwrap();
        fs::create_dir_all(mkt_dir.join("skills").join("foo")).unwrap();
        fs::write(mkt_dir.join("skills").join("foo").join("SKILL.md"), "# foo").unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["foo@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        let vendored = paths.profile_vendor_dir("p").join("foo@m");
        assert!(vendored.join("SKILL.md").is_file());
    }

    #[test]
    fn vendors_external_repo_plugin_by_cloning_it_and_records_sha() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"ext","source":{"source":"github","repo":"owner/ext"}}]}"#,
        ).unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["ext@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        assert!(git.cloned.borrow().iter().any(|(url, _)| url.contains("owner/ext")));
        assert!(paths.profile_vendor_dir("p").join("ext@m").is_dir());
        let locked = lock.plugins.get("ext@m").expect("external plugin recorded in lock");
        assert_eq!(locked.source, "owner/ext");
        assert_eq!(locked.sha, "sha1");
    }

    #[test]
    fn vendors_git_subdir_plugin_copies_only_subpath_and_checks_out_pinned_sha() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"sub","source":{
                "source":"git-subdir",
                "url":"https://github.com/owner/repo.git",
                "path":"plugins/sub",
                "sha":"pinned123"
            }}]}"#,
        ).unwrap();

        // Pre-seed the "clone" with the subdir we want plus a sibling we don't.
        let ext_dir = paths.external_marketplace_dir("owner", "repo");
        fs::create_dir_all(ext_dir.join("plugins").join("sub")).unwrap();
        fs::write(ext_dir.join("plugins").join("sub").join("SKILL.md"), "# sub").unwrap();
        fs::create_dir_all(ext_dir.join("plugins").join("other")).unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["sub@m"]}"#);
        let git = MockGit::new("head_after_checkout");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        // checks out the pinned sha even though the repo dir already existed (force=false)
        assert_eq!(git.checkouts.borrow()[0], (ext_dir.clone(), "pinned123".to_string()));
        // only the named subpath is vendored, not the whole repo
        let vendored = paths.profile_vendor_dir("p").join("sub@m");
        assert!(vendored.join("SKILL.md").is_file());
        assert!(!vendored.join("other").exists());
        let locked = lock.plugins.get("sub@m").expect("recorded in lock");
        assert_eq!(locked.sha, "head_after_checkout");
        assert_eq!(locked.source, "https://github.com/owner/repo.git");
    }

    #[test]
    fn vendors_bare_url_plugin_same_as_external_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"superpowers","source":{"source":"url","url":"https://github.com/obra/superpowers.git"}}]}"#,
        ).unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["superpowers@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        assert!(git.cloned.borrow().iter().any(|(url, _)| url == "https://github.com/obra/superpowers.git"));
        assert!(paths.profile_vendor_dir("p").join("superpowers@m").is_dir());
        let locked = lock.plugins.get("superpowers@m").expect("recorded in lock");
        assert_eq!(locked.source, "https://github.com/obra/superpowers.git");
        assert_eq!(locked.sha, "sha1");
    }

    #[test]
    fn force_revendor_pulls_external_repo_and_updates_locked_sha() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"ext","source":{"source":"github","repo":"owner/ext"}}]}"#,
        ).unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["ext@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();
        assert!(git.pulled.borrow().is_empty()); // first vendor: cloned, not pulled

        vendor_plugins(&git, &p, "p", tmp.path(), &paths, true, &mut lock).unwrap();
        let ext_dir = paths.external_marketplace_dir("owner", "ext");
        assert_eq!(git.pulled.borrow().as_slice(), &[ext_dir]); // force: refreshed, not re-cloned
        assert_eq!(lock.plugins.get("ext@m").unwrap().sha, "sha1"); // MockGit's head_sha is fixed
    }

    #[test]
    fn vendors_loose_skill_and_generates_manifest() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let personal_skill = paths.claude_skills_dir().join("my-skill");
        fs::create_dir_all(&personal_skill).unwrap();
        fs::write(personal_skill.join("SKILL.md"), "# my-skill").unwrap();

        let p = profile(r#"{"name":"p","plugins":["my-skill@skills-dir"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        let vendored = paths.profile_vendor_dir("p").join("my-skill@skills-dir");
        assert!(vendored.join("SKILL.md").is_file());
        assert!(vendored.join(".claude-plugin").join("plugin.json").is_file());
        // original skill folder untouched:
        assert!(!personal_skill.join(".claude-plugin").exists());
    }

    #[test]
    fn skips_already_vendored_plugin_unless_forced() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let mkt_dir = paths.marketplace_clone_dir("m");
        fs::create_dir_all(mkt_dir.join(".claude-plugin")).unwrap();
        fs::write(
            mkt_dir.join(".claude-plugin").join("marketplace.json"),
            r#"{"plugins":[{"name":"foo","source":"./foo"}]}"#,
        ).unwrap();
        fs::create_dir_all(mkt_dir.join("foo")).unwrap();
        fs::write(mkt_dir.join("foo").join("a.txt"), "v1").unwrap();

        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r"},"plugins":["foo@m"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();

        // Marketplace clone changes (simulating a moved pin):
        fs::write(mkt_dir.join("foo").join("a.txt"), "v2").unwrap();

        // Without force: existing vendor copy is left alone (still v1).
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).unwrap();
        let vendored = paths.profile_vendor_dir("p").join("foo@m");
        assert_eq!(fs::read_to_string(vendored.join("a.txt")).unwrap(), "v1");

        // With force: re-vendored (now v2).
        vendor_plugins(&git, &p, "p", tmp.path(), &paths, true, &mut lock).unwrap();
        assert_eq!(fs::read_to_string(vendored.join("a.txt")).unwrap(), "v2");
    }

    #[test]
    fn errors_on_unresolvable_loose_skill() {
        let tmp = tempfile::tempdir().unwrap();
        let paths = crate::fs_paths::Paths::from_home(tmp.path().to_path_buf());
        let p = profile(r#"{"name":"p","plugins":["missing@skills-dir"]}"#);
        let git = MockGit::new("sha1");
        let mut lock = crate::lock::Lockfile::new("p");
        assert!(vendor_plugins(&git, &p, "p", tmp.path(), &paths, false, &mut lock).is_err());
    }

    #[test]
    fn pins_explicit_ref_and_records_sha() {
        let git = MockGit::new("sha_after_v1");
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        let p = profile(r#"{"name":"p","marketplaces":{"m":"o/r#v1"}}"#);
        pin_marketplaces(&git, &p, &dir, &mut lock, false).unwrap();
        assert_eq!(git.checkouts.borrow()[0], (PathBuf::from("/mkts/m"), "v1".to_string()));
        assert_eq!(lock.marketplaces.get("m").unwrap().sha, "sha_after_v1");
        assert_eq!(lock.marketplaces.get("m").unwrap().source, "o/r#v1");
    }

    #[test]
    fn uses_locked_sha_when_not_updating_floating() {
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r"}}"#).unwrap(); // floating source
        // after checkout(locked_sha), HEAD is at locked_sha, so head_sha() returns it too
        let git = MockGit::new("locked_sha");
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        lock.marketplaces.insert("m".into(),
            crate::lock::LockedMarketplace { source: "o/r".into(), sha: "locked_sha".into() });
        pin_marketplaces(&git, &profile, &dir, &mut lock, false).unwrap();
        // checked out the locked sha, not current head
        assert_eq!(git.checkouts.borrow()[0].1, "locked_sha");
        assert_eq!(lock.marketplaces.get("m").unwrap().sha, "locked_sha");
    }

    #[test]
    fn update_floating_moves_to_current_head() {
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r"}}"#).unwrap();
        let git = MockGit::new("new_head");
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        lock.marketplaces.insert("m".into(),
            crate::lock::LockedMarketplace { source: "o/r".into(), sha: "old".into() });
        pin_marketplaces(&git, &profile, &dir, &mut lock, true).unwrap();
        // floating + update_floating: no checkout to a pinned sha, record current head
        assert!(git.checkouts.borrow().is_empty());
        assert_eq!(lock.marketplaces.get("m").unwrap().sha, "new_head");
        // the checkout must be advanced to the remote default-branch HEAD first,
        // otherwise `head_sha` just re-reads the stale commit it was cloned at
        assert_eq!(git.advanced.borrow().as_slice(), &[PathBuf::from("/mkts/m")]);
    }

    #[test]
    fn locked_sha_wins_over_explicit_ref() {
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r#v2"}}"#).unwrap(); // explicit ref
        let git = MockGit::new("head_sha");
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        lock.marketplaces.insert("m".into(),
            crate::lock::LockedMarketplace { source: "o/r#v2".into(), sha: "locked".into() });
        pin_marketplaces(&git, &profile, &dir, &mut lock, false).unwrap();
        // locked sha wins over the explicit #ref
        assert_eq!(git.checkouts.borrow()[0].1, "locked");
        assert_eq!(lock.marketplaces.get("m").unwrap().sha, "head_sha");
    }

    #[test]
    fn non_git_marketplace_degrades_gracefully() {
        // The official marketplace is installed without a `.git`; pinning must be
        // skipped (recorded unpinned) instead of failing the whole launch.
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r"}}"#).unwrap();
        let mut git = MockGit::new("SHOULD_NOT_BE_USED");
        git.present = false; // dir exists but isn't a git checkout
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        pin_marketplaces(&git, &profile, &dir, &mut lock, false).unwrap();
        // no checkout attempted, and the lock records the marketplace as unpinned
        assert!(git.checkouts.borrow().is_empty());
        let locked = lock.marketplaces.get("m").expect("marketplace still recorded in lock");
        assert_eq!(locked.sha, "");
        assert_eq!(locked.source, "o/r");
    }

    #[test]
    fn update_floating_keeps_explicit_ref_pinned() {
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r#v3"}}"#).unwrap(); // explicit ref
        let git = MockGit::new("new_head");
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        lock.marketplaces.insert("m".into(),
            crate::lock::LockedMarketplace { source: "o/r#v3".into(), sha: "old_sha".into() });
        pin_marketplaces(&git, &profile, &dir, &mut lock, true).unwrap();
        // explicit ref stays pinned even when updating floating
        assert_eq!(git.checkouts.borrow()[0].1, "v3");
        // pinned refs must never move: no fetch/reset that would advance the branch
        assert!(git.advanced.borrow().is_empty());
    }

    #[test]
    fn stale_empty_locked_sha_is_not_checked_out() {
        // Regression: a marketplace previously recorded as non-git (empty sha, see
        // `non_git_marketplace_degrades_gracefully`) but now found to be a real git
        // checkout must not `git checkout ""` — that's an invalid pathspec and fails
        // the whole launch. The stale empty sha should be ignored, not treated as a pin.
        let profile = crate::profile::Profile::from_json_str(
            r#"{"name":"p","marketplaces":{"m":"o/r"}}"#).unwrap(); // no explicit ref
        let git = MockGit::new("head_sha"); // present: true (is a git checkout this time)
        let dir = |_n: &str| PathBuf::from("/mkts/m");
        let mut lock = crate::lock::Lockfile::new("p");
        lock.marketplaces.insert("m".into(),
            crate::lock::LockedMarketplace { source: "o/r".into(), sha: "".into() });
        pin_marketplaces(&git, &profile, &dir, &mut lock, false).unwrap();
        assert!(git.checkouts.borrow().is_empty());
        assert_eq!(lock.marketplaces.get("m").unwrap().sha, "head_sha");
    }
}