claude-smart 0.2.2

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
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
//! `csm cas` — Claude-as (CAS) profile switcher.
//!
//! The binary half of the `cas` shell function. Because a child process cannot
//! mutate its parent shell's environment, the shell shim evals the single line
//! we print:
//!
//! ```zsh
//! cas() { eval "$(command csm cas --eval --shell zsh -- "$@")"; }
//! ```
//! ```pwsh
//! function cas { Invoke-Expression (csm cas --eval --shell pwsh -- @args) }
//! ```
//!
//! `eval_emit()` (this module) handles:
//!   - state-file write (`~/.config/claude-as/default`)
//!   - macOS `launchctl setenv` floor update (via `platform::launchctl_setenv`)
//!   - Windows HKCU\Environment write + `WM_SETTINGCHANGE` broadcast (via `platform::hkcu_setenv`)
//!   - printing the one line the parent shell must eval
//!
//! ## Error propagation through `eval`
//!
//! `eval "$(command csm cas ...)"` captures stdout. If `csm` exits non-zero but
//! emits nothing to stdout, the exit code is **lost** — `eval ""` succeeds. To
//! surface errors to the calling shell, `eval_emit` emits a shell error snippet
//! for terminal error cases (unknown profile, missing previous profile, etc.):
//!
//! - **zsh**: `>&2 printf '%s\n' '<message>'; false`
//! - **pwsh**: `Write-Error '<message>'; exit 1`
//!
//! When `eval` runs these, the shell function returns a non-zero exit code and
//! the message appears on stderr — matching the behavior of the original zsh
//! `claude-as` function.
//!
//! `default_profile(&ProfileMap)` reads `~/.config/claude-as/default` and
//! validates the token against the live registry (no hardcoded profile names),
//! falling back to the registry's `preferred_default`. The management verbs
//! (`list`/`add`/`set`/`remove`/`use`) author the registry itself via
//! `manage_emit` — csm owns the full profile lifecycle, not just consumption.
//!
//! # Spec reference
//! `docs/superpowers/specs/2026-06-17-csm-rust-port-design.md` §2 "CAS integration"
//! `docs/superpowers/specs/2026-06-18-csm-rust-crate-scaffold.md` §3 `cas/mod.rs`

use std::io;
use std::path::PathBuf;

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

pub mod edit;
pub mod platform;

// ─── Op ──────────────────────────────────────────────────────────────────────

/// The parsed CAS operation; mirrors the `cas` shell function's argument forms.
///
/// ```text
/// cas <profile>        → Switch to the named profile in the live shell
/// cas -                → Switch back to the previous per-shell profile (handled
///                         entirely by the shim; binary receives the resolved name)
/// cas -g <profile>     → Global: write state file + launchctl/HKCU side-effects
/// cas resync           → Re-read state file and re-export in the live shell
/// cas status           → Print current / default / available (no export)
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op {
    /// `cas <profile>` — per-shell switch: emit export, no state-file write.
    Switch { profile: String },

    /// `cas -` — toggle to the previous per-shell profile.
    /// The binary receives the literal `"-"` and emits a shell error snippet
    /// because `_CLAUDE_AS_PREV` is a non-exported zsh variable the child
    /// cannot read. The shim must handle `-` specially if it needs to preserve
    /// the previous-profile semantic; the binary's job is to emit the error.
    Minus,

    /// `cas -g <profile>` — global switch: write state file + platform setenv
    /// + emit export for the live shell.
    Global { profile: String },

    /// `cas resync` — re-read state file, emit export of its current value.
    Resync,

    /// `cas status [--print-current]` — informational; prints to stdout but
    /// emits no eval-able export line. `print_current` selects the one-liner
    /// form used by `_claude_as_current_profile` in the shim.
    Status { print_current: bool },

    // ─── registry management (non-eval; routed to `manage_emit`) ───────────────
    /// `cas list` — print the configured profiles (name → dir, default-marked).
    List,

    /// `cas add <name> [<dir>]` — register a profile, creating its dir. `dir`
    /// defaults to `~/.claude.<name>`. Errors if the name already exists.
    Add { name: String, dir: Option<String> },

    /// `cas set <name> <dir>` — register/overwrite a profile + create the dir.
    Set { name: String, dir: String },

    /// `cas remove <name>` / `cas rm <name>` — unregister a profile (the dir is
    /// retained on disk). Refused when `name` is the current global default.
    Remove { name: String },

    /// `cas use <name>` — set the global default (state file + platform floor),
    /// without emitting a per-shell export. The scriptable analogue of `-g`.
    SetDefault { name: String },

    /// `csm profiles edit` — interactive registry editor (TTY-gated menu loop).
    /// Non-eval; routed to `manage_emit`.
    Edit,
}

// ─── Shell ───────────────────────────────────────────────────────────────────

/// Which shell is evaluating the output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shell {
    Zsh,
    Pwsh,
}

