claude-smart 0.2.0

Cross-platform Claude Code smart session manager
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
//! `csm profiles edit` — interactive registry editor.
//!
//! A menu loop over [`ProfileMap`] using `std::io::stdin().read_line` (NO fzf
//! dependency, so it behaves identically on Windows-native where fzf may be
//! absent). The logic is split for testability:
//!
//! - **pure core** — [`apply_edit_action`]: takes `&mut ProfileMap` + an
//!   [`Action`] and returns an [`Outcome`]. No I/O, no clock, no stdin. Every
//!   branch (add / dup-reject / invalid-name / edit-dir / rename / delete /
//!   set-default) is unit-tested with scripted `Action` sequences.
//! - **I/O shell** — [`run_interactive`]: TTY gate, render, read an [`Action`]
//!   from stdin, apply, persist immediately. The only untested part (kept thin).
//!
//! Persistence: every mutating action calls [`ProfileMap::save`] right away so a
//! mid-session Ctrl-C never corrupts the registry. The default-NAME state file
//! is written via the same `write_default_profile` + platform-floor path that
//! `csm profiles use` uses, so the interactive `set-default` is identical to the
//! scriptable one.
//!
//! # Spec reference
//! `dave-environment docs/superpowers/specs/2026-06-19-csm-usage-and-interactive-cas-edit.md` §2.

use std::io::{self, Write};

use crate::account::profiles::ProfileMap;

// ─── action / outcome (pure-core vocabulary) ───────────────────────────────────

/// A single editor action, parsed from a menu choice + its prompted arguments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// Register a new profile. `dir = None` → synthesize `~/.claude.<name>`.
    Add { name: String, dir: Option<String> },
    /// Change an existing profile's dir.
    EditDir { name: String, dir: String },
    /// Rename a profile (its dir is preserved; default follows if it was default).
    Rename { from: String, to: String },
    /// Unregister a profile (dir retained on disk; refused if it is the default).
    Delete { name: String },
    /// Set the global default to `name` (state file + platform floor).
    SetDefault { name: String },
    /// Leave the loop.
    Quit,
}

/// What [`apply_edit_action`] decided. The I/O shell turns this into a message
/// + persistence; the unit tests assert on it directly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// The registry was mutated and should be persisted. `msg` is user-facing.
    /// `set_default` carries a profile name when the default-NAME state file
    /// must also be (re)written to it (rename-follows-default / set-default).
    Changed {
        msg: String,
        set_default: Option<String>,
    },
    /// Nothing changed; `msg` explains why (no-op or a recoverable user error).
    NoChange { msg: String },
    /// The user asked to quit.
    Quit,
}

// ─── pure core ─────────────────────────────────────────────────────────────────

