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
use anyhow::Context;
use clap::{Parser, Subcommand};
use std::path::PathBuf;

mod bundled;
mod combine;
mod commands;
mod coord;
mod exe;
mod extends;
mod fs_paths;
mod git;
mod index;
mod launch;
mod lock;
mod pack;
mod profile;
mod progress;
mod provision;
mod resolve;
mod vendor;
mod vendor_fs;

#[derive(Parser)]
#[command(name = "claude-profile", version, about)]
struct Cli {
    #[command(subcommand)]
    command: Option<Command>,
    /// Profile name(s) to launch (when no subcommand is given). Give several to launch a
    /// combined session; each may be a profile name or a repo reference (owner/repo, URL).
    profiles: Vec<String>,
    /// Skip the provisioning confirmation prompt.
    #[arg(long)]
    yes: bool,
    /// Extra args forwarded to claude after `--`.
    #[arg(last = true)]
    extra: Vec<String>,
}

#[derive(Subcommand)]
enum Command {
    /// List available profiles and their sources.
    List,
    /// Show a profile's details and what it would install. TARGET is a profile
    /// name or a repo reference (owner/repo[#ref], https://…, or git@…).
    Show { target: String },
    /// Install or refresh a profile repo (owner/repo[#ref]) without launching.
    Install { spec: String },
    /// Check whether a newer claude-profile release is available (no subcommand), or
    /// git-pull profile repos and re-resolve floating marketplaces (`update profiles`).
    Update {
        #[command(subcommand)]
        target: Option<UpdateTarget>,
    },
    /// Show each profile's vendored plugins/skills under ~/.claude-profiles/store/.
    Status,
    /// Delete a personal profile or cloned pack.
    Remove { target: String },
    /// Scaffold a new profile in ~/.claude-profiles/.
    New { name: String },
    /// Run `claude plugin eval` against a plugin/skill target.
    Test {
        target: String,
        #[arg(long)]
        json: bool,
        #[arg(last = true)]
        extra: Vec<String>,
    },
    /// Search a local index of plugins across marketplaces. Returns profile-ready
    /// `plugin@marketplace` ids. First run auto-syncs; use --sync to rebuild.
    Find {
        query: Vec<String>,
        #[arg(long)]
        sync: bool,
        #[arg(long)]
        refresh_seeds: bool,
        #[arg(long)]
        json: bool,
        #[arg(long)]
        limit: Option<usize>,
        #[arg(long)]
        marketplace: Option<String>,
    },
    /// Remove the claude-profile binary (and optionally profile data).
    SelfUninstall {
        /// Also remove ~/.claude-profiles (all personal profiles, packs, locks).
        #[arg(long)]
        purge: bool,
    },
    /// Print a shell completion script for installed profile names (bash, zsh, fish,
    /// powershell), or write it to the standard location with --install.
    Completions {
        shell: commands::completions::Shell,
        /// Write the script to the standard completion path (and wire it up) instead
        /// of printing it to stdout.
        #[arg(long)]
        install: bool,
    },
    /// (hidden) Print installed profile names, one per line. Used by shell completion
    /// scripts generated by `completions`.
    #[command(hide = true, name = "profile-names")]
    ProfileNames,
    /// Install or remove a statusline showing the active profile.
    Statusline {
        #[command(subcommand)]
        action: commands::statusline::Action,
    },
    /// (hidden) Render the statusline line. Invoked by Claude Code itself via the
    /// `statusLine` command installed by `statusline install` — not for direct use.
    #[command(hide = true, name = "statusline-render")]
    StatuslineRender,
    /// Launch a coordinator session that can delegate tasks to worker sessions.
    Coordinate {
        /// Profile name(s) for the coordinator session.
        profiles: Vec<String>,
        /// Skip the provisioning confirmation prompt.
        #[arg(long)]
        yes: bool,
        /// Maximum number of workers running at once. Extra spawns queue.
        #[arg(long, default_value_t = 4)]
        max_workers: usize,
        /// Run workers headless even inside Herdr.
        #[arg(long)]
        headless: bool,
        /// Extra args forwarded to claude after `--`.
        #[arg(last = true)]
        extra: Vec<String>,
    },
    /// List coordinator runs, or remove finished workers' worktrees and finished runs' state.
    Runs {
        /// Remove the worktrees, branches, and state of runs that are no longer active.
        #[arg(long)]
        clean: bool,
        /// Limit --clean to one run.
        run_id: Option<String>,
    },
    /// (hidden) Serve the worker MCP tools for a coordinate run over stdio. Started by
    /// Claude Code from the coordinator's MCP config — not for direct use.
    #[command(hide = true, name = "workers-mcp")]
    WorkersMcp {
        #[arg(long)]
        run: String,
    },
}