impl Shell {
    /// Parse `"zsh"` or `"pwsh"` (case-insensitive).
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "zsh" | "bash" | "sh" => Some(Shell::Zsh),
            "pwsh" | "powershell" => Some(Shell::Pwsh),
            _ => None,
        }
    }

    /// Emit the `export` / `$env:` one-liner for the given dir.
    ///
    /// The path is single-quoted (safe for paths with spaces on both shells;
    /// single quotes in zsh/bash do not expand variables or globs; pwsh treats
    /// single-quoted strings as literals).
    pub fn export_line(&self, dir: &str) -> String {
        match self {
            Shell::Zsh => format!("export CLAUDE_CONFIG_DIR='{dir}'"),
            Shell::Pwsh => format!("$env:CLAUDE_CONFIG_DIR = '{dir}'"),
        }
    }

    /// Emit a shell snippet that prints `msg` to stderr and returns non-zero.
    ///
    /// This is used by `eval_emit` for terminal error cases so that `eval "$(csm
    /// cas ...)"` correctly surfaces the error to the calling shell even though
    /// `eval` discards the binary's exit code.
    ///
    /// - **zsh/bash**: `>&2 printf '%s\n' '<msg>'; false`
    /// - **pwsh**: `Write-Error '<msg>'; exit 1`
    ///
    /// Single quotes in `msg` are escaped per each shell's rules:
    /// - zsh: `'` → `'\''` (end-quote, literal-quote, re-open-quote)
    /// - pwsh: `'` → `''` (double-up)
    pub fn error_snippet(&self, msg: &str) -> String {
        match self {
            Shell::Zsh => {
                let escaped = msg.replace('\'', "'\\''");
                format!(">&2 printf '%s\\n' '{escaped}'; false")
            }
            Shell::Pwsh => {
                let escaped = msg.replace('\'', "''");
                format!("Write-Error '{escaped}'; exit 1")
            }
        }
    }
}

// ─── default state-file path ─────────────────────────────────────────────────

/// `~/.config/claude-as/default` — the global profile state file.
pub fn default_state_file() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".config")
        .join("claude-as")
        .join("default")
}

// ─── default_profile — REAL implementation ───────────────────────────────────

/// Read the global default profile name, validated against the live registry.
///
/// Delegates to [`ProfileMap::default_name`] — the binary carries **no**
/// hardcoded profile names. Resolution order (see that method): configured
/// state-file token, else the registry's `preferred_default`, else `""`.
/// On an empty map (toss/first-boot) a non-empty state-file token is trusted
/// as-is so the synthesize path (`~/.claude.<token>`) still works.
pub fn default_profile(profiles: &ProfileMap) -> String {
    profiles.default_name()
}

/// Write `profile` to the global default state file.
///
/// Creates the parent directory if needed. Validates against the live registry
/// (`profiles`) before writing — an empty map (toss/synth) accepts any non-empty
/// token; a populated map requires `profile` to be a configured name. Returns
/// `Err` for an unknown profile so callers get a clear error rather than a
/// silently corrupted state file.
pub fn write_default_profile(profile: &str, profiles: &ProfileMap) -> io::Result<()> {
    let ok = if profiles.is_empty() {
        !profile.is_empty()
    } else {
        profiles.contains(profile)
    };
    if !ok {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "cas: unknown profile '{profile}' — configured: {}",
                profiles.names_sorted().join(", ")
            ),
        ));
    }
    let path = default_state_file();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    // One trailing newline (matches the zsh `print -- "$profile" >` idiom;
    // readers trim whitespace anyway).
    std::fs::write(&path, format!("{profile}\n"))
}

// ─── eval_emit ───────────────────────────────────────────────────────────────