/// Apply `action` to `profiles` in memory and report the [`Outcome`].
///
/// Pure: mutates only the passed map, performs no I/O (the caller persists on
/// `Changed`). Mirrors the validation rules of the scriptable `cas` verbs so the
/// interactive and non-interactive paths cannot diverge:
/// - add: valid name, reject duplicate.
/// - edit-dir: must exist.
/// - rename: valid new name, source exists, target free; if source was the
///   default, the new name is returned in `set_default`.
/// - delete: must exist; refuse if it is the current default.
/// - set-default: must exist (populated map); returned in `set_default`.
///
/// `mkdir` for add/edit-dir is the caller's job (an I/O side-effect); the core
/// only records the dir in the map.
pub fn apply_edit_action(profiles: &mut ProfileMap, action: Action) -> Outcome {
    match action {
        Action::Quit => Outcome::Quit,

        Action::Add { name, dir } => {
            if !ProfileMap::is_valid_name(&name) {
                return Outcome::NoChange {
                    msg: format!("invalid name '{name}' (allowed: letters, digits, . _ -)"),
                };
            }
            if profiles.contains(&name) {
                return Outcome::NoChange {
                    msg: format!("profile '{name}' already exists — use edit-dir to change it"),
                };
            }
            let resolved = synth_dir(&name, dir.as_deref());
            profiles.insert(name.clone(), resolved.clone());
            Outcome::Changed {
                msg: format!("added '{name}' → {resolved}"),
                set_default: None,
            }
        }

        Action::EditDir { name, dir } => {
            if !profiles.contains(&name) {
                return Outcome::NoChange {
                    msg: format!("no such profile '{name}'"),
                };
            }
            if dir.trim().is_empty() {
                return Outcome::NoChange {
                    msg: "dir cannot be empty".to_owned(),
                };
            }
            profiles.insert(name.clone(), dir.clone());
            Outcome::Changed {
                msg: format!("'{name}' → {dir}"),
                set_default: None,
            }
        }

        Action::Rename { from, to } => {
            if !profiles.contains(&from) {
                return Outcome::NoChange {
                    msg: format!("no such profile '{from}'"),
                };
            }
            if !ProfileMap::is_valid_name(&to) {
                return Outcome::NoChange {
                    msg: format!("invalid name '{to}' (allowed: letters, digits, . _ -)"),
                };
            }
            if from == to {
                return Outcome::NoChange {
                    msg: "name unchanged".to_owned(),
                };
            }
            if profiles.contains(&to) {
                return Outcome::NoChange {
                    msg: format!("target name '{to}' already exists"),
                };
            }
            let was_default = profiles.default_name() == from;
            let dir = profiles.remove(&from).unwrap_or_default();
            profiles.insert(to.clone(), dir);
            Outcome::Changed {
                msg: format!("renamed '{from}' → '{to}'"),
                // If the renamed profile was the global default, repoint it so
                // the default state file never dangles at a removed name.
                set_default: was_default.then(|| to.clone()),
            }
        }

        Action::Delete { name } => {
            if !profiles.contains(&name) {
                return Outcome::NoChange {
                    msg: format!("no such profile '{name}'"),
                };
            }
            if profiles.default_name() == name {
                return Outcome::NoChange {
                    msg: format!("'{name}' is the global default — set-default elsewhere first"),
                };
            }
            let dir = profiles.remove(&name).unwrap_or_default();
            Outcome::Changed {
                msg: format!("removed '{name}' (dir retained on disk: {dir})"),
                set_default: None,
            }
        }

        Action::SetDefault { name } => {
            // Populated map requires membership (empty/synth never reaches the
            // interactive editor — the TTY menu lists only existing profiles).
            if !profiles.contains(&name) {
                return Outcome::NoChange {
                    msg: format!("no such profile '{name}'"),
                };
            }
            Outcome::Changed {
                msg: format!("global default → {name}"),
                set_default: Some(name),
            }
        }
    }
}

/// Resolve the dir for an `Add`: explicit when non-empty, else `~/.claude.<name>`.
fn synth_dir(name: &str, dir: Option<&str>) -> String {
    match dir {
        Some(d) if !d.trim().is_empty() => d.trim().to_owned(),
        _ => dirs::home_dir()
            .unwrap_or_else(|| std::path::PathBuf::from("."))
            .join(format!(".claude.{name}"))
            .to_string_lossy()
            .into_owned(),
    }
}

// ─── I/O shell ─────────────────────────────────────────────────────────────────

/// Run the interactive editor loop. Requires a TTY on both stdin and stdout.
///
/// `profiles` is loaded fresh and mutable by the caller (`cmd_profiles`), so
/// writes persist. Returns `Ok(())` after the user quits (or EOF). Each mutating
/// action persists immediately via [`ProfileMap::save`]; `set-default` also writes
/// the default-NAME state file and applies the platform floor.
pub fn run_interactive(profiles: &mut ProfileMap) -> anyhow::Result<()> {
    if !is_interactive() {
        anyhow::bail!(
            "csm profiles edit: requires an interactive terminal \
             (use `csm profiles add|set|rm|use` for scripting)"
        );
    }

    let stdin = io::stdin();
    loop {
        render_menu(profiles);
        let names = profiles.names_sorted();
        let names: Vec<String> = names.into_iter().map(str::to_owned).collect();

        print!("> ");
        io::stdout().flush().ok();
        let mut line = String::new();
        if stdin.read_line(&mut line)? == 0 {
            // EOF (Ctrl-D) → quit cleanly.
            println!();
            break;
        }
        let choice = line.trim().to_ascii_lowercase();

        let action = match parse_choice(&choice, &names, &stdin) {
            Ok(Some(a)) => a,
            Ok(None) => continue, // unrecognized / blank → redraw
            Err(e) => {
                eprintln!("  {e}");
                continue;
            }
        };

        match apply_edit_action(profiles, action) {
            Outcome::Quit => break,
            Outcome::NoChange { msg } => println!("  {msg}"),
            Outcome::Changed { msg, set_default } => {
                profiles.save()?;
                if let Some(def) = set_default {
                    apply_default(&def, profiles)?;
                }
                // For add/edit-dir, create the dir on disk (best-effort).
                ensure_dirs(profiles);
                println!("  \u{2713} {msg}");
            }
        }
    }
    println!("done.");
    Ok(())
}