#[derive(Subcommand)]
enum UpdateTarget {
    /// Git-pull profile repos and re-resolve floating marketplaces.
    Profiles {
        /// Fail if the lockfile is out of date instead of updating.
        #[arg(long)]
        frozen: bool,
    },
}

type LoadedProfiles = (Vec<(String, profile::Profile)>, Vec<(PathBuf, String)>);

fn load_all_profiles(
    paths: &fs_paths::Paths, cwd: &std::path::Path,
    env: Option<&std::path::Path>, bundled: &std::path::Path,
) -> LoadedProfiles {
    let mut out = Vec::new();
    let mut failed = Vec::new();
    for (name, path, _src) in resolve::list_available(paths, cwd, env, bundled) {
        match std::fs::read_to_string(&path) {
            Ok(body) => match profile::Profile::from_json_str(&body) {
                Ok(p) => out.push((name, p)),
                Err(e) => failed.push((path, e.to_string())),
            },
            Err(e) => failed.push((path, e.to_string())),
        }
    }
    (out, failed)
}

fn env_dir() -> Option<PathBuf> {
    std::env::var_os("CLAUDE_PROFILE_DIR").map(PathBuf::from)
}

fn run() -> anyhow::Result<i32> {
    let cli = Cli::parse();
    let _progress = progress::install();
    let paths = fs_paths::Paths::detect()?;
    let cwd = std::env::current_dir()?;
    let bundled = paths.bundled_profiles_dir();
    if let Err(e) = bundled::seed(&bundled, env!("CARGO_PKG_VERSION")) {
        eprintln!("warning: could not refresh bundled profiles in {}: {e}", bundled.display());
    }
    let env = env_dir();

    match cli.command {
        Some(command) => dispatch_command(command, &paths, &cwd, env.as_deref(), &bundled),
        None => handle_launch(&cli.profiles, cli.yes, &cli.extra, &paths, &cwd, env.as_deref(), &bundled),
    }
}