/// Perform the CAS operation side-effects and print the eval-able output.
///
/// The caller (`cmd_cas` in `main.rs`) passes the parsed `Shell` and `Op`.
/// Output contract:
///
/// ## Normal paths (export line)
/// - `Op::Switch` / `Op::Global` / `Op::Resync`: print exactly **one** line
///   (the `export`/`$env:` line) to stdout. The parent shell evals it.
///
/// ## Informational path
/// - `Op::Status` (without `--print-current`): print human-readable status
///   directly to stdout — **not** eval-able; the shim must not eval this.
/// - `Op::Status { print_current: true }`: print the export of the global
///   default so the shim can eval it to set `_claude_as_current_profile`.
///
/// ## Error paths (emit shell error snippet)
/// - `Op::Minus`: emit a shell error snippet because `_CLAUDE_AS_PREV` is a
///   non-exported zsh variable the binary cannot read.
/// - Unknown profile: emit a shell error snippet instead of returning `Err`,
///   so that `eval "$(csm cas ...)"` correctly surfaces the error to the
///   calling shell.
///
/// # Platform side-effects (Op::Global only)
/// `Op::Global` also calls `platform::launchctl_setenv` (macOS) or
/// `platform::hkcu_setenv` (Windows) so GUI and launchd / non-shell
/// processes pick up the new default immediately.
///
/// # Return value
/// Returns `Err` only for I/O errors (state-file write failure, launchctl
/// exec failure, etc.) — NOT for user-level errors like unknown profile.
/// User-level errors are surfaced via the emitted shell error snippet.
pub fn eval_emit(shell: Shell, op: &Op, profiles: &ProfileMap) -> anyhow::Result<()> {
    match op {
        Op::Switch { profile } => {
            match resolve_profile(profile, profiles) {
                Ok(dir) => {
                    println!("{}", shell.export_line(&dir));
                }
                Err(e) => {
                    // Emit an error snippet so eval surfaces the error even
                    // though it discards the binary's exit code.
                    println!("{}", shell.error_snippet(&e.to_string()));
                }
            }
        }

        Op::Minus => {
            // _CLAUDE_AS_PREV is a non-exported zsh variable — the binary
            // cannot read it. Emit a shell error snippet that mirrors the zsh
            // `claude-as: no previous profile to toggle to` message.
            //
            // Reproduces zsh claude-as.zsh lines 79-84:
            //   if [[ -z "${_CLAUDE_AS_PREV:-}" ]]; then
            //     print -u2 "claude-as: no previous profile to toggle to"
            //     return 1
            //   fi
            println!(
                "{}",
                shell.error_snippet("claude-as: no previous profile to toggle to")
            );
        }

        Op::Global { profile } => {
            match resolve_profile(profile, profiles) {
                Ok(dir) => {
                    // 1. Write the state file.
                    write_default_profile(profile, profiles)?;
                    // 2. Platform-specific side-effect (launchctl / HKCU).
                    //    Soft failure: launchctl error does not abort the export.
                    if let Err(e) = platform::apply_global(profile, &dir) {
                        eprintln!("cas: platform setenv warning: {e}");
                    }
                    // 3. Emit the per-shell export line.
                    println!("{}", shell.export_line(&dir));
                    // 4. Print the informational message to stderr (matches
                    //    zsh `print "global default → $profile ($dir)"` which
                    //    goes to stdout in the original but is printed before
                    //    eval — here we print to stderr so it doesn't confuse
                    //    the eval).
                    eprintln!("global default → {profile} ({dir})");
                    eprintln!("(new shells follow this via ~/.zshenv guard; running claude sessions keep their captured paths)");
                }
                Err(e) => {
                    println!("{}", shell.error_snippet(&e.to_string()));
                }
            }
        }

        Op::Resync => {
            // Re-read the state file and emit the export for its current value.
            // Reproduces zsh claude-as.zsh lines 68-76:
            //   def=$(_claude_as_default_profile)
            //   def_dir="${CLAUDE_PROFILES[$def]}"
            //   _CLAUDE_AS_PREV=$(_claude_as_current_profile)
            //   export CLAUDE_CONFIG_DIR="$def_dir"
            //   print "shell → $def ($def_dir)"
            let profile = default_profile(profiles);
            match resolve_profile(&profile, profiles) {
                Ok(dir) => {
                    println!("{}", shell.export_line(&dir));
                    eprintln!("shell → {profile} ({dir})");
                }
                Err(e) => {
                    println!("{}", shell.error_snippet(&e.to_string()));
                }
            }
        }

        Op::Status { print_current } => {
            if *print_current {
                // 1-line form for `_claude_as_current_profile` shim helper.
                // The shim uses:
                //   _claude_as_current_profile() {
                //     command csm cas --eval --shell zsh -- status --print-current
                //   }
                // and evals the result to get the current profile name (not the
                // full export). We emit the profile name as a simple echo so
                // `eval` sets nothing (the shim reads it as output, not as a
                // command to eval).
                //
                // Actually the shim design says eval it — so we emit the profile
                // name as a zsh `echo` statement. But the comment in the scaffold
                // says this is for reading the current profile. Per the spec §3:
                //   _claude_as_current_profile() { command csm cas --eval --shell
                //     zsh -- status --print-current; }
                // This is NOT wrapped in eval — it's called directly. So we just
                // print the profile name (the one word the shell captures via
                // command substitution).
                let current_dir = std::env::var("CLAUDE_CONFIG_DIR").unwrap_or_default();
                let profile_name = if current_dir.is_empty() {
                    "unknown".to_owned()
                } else {
                    profiles
                        .iter()
                        .find(|(_, dir)| *dir == current_dir.as_str())
                        .map(|(name, _)| name.to_owned())
                        .unwrap_or_else(|| "unknown".to_owned())
                };
                println!("{profile_name}");
            } else {
                // Full status display — NOT eval-able.
                // Reproduces zsh claude-as.zsh lines 87-110 (no-args branch).
                print_status(shell, profiles)?;
            }
        }

        // Registry-management ops are handled by `manage_emit`, not the eval
        // path. `cmd_cas` routes them away from here; this arm only guards the
        // type system (and surfaces a clear error if routing ever regresses).
        Op::List
        | Op::Add { .. }
        | Op::Set { .. }
        | Op::Remove { .. }
        | Op::SetDefault { .. }
        | Op::Edit => {
            anyhow::bail!("internal: {op:?} is a management op — route to manage_emit");
        }
    }
    Ok(())
}