/// Map a menu key + interactive prompts into an [`Action`].
///
/// Returns `Ok(None)` for an unrecognized/blank choice (the loop redraws),
/// `Err` for a recoverable input error (the loop reports and redraws).
fn parse_choice(
    choice: &str,
    names: &[String],
    stdin: &io::Stdin,
) -> anyhow::Result<Option<Action>> {
    match choice {
        "q" | "quit" => Ok(Some(Action::Quit)),
        "a" | "add" => {
            let name = prompt(stdin, "  new profile name: ")?;
            if name.is_empty() {
                return Ok(None);
            }
            let dir = prompt(stdin, "  config dir (blank = ~/.claude.<name>): ")?;
            Ok(Some(Action::Add {
                name,
                dir: if dir.is_empty() { None } else { Some(dir) },
            }))
        }
        "e" | "edit" | "edit-dir" => {
            let name = pick(stdin, names, "edit-dir")?;
            match name {
                Some(name) => {
                    let dir = prompt(stdin, "  new config dir: ")?;
                    Ok(Some(Action::EditDir { name, dir }))
                }
                None => Ok(None),
            }
        }
        "r" | "rename" => {
            let from = pick(stdin, names, "rename")?;
            match from {
                Some(from) => {
                    let to = prompt(stdin, "  new name: ")?;
                    if to.is_empty() {
                        return Ok(None);
                    }
                    Ok(Some(Action::Rename { from, to }))
                }
                None => Ok(None),
            }
        }
        "d" | "delete" | "rm" => {
            let name = pick(stdin, names, "delete")?;
            Ok(name.map(|name| Action::Delete { name }))
        }
        "*" | "default" | "set-default" => {
            let name = pick(stdin, names, "set-default")?;
            Ok(name.map(|name| Action::SetDefault { name }))
        }
        _ => Ok(None),
    }
}

/// Prompt for a line of input, returning the trimmed string.
fn prompt(stdin: &io::Stdin, label: &str) -> anyhow::Result<String> {
    print!("{label}");
    io::stdout().flush().ok();
    let mut s = String::new();
    stdin.read_line(&mut s)?;
    Ok(s.trim().to_owned())
}

/// Prompt the user to pick a profile by number (1-based) for `verb`.
/// Returns `Ok(None)` on a blank/invalid choice.
fn pick(stdin: &io::Stdin, names: &[String], verb: &str) -> anyhow::Result<Option<String>> {
    if names.is_empty() {
        println!("  (no profiles to {verb})");
        return Ok(None);
    }
    let raw = prompt(stdin, &format!("  {verb} which # (blank to cancel)? "))?;
    if raw.is_empty() {
        return Ok(None);
    }
    match raw.parse::<usize>() {
        Ok(n) if n >= 1 && n <= names.len() => Ok(Some(names[n - 1].clone())),
        _ => {
            println!("  invalid selection '{raw}'");
            Ok(None)
        }
    }
}

/// Render the profile list + action menu.
fn render_menu(profiles: &ProfileMap) {
    let default = profiles.default_name();
    let names = profiles.names_sorted();
    println!();
    println!(
        "csm profiles edit — {} profile(s), default: {}",
        names.len(),
        if default.is_empty() {
            "(none)"
        } else {
            &default
        }
    );
    let current = std::env::var("CLAUDE_CONFIG_DIR").unwrap_or_default();
    for (i, name) in names.iter().enumerate() {
        let dir = profiles.get(name).unwrap_or("");
        let mut tags = String::new();
        if *name == default {
            tags.push_str(" [default]");
        }
        if !current.is_empty() && dir == current {
            tags.push_str(" [current shell]");
        }
        println!("  {}) {:<14} {}{}", i + 1, name, dir, tags);
    }
    if names.is_empty() {
        println!("  (none yet)");
    }
    println!("Actions: [a]dd  [e]dit-dir  [r]ename  [d]elete  [*]set-default  [q]uit");
}