fn dispatch_command(
    command: Command,
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<i32> {
    match command {
        Command::List => {
            commands::list::run(paths, cwd, env, bundled)?;
            Ok(0)
        }
        Command::Show { target } => {
            commands::show::run(&target, paths, cwd, env, bundled)?;
            Ok(0)
        }
        Command::Install { spec } => {
            let dir = pack::install_pack(&git::RealGit, &spec, paths)?;
            progress::clear();
            println!("installed pack at {}", dir.display());
            Ok(0)
        }
        Command::Update { target: None } => {
            commands::check_update::run(&std::env::current_exe()?)?;
            Ok(0)
        }
        Command::Update { target: Some(UpdateTarget::Profiles { frozen }) } => {
            handle_update(frozen, paths, cwd, env, bundled)?;
            Ok(0)
        }
        Command::New { name } => {
            commands::new::run(&name, paths)?;
            Ok(0)
        }
        Command::Test { target, json, extra } => commands::test::run(&target, json, &extra),
        Command::Find { query, sync, refresh_seeds, json, limit, marketplace } => {
            commands::find::run(paths, &query, sync, refresh_seeds, json, limit, marketplace.as_deref())
        }
        Command::SelfUninstall { purge } => {
            commands::self_uninstall::run(paths, purge)?;
            Ok(0)
        }
        Command::Status => handle_status(paths, cwd, env, bundled),
        Command::Remove { target } => handle_remove(&target, paths, cwd, env, bundled),
        Command::Completions { shell, install } => {
            commands::completions::run(shell, install, paths)?;
            Ok(0)
        }
        Command::ProfileNames => {
            commands::list::run_names(paths, cwd, env, bundled)?;
            Ok(0)
        }
        Command::Statusline { action } => commands::statusline::run_action(action, paths, cwd),
        Command::StatuslineRender => {
            print!("{}", commands::statusline::render(paths, cwd));
            Ok(0)
        }
        Command::Coordinate { profiles, yes, max_workers, headless, extra } => {
            let opts = commands::coordinate::Options { profiles, yes, max_workers, headless, extra };
            commands::coordinate::run(&opts, paths, cwd, env, bundled)
        }
        Command::Runs { clean, run_id } => commands::runs::run(paths, clean, run_id.as_deref()),
        Command::WorkersMcp { run } => commands::coordinate::serve_workers(&run, paths, env, bundled),
    }
}

fn handle_status(
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<i32> {
    let (profiles, failed) = load_all_profiles(paths, cwd, env, bundled);
    for (path, err) in &failed {
        eprintln!("warning: could not parse profile {}: {err}", path.display());
    }
    commands::status::run(paths, &profiles)?;
    Ok(0)
}

fn handle_remove(
    target: &str,
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<i32> {
    let plan = commands::remove::remove_target(target, paths, cwd, env, bundled)?;
    commands::remove::apply(&plan)?;
    println!("removed {target}");
    Ok(0)
}

fn handle_update(
    frozen: bool,
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<()> {
    pack::update_all_packs(&git::RealGit, paths)?;
    let (profiles, failed) = load_all_profiles(paths, cwd, env, bundled);
    for (path, err) in &failed {
        eprintln!("warning: skipping unparseable profile {}: {err}", path.display());
    }
    let dir_lookup = |n: &str| paths.marketplace_clone_dir(n);
    if frozen {
        let mut triples = Vec::new();
        for (name, profile) in &profiles {
            let Some(profile) = resolve_extends_or_warn(name, profile, paths, cwd, env, bundled) else { continue };
            let resolved = resolve::resolve(name, paths, cwd, env, bundled)?;
            let lp = lock::lock_path(name, &resolved.path, &resolved.source, paths);
            let lf = lock::Lockfile::load(&lp)?.unwrap_or_else(|| lock::Lockfile::new(name));
            triples.push((name.clone(), profile, lf));
        }
        commands::update::frozen_check(&triples)?;
        progress::clear();
        println!("--frozen: all locks up to date");
    } else {
        let total = profiles.len();
        for (i, (name, profile)) in profiles.iter().enumerate() {
            let Some(profile) = resolve_extends_or_warn(name, profile, paths, cwd, env, bundled) else { continue };
            let missing = profile.marketplaces.keys().find(|mkt| !paths.marketplace_clone_dir(mkt).is_dir());
            if let Some(mkt) = missing {
                eprintln!(
                    "skipping '{name}': marketplace '{mkt}' not cloned yet (launch the profile once to provision it)"
                );
                continue;
            }
            let resolved = resolve::resolve(name, paths, cwd, env, bundled)?;
            let lp = lock::lock_path(name, &resolved.path, &resolved.source, paths);
            let mut lf = lock::Lockfile::load(&lp)?.unwrap_or_else(|| lock::Lockfile::new(name));
            progress::step(&format!("re-resolving {name} ({}/{total})", i + 1));
            commands::update::reresolve_profile(&git::RealGit, &profile, name, cwd, paths, &dir_lookup, &mut lf)
                .with_context(|| format!("updating profile '{name}'"))?;
            lf.save(&lp)?;
            let mkt_count = profile.marketplaces.len();
            let plugin_count = profile.plugins.len();
            let mkt_plural = if mkt_count == 1 { "marketplace" } else { "marketplaces" };
            let plugin_plural = if plugin_count == 1 { "plugin" } else { "plugins" };
            progress::done(&format!(
                "{name} — {mkt_count} {mkt_plural}, {plugin_count} {plugin_plural}"
            ));
        }
    }
    Ok(())
}

/// Resolve `extends` for a profile, printing a warning and returning `None`
/// (so the caller can skip it) instead of aborting the whole `update` run.
fn resolve_extends_or_warn(
    name: &str,
    profile: &profile::Profile,
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> Option<profile::Profile> {
    match extends::resolve_extends(profile.clone(), &|parent| {
        Ok(resolve::resolve(parent, paths, cwd, env, bundled)?.profile)
    }) {
        Ok(p) => Some(p),
        Err(e) => {
            eprintln!("warning: skipping '{name}': could not resolve extends: {e}");
            None
        }
    }
}

/// Dispatch a launch: no args prints help, otherwise resolve the target(s) and launch.
fn handle_launch(
    names: &[String],
    assume_yes: bool,
    extra: &[String],
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<i32> {
    if names.is_empty() {
        use clap::CommandFactory;
        Cli::command().print_help()?;
        println!();
        return Ok(0);
    }
    let target = resolve_launch(names, paths, cwd, env, bundled)?;
    provision_pin_launch(&target.profile, &target.key, &target.lock_file, assume_yes, extra, cwd, paths)
}

/// A launch target ready for provisioning: the effective profile, its key, and its lockfile.
pub(crate) struct LaunchTarget {
    pub(crate) profile: profile::Profile,
    pub(crate) key: String,
    pub(crate) lock_file: PathBuf,
}

/// Resolve one profile (with the owner/repo sugar) or several (merged into a combined
/// profile with a lockfile under `~/.claude-profiles/locks/`).
pub(crate) fn resolve_launch(
    names: &[String],
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<LaunchTarget> {
    match names {
        [] => anyhow::bail!("no profile names given"),
        [name] => {
            let one = resolve_one(name, paths, cwd, env, bundled)?;
            let lock_file = lock::lock_path(&one.key, &one.path, &one.source, paths);
            Ok(LaunchTarget { profile: one.profile, key: one.key, lock_file })
        }
        _ => {
            let mut resolved = Vec::new();
            for name in names {
                let t = resolve_one(name, paths, cwd, env, bundled)?;
                resolved.push((t.key, t.profile));
            }
            let combined = combine::combine_profiles(&resolved)?;
            let key = combined.name.clone();
            let lock_file = paths.locks_dir().join(format!("{key}.lock"));
            Ok(LaunchTarget { profile: combined, key, lock_file })
        }
    }
}

/// A resolved launch target: its display key, `extends`-expanded profile, and the source
/// file/origin (used to place a single profile's lockfile).
struct ResolvedTarget {
    key: String,
    profile: profile::Profile,
    path: std::path::PathBuf,
    source: resolve::ProfileSource,
}

/// Resolve one launch target (a profile name, or an owner/repo/URL installed as a pack).
fn resolve_one(
    name: &str,
    paths: &fs_paths::Paths,
    cwd: &std::path::Path,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<ResolvedTarget> {
    let key = if name.contains('/') {
        let dir = pack::install_pack(&git::RealGit, name, paths)?;
        pack::default_profile_name(&dir)?
    } else {
        name.to_string()
    };
    let resolved = resolve::resolve(&key, paths, cwd, env, bundled)?;
    let (path, source) = (resolved.path.clone(), resolved.source.clone());
    let profile = extends::resolve_extends(resolved.profile, &|parent| {
        Ok(resolve::resolve(parent, paths, cwd, env, bundled)?.profile)
    })?;
    Ok(ResolvedTarget { key, profile, path, source })
}

/// Shared launch tail: provision and pin the profile, then spawn `claude` for the session
/// with the vendored plugin dirs.
fn provision_pin_launch(
    profile: &profile::Profile,
    key: &str,
    lock_file: &std::path::Path,
    assume_yes: bool,
    extra: &[String],
    cwd: &std::path::Path,
    paths: &fs_paths::Paths,
) -> anyhow::Result<i32> {
    provision_and_pin(profile, key, lock_file, assume_yes, cwd, paths)?;
    let args = launch::build_args(profile, key, paths, extra)?;
    progress::clear();
    launch::spawn(key, &args)
}

/// Resolve the named profiles and provision and pin them without launching, so a later
/// `claude-profile <names> --yes` starts without first-launch work.
pub(crate) fn prepare_profiles(
    names: &[String],
    cwd: &std::path::Path,
    paths: &fs_paths::Paths,
    env: Option<&std::path::Path>,
    bundled: &std::path::Path,
) -> anyhow::Result<()> {
    let target = resolve_launch(names, paths, cwd, env, bundled)?;
    provision_and_pin(&target.profile, &target.key, &target.lock_file, true, cwd, paths)
}

/// Provision the profile (cloning marketplaces / prompting as needed), pin its marketplaces
/// into `lock_file`, and vendor plugins against the pinned checkout.
fn provision_and_pin(
    profile: &profile::Profile,
    key: &str,
    lock_file: &std::path::Path,
    assume_yes: bool,
    cwd: &std::path::Path,
    paths: &fs_paths::Paths,
) -> anyhow::Result<()> {
    provision::provision(&git::RealGit, profile, key, cwd, paths, assume_yes)
        .with_context(|| format!("provisioning profile '{key}'"))?;

    let mut lock = lock::Lockfile::load(lock_file)?.unwrap_or_else(|| lock::Lockfile::new(key));
    let dir_lookup = |n: &str| paths.marketplace_clone_dir(n);
    provision::pin_marketplaces(&git::RealGit, profile, &dir_lookup, &mut lock, false)
        .with_context(|| format!("pinning marketplaces for profile '{key}'"))?;

    provision::vendor_plugins(&git::RealGit, profile, key, cwd, paths, false, &mut lock)
        .with_context(|| format!("vendoring plugins for profile '{key}'"))?;

    if let Some(parent) = lock_file.parent() {
        std::fs::create_dir_all(parent)?;
    }
    lock.save(lock_file)
}

fn main() {
    match run() {
        Ok(code) => std::process::exit(code),
        Err(e) => {
            eprintln!("error: {e:#}");
            std::process::exit(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write_profiles(dir: &std::path::Path, names: &[&str]) {
        for n in names {
            std::fs::write(dir.join(format!("{n}.json")), format!("{{\"name\": \"{n}\"}}")).unwrap();
        }
    }

    #[test]
    fn resolve_launch_combines_two_profiles() {
        let home = tempfile::tempdir().unwrap();
        let env = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        write_profiles(env.path(), &["a", "b"]);
        let paths = fs_paths::Paths::from_home(home.path().to_path_buf());
        let names = vec!["a".to_string(), "b".to_string()];
        let target =
            resolve_launch(&names, &paths, cwd.path(), Some(env.path()), &paths.bundled_profiles_dir()).unwrap();
        let a = profile::Profile::from_json_str(r#"{"name": "a"}"#).unwrap();
        let b = profile::Profile::from_json_str(r#"{"name": "b"}"#).unwrap();
        let combined = combine::combine_profiles(&[("a".into(), a), ("b".into(), b)]).unwrap();
        assert_eq!(target.key, combined.name);
        assert_eq!(target.lock_file, paths.locks_dir().join(format!("{}.lock", target.key)));
    }

    #[test]
    fn resolve_launch_single_uses_profile_lock() {
        let home = tempfile::tempdir().unwrap();
        let env = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        write_profiles(env.path(), &["a"]);
        let paths = fs_paths::Paths::from_home(home.path().to_path_buf());
        let names = vec!["a".to_string()];
        let target =
            resolve_launch(&names, &paths, cwd.path(), Some(env.path()), &paths.bundled_profiles_dir()).unwrap();
        assert_eq!(target.key, "a");
        assert_eq!(target.profile.name, "a");
    }

    #[test]
    fn resolve_launch_rejects_empty_names() {
        let home = tempfile::tempdir().unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let paths = fs_paths::Paths::from_home(home.path().to_path_buf());
        assert!(resolve_launch(&[], &paths, cwd.path(), None, &paths.bundled_profiles_dir()).is_err());
    }
}