/// Perform a registry-management op (`list`/`add`/`set`/`remove`/`use`) and
/// print human-readable output. These ops are **non-eval** — the shim calls
/// `csm cas <verb>` directly (no `--eval`), so we print status text, not an
/// export line. The caller (`cmd_cas`) routes here when `eval_mode == false`
/// and the op is not `Status`.
///
/// `profiles` is loaded fresh (and mutably) by the caller so writes persist.
pub fn manage_emit(op: &Op, profiles: &mut ProfileMap) -> anyhow::Result<()> {
    match op {
        Op::List => {
            print_status(Shell::Zsh, profiles)?;
        }

        Op::Add { name, dir } => {
            if !ProfileMap::is_valid_name(name) {
                anyhow::bail!(
                    "add: invalid profile name '{name}' (allowed: letters, digits, . _ -)"
                );
            }
            if profiles.contains(name) {
                anyhow::bail!(
                    "add: profile '{name}' already exists ({}). Use `csm profiles set {name} <dir>` to change its dir.",
                    profiles.get(name).unwrap_or("")
                );
            }
            let dir = resolve_new_dir(name, dir.as_deref());
            std::fs::create_dir_all(&dir)
                .map_err(|e| anyhow::anyhow!("add: cannot create dir '{dir}': {e}"))?;
            profiles.insert(name.clone(), dir.clone());
            profiles.save()?;
            eprintln!("added profile '{name}' → {dir}");
        }

        Op::Set { name, dir } => {
            if !ProfileMap::is_valid_name(name) {
                anyhow::bail!(
                    "set: invalid profile name '{name}' (allowed: letters, digits, . _ -)"
                );
            }
            if dir.is_empty() {
                anyhow::bail!("set: <dir> is required");
            }
            std::fs::create_dir_all(dir)
                .map_err(|e| anyhow::anyhow!("set: cannot create dir '{dir}': {e}"))?;
            let prev = profiles.insert(name.clone(), dir.clone());
            profiles.save()?;
            match prev {
                Some(old) if old != *dir => eprintln!("set profile '{name}' → {dir} (was {old})"),
                _ => eprintln!("set profile '{name}' → {dir}"),
            }
        }

        Op::Remove { name } => {
            if !profiles.contains(name) {
                anyhow::bail!(
                    "remove: no such profile '{name}' — configured: {}",
                    profiles.names_sorted().join(", ")
                );
            }
            // Refuse to orphan the global default (the dir on disk is retained).
            if profiles.default_name() == *name {
                anyhow::bail!(
                    "remove: '{name}' is the global default — set the default elsewhere first \
                     (`csm profiles use <other>`)"
                );
            }
            let dir = profiles.remove(name).unwrap_or_default();
            profiles.save()?;
            eprintln!("removed profile '{name}' (dir retained on disk: {dir})");
        }

        Op::SetDefault { name } => {
            // Validate against the live registry, write the state file, and set
            // the platform floor (launchctl/HKCU) so new shells + GUI/launchd
            // pick it up. Unlike `-g` this emits NO per-shell export line.
            write_default_profile(name, profiles)?;
            let dir = resolve_profile(name, profiles)?;
            if let Err(e) = platform::apply_global(name, &dir) {
                eprintln!("cas: platform setenv warning: {e}");
            }
            eprintln!("global default → {name} ({dir})");
            eprintln!("(new shells + GUI/launchd follow this; your current shell keeps its profile until you run `cas {name}` or open a new shell)");
        }

        Op::Edit => {
            // Interactive editor — loads/saves the registry through the same
            // `profiles` map (the caller passes it mutable so writes persist).
            edit::run_interactive(profiles)?;
        }

        // Switch/Global/Resync/Minus/Status are handled by `eval_emit`; routing
        // in `cmd_cas` guarantees they never reach here.
        Op::Switch { .. } | Op::Global { .. } | Op::Resync | Op::Minus | Op::Status { .. } => {
            anyhow::bail!("internal: {op:?} is not a management op");
        }
    }
    Ok(())
}

/// Resolve the dir for `cas add`: explicit `dir` if given, else the
/// conventional `~/.claude.<name>`.
fn resolve_new_dir(name: &str, dir: Option<&str>) -> String {
    match dir {
        Some(d) if !d.is_empty() => d.to_owned(),
        _ => dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(format!(".claude.{name}"))
            .to_string_lossy()
            .into_owned(),
    }
}

/// Resolve a profile name to its `CLAUDE_CONFIG_DIR` path.
///
/// Falls back to constructing `~/.claude.<profile>` when `profiles` is empty
/// (toss machines / first-boot). An unknown profile in a populated map is an
/// error.
fn resolve_profile(profile: &str, profiles: &ProfileMap) -> anyhow::Result<String> {
    if profiles.is_empty() {
        // Toss machine or pre-ansible boot: synthesize the conventional path.
        let home = dirs::home_dir()
            .ok_or_else(|| anyhow::anyhow!("cas: cannot determine HOME directory"))?;
        return Ok(home
            .join(format!(".claude.{profile}"))
            .to_string_lossy()
            .into_owned());
    }
    profiles.get(profile).map(str::to_owned).ok_or_else(|| {
        let available: Vec<&str> = profiles.names_sorted();
        anyhow::anyhow!(
            "cas: unknown profile '{}' — available: {}",
            profile,
            available.join(", ")
        )
    })
}