/// Write the default-NAME state file + apply the platform floor (mirrors
/// `csm profiles use` / `cas use`).
fn apply_default(name: &str, profiles: &ProfileMap) -> anyhow::Result<()> {
    crate::cas::write_default_profile(name, profiles)?;
    if let Some(dir) = profiles.get(name) {
        if let Err(e) = crate::cas::platform::apply_global(name, dir) {
            eprintln!("  (platform floor warning: {e})");
        }
    }
    Ok(())
}

/// Best-effort: create each profile's config dir if missing.
fn ensure_dirs(profiles: &ProfileMap) {
    for (_, dir) in profiles.iter() {
        let _ = std::fs::create_dir_all(dir);
    }
}

/// True when both stdin and stdout are TTYs.
fn is_interactive() -> bool {
    use std::io::IsTerminal;
    io::stdin().is_terminal() && io::stdout().is_terminal()
}

// ─── tests ────────────────────────────────────────────────────────────────────

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

    fn registry(pairs: &[(&str, &str)]) -> ProfileMap {
        let mut m = HashMap::new();
        for (n, d) in pairs {
            m.insert((*n).to_owned(), (*d).to_owned());
        }
        ProfileMap(m)
    }

    #[test]
    fn add_valid_inserts() {
        let mut p = registry(&[]);
        let out = apply_edit_action(
            &mut p,
            Action::Add {
                name: "work".into(),
                dir: Some("/tmp/.claude.work".into()),
            },
        );
        assert!(matches!(
            out,
            Outcome::Changed {
                set_default: None,
                ..
            }
        ));
        assert_eq!(p.get("work"), Some("/tmp/.claude.work"));
    }

    #[test]
    fn add_blank_dir_synthesizes() {
        let mut p = registry(&[]);
        let out = apply_edit_action(
            &mut p,
            Action::Add {
                name: "work".into(),
                dir: None,
            },
        );
        assert!(matches!(out, Outcome::Changed { .. }));
        assert!(p.get("work").unwrap().ends_with(".claude.work"));
    }

    #[test]
    fn add_duplicate_rejected() {
        let mut p = registry(&[("work", "/tmp/work")]);
        let out = apply_edit_action(
            &mut p,
            Action::Add {
                name: "work".into(),
                dir: None,
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
        // unchanged
        assert_eq!(p.get("work"), Some("/tmp/work"));
    }

    #[test]
    fn add_invalid_name_rejected() {
        let mut p = registry(&[]);
        let out = apply_edit_action(
            &mut p,
            Action::Add {
                name: "has space".into(),
                dir: None,
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
        assert!(p.is_empty());
    }

    #[test]
    fn edit_dir_changes_existing() {
        let mut p = registry(&[("work", "/old")]);
        let out = apply_edit_action(
            &mut p,
            Action::EditDir {
                name: "work".into(),
                dir: "/new".into(),
            },
        );
        assert!(matches!(out, Outcome::Changed { .. }));
        assert_eq!(p.get("work"), Some("/new"));
    }

    #[test]
    fn edit_dir_missing_profile_no_change() {
        let mut p = registry(&[]);
        let out = apply_edit_action(
            &mut p,
            Action::EditDir {
                name: "x".into(),
                dir: "/d".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
    }

    #[test]
    fn edit_dir_empty_rejected() {
        let mut p = registry(&[("work", "/old")]);
        let out = apply_edit_action(
            &mut p,
            Action::EditDir {
                name: "work".into(),
                dir: "  ".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
        assert_eq!(p.get("work"), Some("/old"));
    }

    #[test]
    fn rename_moves_dir() {
        // Two profiles so the ambient `default` state file (read by
        // default_name()) does not implicitly make "work" the preferred default
        // — keeps this test about dir-movement, not default-following (covered
        // separately in rename_default_follows).
        let mut p = registry(&[("work", "/w"), ("keep", "/k")]);
        let out = apply_edit_action(
            &mut p,
            Action::Rename {
                from: "work".into(),
                to: "job".into(),
            },
        );
        // The dir moved and the source name is gone, regardless of whether the
        // global default happened to point at "work" in this environment.
        assert!(matches!(out, Outcome::Changed { .. }));
        assert_eq!(p.get("job"), Some("/w"));
        assert!(!p.contains("work"));
        assert!(p.contains("keep"));
    }

    #[test]
    fn rename_target_exists_rejected() {
        let mut p = registry(&[("work", "/w"), ("job", "/j")]);
        let out = apply_edit_action(
            &mut p,
            Action::Rename {
                from: "work".into(),
                to: "job".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
        // both intact
        assert_eq!(p.get("work"), Some("/w"));
        assert_eq!(p.get("job"), Some("/j"));
    }

    #[test]
    fn rename_invalid_target_rejected() {
        let mut p = registry(&[("work", "/w")]);
        let out = apply_edit_action(
            &mut p,
            Action::Rename {
                from: "work".into(),
                to: "a/b".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
        assert!(p.contains("work"));
    }

    #[test]
    fn rename_default_follows() {
        // A single-profile map: default_name() resolves to "work" (preferred).
        let mut p = registry(&[("work", "/w")]);
        assert_eq!(p.default_name(), "work");
        let out = apply_edit_action(
            &mut p,
            Action::Rename {
                from: "work".into(),
                to: "job".into(),
            },
        );
        match out {
            Outcome::Changed { set_default, .. } => {
                assert_eq!(
                    set_default.as_deref(),
                    Some("job"),
                    "default must follow rename"
                );
            }
            other => panic!("expected Changed, got {other:?}"),
        }
    }

    #[test]
    fn delete_non_default_ok() {
        // Two profiles; default resolves to alphabetical-first "a". Delete "b".
        let mut p = registry(&[("a", "/a"), ("b", "/b")]);
        assert_eq!(p.default_name(), "a");
        let out = apply_edit_action(&mut p, Action::Delete { name: "b".into() });
        assert!(matches!(out, Outcome::Changed { .. }));
        assert!(!p.contains("b"));
    }

    #[test]
    fn delete_default_refused() {
        let mut p = registry(&[("a", "/a"), ("b", "/b")]);
        assert_eq!(p.default_name(), "a");
        let out = apply_edit_action(&mut p, Action::Delete { name: "a".into() });
        assert!(matches!(out, Outcome::NoChange { .. }));
        assert!(p.contains("a"), "default must not be deleted");
    }

    #[test]
    fn delete_missing_no_change() {
        let mut p = registry(&[("a", "/a")]);
        let out = apply_edit_action(
            &mut p,
            Action::Delete {
                name: "nope".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
    }

    #[test]
    fn set_default_existing_returns_name() {
        let mut p = registry(&[("a", "/a"), ("b", "/b")]);
        let out = apply_edit_action(&mut p, Action::SetDefault { name: "b".into() });
        match out {
            Outcome::Changed { set_default, .. } => assert_eq!(set_default.as_deref(), Some("b")),
            other => panic!("expected Changed, got {other:?}"),
        }
    }

    #[test]
    fn set_default_missing_no_change() {
        let mut p = registry(&[("a", "/a")]);
        let out = apply_edit_action(
            &mut p,
            Action::SetDefault {
                name: "ghost".into(),
            },
        );
        assert!(matches!(out, Outcome::NoChange { .. }));
    }

    #[test]
    fn quit_is_quit() {
        let mut p = registry(&[]);
        assert_eq!(apply_edit_action(&mut p, Action::Quit), Outcome::Quit);
    }

    /// A scripted sequence: add two, set-default, rename the default, delete the
    /// other — exercising the pure core end to end without any I/O.
    #[test]
    fn scripted_lifecycle() {
        let mut p = registry(&[]);
        assert!(matches!(
            apply_edit_action(
                &mut p,
                Action::Add {
                    name: "alpha".into(),
                    dir: Some("/a".into())
                }
            ),
            Outcome::Changed { .. }
        ));
        assert!(matches!(
            apply_edit_action(
                &mut p,
                Action::Add {
                    name: "beta".into(),
                    dir: Some("/b".into())
                }
            ),
            Outcome::Changed { .. }
        ));
        // set-default beta
        match apply_edit_action(
            &mut p,
            Action::SetDefault {
                name: "beta".into(),
            },
        ) {
            Outcome::Changed { set_default, .. } => {
                assert_eq!(set_default.as_deref(), Some("beta"))
            }
            o => panic!("{o:?}"),
        }
        // rename alpha (non-default) → gamma; default does NOT follow.
        match apply_edit_action(
            &mut p,
            Action::Rename {
                from: "alpha".into(),
                to: "gamma".into(),
            },
        ) {
            // NOTE: default_name() here reads the real state file, which in a
            // test env is unlikely to be "alpha"; assert structurally instead.
            Outcome::Changed { .. } => {}
            o => panic!("{o:?}"),
        }
        assert!(p.contains("gamma"));
        assert!(p.contains("beta"));
        assert!(!p.contains("alpha"));
    }
}