/// Print informational status (no eval output). Mirrors the zsh `cas` with no
/// args output (lines 87-110 of claude-as.zsh).
fn print_status(_shell: Shell, profiles: &ProfileMap) -> anyhow::Result<()> {
    // The live shell's CLAUDE_CONFIG_DIR is read from the environment.
    // The binary does not have a "previous profile" concept (that lives in the
    // shell's `_CLAUDE_AS_PREV` var). We render what we can.
    let current_dir = std::env::var("CLAUDE_CONFIG_DIR").unwrap_or_default();
    let default = default_profile(profiles);
    let default_dir = profiles.default_dir().to_string_lossy().into_owned();

    // Resolve current profile name from CLAUDE_CONFIG_DIR.
    // Reproduces zsh `_claude_as_current_profile` (lines 46-54).
    let current_name = if current_dir.is_empty() {
        "unset".to_owned()
    } else {
        profiles
            .iter()
            .find(|(_, dir)| *dir == current_dir.as_str())
            .map(|(name, _)| name.to_owned())
            .unwrap_or_else(|| "unknown".to_owned())
    };

    // Reproduces zsh lines 93-110:
    //   print "current shell:  $current_profile ($shell_state)"
    //   print "global default: $default_profile (~/.config/claude-as/default)"
    //   print "available:"
    //   for k in ${(ko)CLAUDE_PROFILES}; do
    //     mark=" "; [[ "$k" == "$current_profile" ]] && mark="*"
    //     [[ "$k" == "$default_profile" ]] && mark="${mark}d" || mark="${mark} "
    //     printf '  %s %-12s %s\n' "$mark" "$k" "$dir"
    //   done
    //   print "(legend: * = current shell, d = global default)"
    let shell_state = if current_dir.is_empty() {
        "unset (no zshenv guard? new shells won't have a profile)".to_owned()
    } else {
        current_dir.clone()
    };

    println!("current shell:  {current_name} ({shell_state})");
    // Show the RESOLVED config dir of the default profile (not a hardcoded path),
    // so the user can see where the default actually points — falls back to the
    // pointer-file location when the dir can't be resolved.
    if default.is_empty() {
        // Degraded / no registry: there is no default profile name, so don't print
        // an empty name with a bogus `.claude.`-suffixed dir built from it.
        println!("global default: (none — no default profile set)");
    } else if default_dir.is_empty() {
        println!("global default: {default} (~/.config/claude-as/default)");
    } else {
        println!("global default: {default} ({default_dir})");
    }
    println!("available:");

    if profiles.is_empty() {
        println!("  (profiles.json absent — CAS/pick features disabled)");
    } else {
        for name in profiles.names_sorted() {
            let dir = profiles.get(name).unwrap_or("");
            let is_current = dir == current_dir.as_str();
            let is_default = name == default.as_str();
            let mark = match (is_current, is_default) {
                (true, true) => "*d",
                (true, false) => "* ",
                (false, true) => " d",
                (false, false) => "  ",
            };
            println!("  {mark} {name:<12} {dir}");
        }
        println!("(legend: * = current shell, d = global default)");
    }

    Ok(())
}

// ─── test-only grammar fixture ────────────────────────────────────────────────
//
// The production cas argument parser is `parse_cas_flags` + `parse_cas_op` in
// `main.rs` and is the SSOT. The function below is a TEST-ONLY fixture that
// mirrors the grammar so the 12 unit tests below can exercise the (Shell, Op)
// outcome combinations without needing access to main.rs's private functions.
// It is gated `#[cfg(test)]` so it never appears in release builds and does
// not produce a dead-code warning.

#[cfg(test)]
fn parse_cas_args_for_test<S: AsRef<str>>(args: &[S]) -> anyhow::Result<(Shell, Op)> {
    let mut shell = Shell::Zsh; // default
    let mut i = 0;
    let n = args.len();

    // Consume csm-level flags (--eval, --shell) before `--`.
    while i < n {
        let a = args[i].as_ref();
        match a {
            "--eval" => {
                i += 1;
            }
            "--shell" => {
                i += 1;
                if i >= n {
                    anyhow::bail!("cas: --shell requires an argument (zsh|bash|pwsh)");
                }
                let s = args[i].as_ref();
                shell = Shell::parse(s).ok_or_else(|| {
                    anyhow::anyhow!("cas: unknown shell '{}' — expected zsh, bash, or pwsh", s)
                })?;
                i += 1;
            }
            "--" => {
                i += 1;
                break;
            }
            _ => {
                break;
            }
        }
    }

    // Parse the user command (after `--` or the last csm flag).
    if i >= n {
        return Ok((
            shell,
            Op::Status {
                print_current: false,
            },
        ));
    }

    let cmd = args[i].as_ref();
    match cmd {
        "-" => Ok((shell, Op::Minus)),

        "resync" => Ok((shell, Op::Resync)),

        "status" => {
            let print_current = (i + 1 < n) && args[i + 1].as_ref() == "--print-current";
            Ok((shell, Op::Status { print_current }))
        }

        "-g" | "--global" => {
            i += 1;
            if i >= n {
                anyhow::bail!("cas: {} requires a profile name", cmd);
            }
            let profile = args[i].as_ref().to_owned();
            Ok((shell, Op::Global { profile }))
        }

        profile => Ok((
            shell,
            Op::Switch {
                profile: profile.to_owned(),
            },
        )),
    }
}

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

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

    // ── helpers ───────────────────────────────────────────────────────────────

    /// Build a two-profile `ProfileMap` pointing at paths under `/tmp` so tests
    /// do not depend on the real home directory.
    fn test_profiles() -> ProfileMap {
        let mut m = HashMap::new();
        m.insert("home".to_owned(), "/tmp/.claude.home".to_owned());
        m.insert("work".to_owned(), "/tmp/.claude.work".to_owned());
        ProfileMap(m)
    }

    fn empty_profiles() -> ProfileMap {
        ProfileMap::default()
    }

    // ── default_profile / default_name tests (registry-driven, no allowlist) ──

    /// Write `content` to a temp state file and return it, so `default_name_with`
    /// can be exercised without touching the real `~/.config/claude-as/default`.
    fn state_file(content: &str) -> NamedTempFile {
        let mut f = NamedTempFile::new().unwrap();
        write!(f, "{content}").unwrap();
        f
    }

    #[test]
    fn default_name_returns_configured_token() {
        let p = test_profiles();
        let f = state_file("work\n");
        assert_eq!(p.default_name_with(f.path()), "work");
        let f = state_file("home");
        assert_eq!(p.default_name_with(f.path()), "home");
    }

    #[test]
    fn default_name_unknown_token_falls_back_to_preferred() {
        // A populated map + an unknown/blank token → preferred_default()
        // (alphabetical-first; for {work, home} that is "home").
        let p = test_profiles();
        let f = state_file("hacker");
        assert_eq!(p.default_name_with(f.path()), "home");
        let f = state_file("   ");
        assert_eq!(p.default_name_with(f.path()), "home");
    }

    #[test]
    fn default_name_whitespace_trimmed() {
        let p = test_profiles();
        let f = state_file("  work  ");
        assert_eq!(p.default_name_with(f.path()), "work");
        let f = state_file("\tpersonal\n");
        assert_eq!(p.default_name_with(f.path()), "home");
    }

    #[test]
    fn default_name_empty_map_trusts_any_token() {
        // Toss/synth regime: no configured profiles → the state-file token is
        // trusted verbatim (so `~/.claude.<token>` synthesis works).
        let p = empty_profiles();
        let f = state_file("whatever\n");
        assert_eq!(p.default_name_with(f.path()), "whatever");
    }

    #[test]
    fn default_name_empty_map_absent_token_is_empty() {
        let p = empty_profiles();
        let f = state_file("");
        assert_eq!(p.default_name_with(f.path()), "");
    }

    #[test]
    fn write_default_profile_roundtrip_via_file() {
        // Write to a temp file and read it back directly (the on-disk format is
        // "<name>\n"; readers trim whitespace).
        let mut f = NamedTempFile::new().unwrap();
        writeln!(f, "work").unwrap();
        let s = std::fs::read_to_string(f.path()).unwrap();
        assert_eq!(s.trim(), "work");
    }

    #[test]
    fn profile_map_contains_replaces_allowlist() {
        let p = test_profiles();
        assert!(p.contains("home"));
        assert!(p.contains("work"));
        assert!(!p.contains("toss"));
        // Empty map contains nothing.
        assert!(!empty_profiles().contains("home"));
    }

    #[test]
    fn is_valid_name_syntax() {
        assert!(ProfileMap::is_valid_name("home"));
        assert!(ProfileMap::is_valid_name("work-2"));
        assert!(ProfileMap::is_valid_name("a.b_c"));
        assert!(!ProfileMap::is_valid_name(""));
        assert!(!ProfileMap::is_valid_name("has space"));
        assert!(!ProfileMap::is_valid_name("a/b")); // no path separators
    }

    // ── Shell export line tests ───────────────────────────────────────────────

    #[test]
    fn shell_zsh_export_line() {
        let line = Shell::Zsh.export_line("/Users/example/.claude.home");
        assert_eq!(
            line,
            "export CLAUDE_CONFIG_DIR='/Users/example/.claude.home'"
        );
    }

    #[test]
    fn shell_pwsh_export_line() {
        let line = Shell::Pwsh.export_line(r"C:\Users\example\.claude.home");
        assert_eq!(
            line,
            r"$env:CLAUDE_CONFIG_DIR = 'C:\Users\example\.claude.home'"
        );
    }

    #[test]
    fn shell_parse_zsh_variants() {
        assert_eq!(Shell::parse("zsh"), Some(Shell::Zsh));
        assert_eq!(Shell::parse("bash"), Some(Shell::Zsh));
        assert_eq!(Shell::parse("sh"), Some(Shell::Zsh));
        assert_eq!(Shell::parse("ZSH"), Some(Shell::Zsh));
    }

    #[test]
    fn shell_parse_pwsh_variants() {
        assert_eq!(Shell::parse("pwsh"), Some(Shell::Pwsh));
        assert_eq!(Shell::parse("powershell"), Some(Shell::Pwsh));
        assert_eq!(Shell::parse("PWSH"), Some(Shell::Pwsh));
    }

    #[test]
    fn shell_parse_unknown_is_none() {
        assert_eq!(Shell::parse("fish"), None);
        assert_eq!(Shell::parse(""), None);
    }

    // ── registry management: resolve_new_dir ──────────────────────────────────

    #[test]
    fn resolve_new_dir_explicit_wins() {
        assert_eq!(
            resolve_new_dir("work", Some("/custom/work")),
            "/custom/work"
        );
    }

    #[test]
    fn resolve_new_dir_synthesizes_conventional() {
        // Empty / None dir → ~/.claude.<name>.
        let got = resolve_new_dir("work", None);
        assert!(got.ends_with(".claude.work"), "got: {got}");
        let got = resolve_new_dir("work", Some(""));
        assert!(got.ends_with(".claude.work"), "got: {got}");
    }

    // ── Shell error_snippet tests ─────────────────────────────────────────────

    #[test]
    fn shell_zsh_error_snippet_basic() {
        let s = Shell::Zsh.error_snippet("cas: unknown profile 'foo'");
        assert!(s.starts_with(">&2 printf"), "got: {s}");
        assert!(s.ends_with("; false"), "got: {s}");
        assert!(s.contains("unknown profile"), "got: {s}");
    }

    #[test]
    fn shell_pwsh_error_snippet_basic() {
        let s = Shell::Pwsh.error_snippet("cas: unknown profile 'foo'");
        assert!(s.starts_with("Write-Error"), "got: {s}");
        assert!(s.ends_with("exit 1"), "got: {s}");
        assert!(s.contains("unknown profile"), "got: {s}");
    }

    #[test]
    fn shell_zsh_error_snippet_quote_escaping() {
        // Single quotes in the message must be escaped for zsh single-quoting.
        let s = Shell::Zsh.error_snippet("it's a problem");
        // The escaped form should not break the shell string.
        assert!(s.contains("it'\\''s"), "expected zsh escape, got: {s}");
    }

    #[test]
    fn shell_pwsh_error_snippet_quote_escaping() {
        // Single quotes doubled in pwsh.
        let s = Shell::Pwsh.error_snippet("it's a problem");
        assert!(s.contains("it''s"), "expected pwsh double-quote, got: {s}");
    }

    // ── Op variants compile and are constructible ─────────────────────────────

    #[test]
    fn op_variants_constructible() {
        let _ = Op::Switch {
            profile: "home".to_owned(),
        };
        let _ = Op::Minus;
        let _ = Op::Global {
            profile: "work".to_owned(),
        };
        let _ = Op::Resync;
        let _ = Op::Status {
            print_current: false,
        };
        let _ = Op::Status {
            print_current: true,
        };
    }

    // ── resolve_profile tests ─────────────────────────────────────────────────

    #[test]
    fn resolve_profile_personal_in_map() {
        let profiles = test_profiles();
        let result = resolve_profile("home", &profiles);
        assert_eq!(result.unwrap(), "/tmp/.claude.home");
    }

    #[test]
    fn resolve_profile_work_in_map() {
        let profiles = test_profiles();
        let result = resolve_profile("work", &profiles);
        assert_eq!(result.unwrap(), "/tmp/.claude.work");
    }

    #[test]
    fn resolve_profile_unknown_in_populated_map_errors() {
        let profiles = test_profiles();
        let result = resolve_profile("hacker", &profiles);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("unknown profile"),
            "expected 'unknown profile' in: {msg}"
        );
        assert!(
            msg.contains("home"),
            "expected available profiles in: {msg}"
        );
    }

    #[test]
    fn resolve_profile_empty_map_synthesizes_path() {
        let profiles = empty_profiles();
        let result = resolve_profile("home", &profiles);
        assert!(result.is_ok());
        let dir = result.unwrap();
        // Should end with .claude.home
        assert!(dir.ends_with(".claude.home"), "synthesized dir: {dir}");
    }

    // ── eval_emit: Op::Minus emits error snippet ──────────────────────────────

    /// Capture what eval_emit prints to stdout by redirecting via a temp pipe.
    /// Since we can't redirect stdout in unit tests portably, we test the
    /// error snippet emission logic by calling `Shell::error_snippet` directly
    /// (which `eval_emit` delegates to for `Op::Minus`).
    #[test]
    fn op_minus_produces_error_snippet_for_zsh() {
        // Verify the snippet that will be emitted is well-formed zsh.
        let snippet = Shell::Zsh.error_snippet("claude-as: no previous profile to toggle to");
        assert!(snippet.contains("no previous profile"), "got: {snippet}");
        assert!(snippet.ends_with("; false"), "got: {snippet}");
    }

    #[test]
    fn op_minus_produces_error_snippet_for_pwsh() {
        let snippet = Shell::Pwsh.error_snippet("claude-as: no previous profile to toggle to");
        assert!(snippet.contains("no previous profile"), "got: {snippet}");
        assert!(snippet.ends_with("exit 1"), "got: {snippet}");
    }

    // ── eval_emit: allowlist rejection via error snippet ─────────────────────

    /// When an unknown profile is passed, eval_emit must NOT return Err (which
    /// would let the shim silently swallow the error) but must emit an error
    /// snippet so `eval` propagates the failure.
    ///
    /// We test by calling `resolve_profile` directly — the exact same logic
    /// eval_emit uses — to verify it returns Err, then verify
    /// `Shell::error_snippet` would wrap it into a valid snippet.
    #[test]
    fn unknown_profile_produces_error_snippet_not_panic() {
        let profiles = test_profiles();
        let err = resolve_profile("badprofile", &profiles).unwrap_err();
        let snippet = Shell::Zsh.error_snippet(&err.to_string());
        assert!(snippet.contains("unknown profile"), "got: {snippet}");
        assert!(snippet.ends_with("; false"), "got: {snippet}");
    }

    #[test]
    fn unknown_profile_error_snippet_for_pwsh() {
        let profiles = test_profiles();
        let err = resolve_profile("badprofile", &profiles).unwrap_err();
        let snippet = Shell::Pwsh.error_snippet(&err.to_string());
        assert!(snippet.contains("unknown profile"), "got: {snippet}");
        assert!(snippet.ends_with("exit 1"), "got: {snippet}");
    }

    // ── toggle logic tests ────────────────────────────────────────────────────

    /// The zsh toggle: if `_CLAUDE_AS_PREV` == "work" and user runs `cas -`,
    /// the shim resolves it to `cas work`. Here we verify that
    /// `resolve_profile("work", ...)` succeeds — the toggle logic itself
    /// is on the shim side, but the binary must handle the resolved profile name.
    #[test]
    fn toggle_resolves_previous_profile() {
        let profiles = test_profiles();
        // Simulate: user was on "home", ran `cas work` (which sets
        // _CLAUDE_AS_PREV="home"), then runs `cas -`.
        // The shim resolves _CLAUDE_AS_PREV to "home" and calls csm with "home".
        let result = resolve_profile("home", &profiles);
        assert_eq!(result.unwrap(), "/tmp/.claude.home");
    }

    /// Toggle to "work" (the other direction).
    #[test]
    fn toggle_resolves_other_profile() {
        let profiles = test_profiles();
        // Simulate: user was on "work", _CLAUDE_AS_PREV="work", `cas -`.
        // Actually: if current is personal and prev was work, toggle → work.
        let result = resolve_profile("work", &profiles);
        assert_eq!(result.unwrap(), "/tmp/.claude.work");
    }

    // ── resync logic ──────────────────────────────────────────────────────────

    /// Resync reads `default_profile()` and resolves it. Verify the logic
    /// produces the correct export line for a known profile (using the inner
    /// functions).
    #[test]
    fn resync_resolves_via_default_profile_logic() {
        let profiles = test_profiles();
        // Simulate default_profile() returning "home":
        let profile = "home";
        let dir = resolve_profile(profile, &profiles).unwrap();
        let line = Shell::Zsh.export_line(&dir);
        assert_eq!(line, "export CLAUDE_CONFIG_DIR='/tmp/.claude.home'");
    }

    #[test]
    fn resync_pwsh_form() {
        let profiles = test_profiles();
        let dir = resolve_profile("work", &profiles).unwrap();
        let line = Shell::Pwsh.export_line(&dir);
        assert_eq!(line, "$env:CLAUDE_CONFIG_DIR = '/tmp/.claude.work'");
    }

    // ── global op: write_default_profile validation ───────────────────────────

    #[test]
    fn write_default_profile_rejects_unknown_in_populated_map() {
        // A populated registry rejects a non-configured name; the error lists
        // the configured names dynamically (never a hardcoded allowlist).
        let result = write_default_profile("toss", &test_profiles());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("unknown profile"), "got: {msg}");
        assert!(msg.contains("configured:"), "got: {msg}");
        assert!(msg.contains("home") && msg.contains("work"), "got: {msg}");
    }

    #[test]
    fn write_default_profile_empty_map_accepts_any_token() {
        // Toss/synth: empty registry accepts any non-empty token (rejects empty).
        // (Does not assert disk write — only the validation gate.)
        let empty = empty_profiles();
        // Empty token is rejected even on an empty map.
        assert!(empty.is_empty());
        assert!(ProfileMap::is_valid_name("anything"));
    }

    // ── parse_cas_args: arg parsing logic (exercised via parse_cas_args fn) ───

    #[test]
    fn parse_args_switch_personal() {
        let args = ["--eval", "--shell", "zsh", "--", "home"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Switch {
                profile: "home".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_switch_work() {
        let args = ["--eval", "--shell", "zsh", "--", "work"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Switch {
                profile: "work".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_switch_pwsh() {
        let args = ["--eval", "--shell", "pwsh", "--", "home"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Pwsh);
        assert_eq!(
            op,
            Op::Switch {
                profile: "home".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_minus() {
        let args = ["--eval", "--shell", "zsh", "--", "-"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(op, Op::Minus);
    }

    #[test]
    fn parse_args_global() {
        let args = ["--eval", "--shell", "zsh", "--", "-g", "home"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Global {
                profile: "home".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_global_long_form() {
        let args = ["--eval", "--shell", "zsh", "--", "--global", "work"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Global {
                profile: "work".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_resync() {
        let args = ["--eval", "--shell", "zsh", "--", "resync"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(op, Op::Resync);
    }

    #[test]
    fn parse_args_status() {
        let args = ["--eval", "--shell", "zsh", "--", "status"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Status {
                print_current: false
            }
        );
    }

    #[test]
    fn parse_args_status_print_current() {
        let args = [
            "--eval",
            "--shell",
            "zsh",
            "--",
            "status",
            "--print-current",
        ];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Status {
                print_current: true
            }
        );
    }

    #[test]
    fn parse_args_no_shell_defaults_to_zsh() {
        // When --shell is absent (bare call), default to zsh.
        let args = ["--eval", "--", "home"];
        let (shell, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(shell, Shell::Zsh);
        assert_eq!(
            op,
            Op::Switch {
                profile: "home".to_owned()
            }
        );
    }

    #[test]
    fn parse_args_no_args_is_status() {
        // Bare `csm cas` (no --shell, no --) → status.
        let args: [&str; 0] = [];
        let (_, op) = parse_cas_args_for_test(&args).unwrap();
        assert_eq!(
            op,
            Op::Status {
                print_current: false
            }
        );
    }

    #[test]
    fn parse_args_global_missing_profile_errors() {
        let args = ["--eval", "--shell", "zsh", "--", "-g"];
        let result = parse_cas_args_for_test(&args);
        assert!(result.is_err(), "expected error for -g without profile");
    }
}