ditto-cli 0.4.2

Switch between Claude Code, Codex, opencode, OMP, Prime Agent, Pi, and 29 more coding-agent accounts
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
mod cli;
mod herdr;
mod history;
mod indicator;
mod launch;
mod profile;
mod program;
#[cfg(unix)]
mod proxy;
mod settings;
mod shared;
mod shell;
mod tools;
mod ui;
mod update;
mod workspace;

use std::{
    io::{self, IsTerminal},
    path::PathBuf,
};

use anyhow::{Context, Result, bail};
use clap::{CommandFactory, FromArgMatches};
use serde_json::{Value, json};

use cli::{
    AutoState, Cli, CodexAppArgs, Command, DefaultAction, DefaultArgs, DeleteArgs, IndicatorAction,
    IndicatorArgs, LaunchArgs, ShellInitArgs, SyncArgs, WorkspaceArgs, WorkspaceCommand,
};
use indicator::Existing;
use launch::{AuthStatus, Tool};
use profile::{DEFAULT_PROFILE, Fallback, Profile, Store};
use workspace::{WORKSPACE_FILE, Workspaces};

fn main() {
    restore_sigpipe();

    // The table's tools share one subcommand between them, so `--help` names
    // them here rather than nowhere.
    let matches = Cli::command().after_help(other_agents_help()).get_matches();
    let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|error| error.exit());
    // Read before the command is consumed, so a failure can answer in the shape
    // the caller asked for rather than dropping to prose halfway through.
    let json = cli.json;

    if let Err(error) = run(cli) {
        if json {
            eprintln!("{}", json!({ "error": format!("{error:#}") }));
        } else {
            eprintln!("ditto-cli: {error:#}");
        }
        std::process::exit(1);
    }
}

fn other_agents_help() -> String {
    let names = tools::ALL
        .iter()
        .map(|spec| spec.key)
        .collect::<Vec<_>>()
        .chunks(6)
        .map(|row| row.join(", "))
        .collect::<Vec<_>>()
        .join(",\n  ");
    format!(
        "Other agents, launched the same way as the commands above \
         (`ditto-cli <agent> [profile] -- [args]`):\n  {names}"
    )
}

/// Ends quietly when the reader of Ditto's output goes away.
///
/// Rust ignores `SIGPIPE` so that a write to a closed pipe returns an error
/// instead of killing the process, but the print macros then panic on that
/// error. Every reporting command here prints lines someone may well pipe into
/// `head`, and a panic and a backtrace is not the answer that deserves, so the
/// default disposition is restored and Ditto ends the way every other tool in
/// the pipeline does.
#[cfg(unix)]
fn restore_sigpipe() {
    // SAFETY: called before any thread is started, and `SIG_DFL` is the
    // disposition the process began life with before Rust's runtime changed it.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}

#[cfg(not(unix))]
fn restore_sigpipe() {}

fn run(cli: Cli) -> Result<()> {
    let store = Store::discover()?;
    let workspaces = Workspaces::new(&store);
    let json = cli.json;

    match cli.command {
        None => run_tui(&store, &workspaces),
        Some(Command::List) => list_profiles(&store, &workspaces, json),
        Some(Command::Status { profile }) => {
            show_status(&store, &workspaces, profile.as_deref(), json)
        }
        Some(Command::Create { name }) => create_profile(&store, &name, json),
        Some(Command::Rename { profile, new_name }) => {
            rename_profile(&store, &profile, &new_name, json)
        }
        Some(Command::Delete(arguments)) => delete_profile(&store, arguments, json),
        Some(Command::Sync(arguments)) => sync_settings(&store, &workspaces, arguments, json),
        Some(Command::Default(arguments)) => {
            set_default_profile(&store, &workspaces, arguments, json)
        }
        Some(Command::Workspace(arguments)) => run_workspace(&store, &workspaces, arguments, json),
        Some(Command::Paths { profile }) => {
            show_paths(&store, &workspaces, profile.as_deref(), json)
        }
        Some(Command::Claude(arguments)) => {
            launch_direct(&store, &workspaces, Tool::Claude, arguments)
        }
        Some(Command::Codex(arguments)) => {
            launch_direct(&store, &workspaces, Tool::Codex, arguments)
        }
        Some(Command::CodexApp(arguments)) => launch_codex_app(&store, &workspaces, arguments),
        Some(Command::Fx(arguments)) => launch_direct(&store, &workspaces, Tool::Fx, arguments),
        Some(Command::Opencode(arguments)) => {
            launch_direct(&store, &workspaces, Tool::Opencode, arguments)
        }
        Some(Command::Omp(arguments)) => launch_direct(&store, &workspaces, Tool::Omp, arguments),
        Some(Command::PrimeAgent(arguments)) => {
            launch_direct(&store, &workspaces, Tool::PrimeAgent, arguments)
        }
        Some(Command::Pi(arguments)) => launch_direct(&store, &workspaces, Tool::Pi, arguments),
        Some(Command::Other(argv)) => {
            let (name, arguments) = cli::external_launch(&argv)?;
            let Some(tool) = Tool::by_key(&name) else {
                bail!(
                    "'{name}' is not a Ditto command or an agent it launches; run `ditto-cli --help`"
                );
            };
            launch_direct(&store, &workspaces, tool, arguments)
        }
        Some(Command::ShellInit(arguments)) => print_shell_init(arguments),
        Some(Command::Indicator(arguments)) => set_indicator(&store, &workspaces, arguments, json),
        Some(Command::Statusline(arguments)) => {
            indicator::render(arguments.with, arguments.with_encoded)
        }
        Some(Command::Update(arguments)) => update::run(arguments.check, arguments.git),
    }
}

/// Answers in whichever shape the caller asked for. Every reporting command
/// speaks both, so the choice is made here rather than in each of them.
fn report(json: bool, payload: impl FnOnce() -> Value, human: impl FnOnce()) {
    if json {
        println!("{}", payload());
    } else {
        human();
    }
}

/// The picker needs a terminal to draw on and a keyboard to read, and gets
/// neither from a script or an agent. Saying so beats the panic that reaching
/// for an absent terminal would otherwise raise, and naming the commands that
/// do work turns a dead end into a next step.
fn run_tui(store: &Store, workspaces: &Workspaces) -> Result<()> {
    if !io::stdout().is_terminal() || !io::stdin().is_terminal() {
        bail!(
            "the profile picker needs an interactive terminal, and this is not one.\n\
             Every command works without it:\n\
            \x20 ditto-cli list --json\n\
            \x20 ditto-cli status <profile> --json\n\
            \x20 ditto-cli create <profile>\n\
            \x20 ditto-cli default <profile>\n\
            \x20 ditto-cli workspace use <profile>\n\
             Run `ditto-cli --help` for the full set."
        );
    }

    // The directory decides where the cursor opens, falling back to the last
    // launch as it did before there were workspaces. Resolved once, outside the
    // loop, so signing in and coming back does not move the cursor off the
    // profile that was just signed in.
    let mut selected = match current_binding(workspaces) {
        Some(binding) if store.load_profile(&binding.profile).is_ok() => Some(binding.profile),
        _ => store.last_profile()?,
    };

    loop {
        let profiles = store.list_profiles()?;
        let default_profile = store.default_profile_name()?;
        let Some(action) = ui::run(store, profiles, selected.as_deref(), default_profile)? else {
            return Ok(());
        };

        match action {
            ui::UiAction::Launch { tool, profile } => {
                store.save_last_profile(&profile.name)?;
                auto_bind(store, workspaces, &profile.name)?;
                return launch::launch(tool, &profile, &[]);
            }
            #[cfg(target_os = "macos")]
            ui::UiAction::LaunchCodexDesktop { profile } => {
                return launch_codex_app(
                    store,
                    workspaces,
                    CodexAppArgs {
                        profile: Some(profile.name),
                        directory: None,
                    },
                );
            }
            ui::UiAction::Authenticate {
                operation,
                tool,
                profile,
            } => {
                store.save_last_profile(&profile.name)?;
                selected = Some(profile.name.clone());
                launch::authenticate(operation, tool, &profile)?;
            }
        }
    }
}

fn list_profiles(store: &Store, workspaces: &Workspaces, json: bool) -> Result<()> {
    let last_profile = store.last_profile()?;
    let default_profile = store.default_profile_name()?;
    let profiles = store.list_profiles()?;
    let binding = current_binding(workspaces);
    let fallback = effective_fallback(store, binding.as_ref())?;

    let is_default = |profile: &Profile| default_profile.as_deref() == Some(&profile.name);
    let is_last = |profile: &Profile| last_profile.as_deref() == Some(&profile.name);

    report(
        json,
        || {
            json!({
                "profiles": profiles
                    .iter()
                    .map(|profile| json!({
                        "name": profile.name,
                        "managed": profile.managed,
                        "is_default": is_default(profile),
                        "is_last_selected": is_last(profile),
                    }))
                    .collect::<Vec<_>>(),
                "default_profile": default_profile,
                "last_profile": last_profile,
                // What a command with no profile name would actually use, so a
                // caller does not have to re-derive the precedence rule. The
                // directory outranks both saved values, so it is answered from
                // here rather than from the state file alone.
                "fallback_profile": fallback,
                "workspace": binding_payload(binding.as_ref()),
            })
        },
        || {
            for profile in &profiles {
                let selected = if is_last(profile) { "*" } else { " " };
                let kind = if profile.managed {
                    "isolated"
                } else {
                    "native"
                };
                let pinned = if is_default(profile) { "  default" } else { "" };
                println!("{selected} {:<32} {kind}{pinned}", profile.name);
            }
        },
    );
    Ok(())
}

fn show_status(
    store: &Store,
    workspaces: &Workspaces,
    requested_profile: Option<&str>,
    json: bool,
) -> Result<()> {
    let (profile, _) = resolve_profile(store, workspaces, requested_profile)?;
    let statuses = Tool::ALL.map(|tool| (tool, launch::auth_status(tool, &profile)));

    report(
        json,
        || {
            json!({
                "profile": profile.name,
                "managed": profile.managed,
                "tools": statuses
                    .iter()
                    .map(|(tool, status)| json!({
                        "tool": tool.key(),
                        "label": tool.label(),
                        "status": status.key(),
                        "signed_in": *status == AuthStatus::SignedIn,
                    }))
                    .collect::<Vec<_>>(),
            })
        },
        || {
            println!("{}", profile.name);
            for (tool, status) in &statuses {
                // JSON keeps every tool so the shape is stable; a person is
                // shown the agents they have, not every one Ditto knows.
                if matches!(tool, Tool::Generic(_)) && *status == AuthStatus::Unavailable {
                    continue;
                }
                print_auth_status(*tool, *status);
            }
        },
    );
    Ok(())
}

fn print_auth_status(tool: Tool, status: AuthStatus) {
    let status = match status {
        AuthStatus::SignedIn => "signed in",
        AuthStatus::SignedOut => "sign in required",
        AuthStatus::Unavailable => "CLI or status unavailable",
    };
    println!("  {:<13} {status}", tool.label());
}

fn create_profile(store: &Store, name: &str, json: bool) -> Result<()> {
    let profile = store.create_profile(name)?;
    // Claude Code reads its settings from the directory a launch moves, so a
    // new profile would otherwise start with none of the permission mode,
    // model, or hooks its owner set up once and expects everywhere.
    let copied = settings::seed(store, &profile);
    // Skills, subagents, commands, hooks and plugins are not accounts, and a
    // profile that started without them would be a different working
    // environment rather than the same one signed in as somebody else.
    let linked = shared::seed(store, &profile);

    report(
        json,
        || {
            let mut created = profile_paths(&profile);
            // A new profile is signed in to nothing, so the commands that fix
            // that are part of the answer rather than a note beside it.
            created["created"] = json!(true);
            created["settings_copied"] = json!(copied.copied);
            created["shared"] = json!(linked.linked);
            let mut sign_in = json!({
                "claude": format!("ditto-cli claude {} -- auth login", profile.name),
                "codex": format!("ditto-cli codex {} -- login", profile.name),
                "fx": format!("ditto-cli fx {} -- login", profile.name),
                "opencode": format!("ditto-cli opencode {} -- auth login", profile.name),
                "omp": format!("ditto-cli omp {} (then /login inside OMP)", profile.name),
                "prime-agent": format!(
                    "ditto-cli prime-agent {} -- /login",
                    profile.name
                ),
                "pi": format!("ditto-cli pi {} (then /login inside Pi)", profile.name),
            });
            for spec in tools::ALL {
                sign_in[spec.key] = json!(match spec.login {
                    Some(login) => format!(
                        "ditto-cli {} {} -- {}",
                        spec.key,
                        profile.name,
                        login.join(" ")
                    ),
                    None => format!(
                        "ditto-cli {} {} (then sign in inside {})",
                        spec.key, profile.name, spec.label
                    ),
                });
            }
            created["sign_in"] = sign_in;
            created["preserve_history"] = json!({
                "this_profile": format!("ditto-cli sync {} --history", profile.name),
                "all_profiles": "ditto-cli sync --all --history",
            });
            created
        },
        || {
            println!("Created profile '{}'.", profile.name);
            if copied.changed() {
                println!(
                    "Copied your Claude Code settings into it: {}.",
                    copied.copied.join(", ")
                );
            }
            if !linked.linked.is_empty() {
                println!("Reading yours for: {}.", linked.linked.join(", "));
            }
            println!(
                "Preserve existing chats in this profile with `ditto-cli sync {} \
                 --history`, or in every profile with `ditto-cli sync --all --history`.",
                profile.name
            );
            print_login_instructions(&profile);
        },
    );
    Ok(())
}

/// Brings a profile that already exists up to the settings a new one would be
/// created with. Profiles made before Ditto copied anything started empty, and
/// a setting changed since then reaches them no other way.
fn sync_settings(
    store: &Store,
    workspaces: &Workspaces,
    arguments: SyncArgs,
    json: bool,
) -> Result<()> {
    let source = store.load_profile(DEFAULT_PROFILE)?;
    let profiles = if arguments.all {
        store
            .list_profiles()?
            .into_iter()
            .filter(|profile| profile.managed)
            .collect::<Vec<_>>()
    } else {
        vec![resolve_profile(store, workspaces, arguments.profile.as_deref())?.0]
    };
    let outcomes = profiles
        .into_iter()
        .map(|profile| {
            sync_profile(
                store,
                &source,
                profile,
                arguments.overwrite,
                arguments.adopt,
                arguments.history,
            )
        })
        .collect::<Result<Vec<_>>>()?;

    if arguments.all {
        report(
            json,
            || {
                json!({
                    "profiles": outcomes.iter().map(sync_payload).collect::<Vec<_>>(),
                    "changed": outcomes.iter().any(SyncOutcome::changed),
                })
            },
            || {
                for outcome in &outcomes {
                    print_sync(outcome);
                }
            },
        );
    } else {
        let outcome = &outcomes[0];
        report(json, || sync_payload(outcome), || print_sync(outcome));
    }
    Ok(())
}

struct SyncOutcome {
    profile: String,
    copied: settings::Copied,
    linked: shared::Linked,
    repaired: shared::Repaired,
    history: Option<history::Backfilled>,
}

impl SyncOutcome {
    fn changed(&self) -> bool {
        self.copied.changed()
            || self.linked.changed()
            || self.repaired.changed()
            || self
                .history
                .as_ref()
                .is_some_and(history::Backfilled::changed)
    }
}

fn sync_profile(
    store: &Store,
    source: &Profile,
    profile: Profile,
    overwrite: bool,
    adopt: bool,
    backfill_history: bool,
) -> Result<SyncOutcome> {
    store.ensure_profile_directories(&profile)?;
    let copied = settings::copy(source, &profile, overwrite)?;
    let linked = shared::link(source, &profile, adopt)?;
    // A launch repairs the tool it is about to start; asking for a sync is
    // asking about the profile, so this answers for every tool at once.
    let repaired = shared::repair(&profile);
    let history = backfill_history
        .then(|| history::backfill(source, &profile))
        .transpose()?;

    Ok(SyncOutcome {
        profile: profile.name,
        copied,
        linked,
        repaired,
        history,
    })
}

fn sync_payload(outcome: &SyncOutcome) -> Value {
    let mut payload = json!({
        "profile": outcome.profile,
        "source": DEFAULT_PROFILE,
        "copied": outcome.copied.copied,
        "kept": outcome.copied.kept,
        "shared": outcome.linked.linked,
        "shared_kept": outcome.linked.kept,
        "shared_failed": outcome
            .linked
            .failed
            .iter()
            .map(|(path, reason)| json!({ "path": path, "reason": reason }))
            .collect::<Vec<_>>(),
        "repaired": outcome.repaired.links,
        "repair_failed": outcome
            .repaired
            .failed
            .iter()
            .map(|(path, reason)| json!({ "path": path, "reason": reason }))
            .collect::<Vec<_>>(),
        "changed": outcome.changed(),
    });
    if let Some(history) = &outcome.history {
        payload["history"] = json!(
            history
                .tools
                .iter()
                .map(|(tool, counts)| (
                    tool.key().to_owned(),
                    json!({ "copied": counts.copied, "kept": counts.kept })
                ))
                .collect::<serde_json::Map<_, _>>()
        );
    }
    payload
}

fn print_sync(outcome: &SyncOutcome) {
    if outcome.copied.changed() {
        println!(
            "Copied into '{}': {}.",
            outcome.profile,
            outcome.copied.copied.join(", ")
        );
    } else {
        println!(
            "'{}' already has every setting your own configuration sets.",
            outcome.profile
        );
    }
    if !outcome.copied.kept.is_empty() {
        println!(
            "Left '{}' as it is for: {}.",
            outcome.profile,
            outcome.copied.kept.join(", ")
        );
        println!(
            "  Replace those too with `ditto-cli sync {} --overwrite`.",
            outcome.profile
        );
    }
    if !outcome.linked.linked.is_empty() {
        println!("Reading yours for: {}.", outcome.linked.linked.join(", "));
    }
    if !outcome.linked.kept.is_empty() {
        println!(
            "'{}' has its own and keeps it: {}.",
            outcome.profile,
            outcome.linked.kept.join(", ")
        );
        println!(
            "  Point those at yours too with `ditto-cli sync {} --adopt`, \
             which moves what is there aside rather than deleting it.",
            outcome.profile
        );
    }
    for (path, reason) in &outcome.linked.failed {
        println!("Could not share {path}: {reason}");
    }
    if !outcome.repaired.links.is_empty() {
        println!(
            "Repaired links installed pointing at nothing: {}.",
            outcome.repaired.links.join(", ")
        );
    }
    for (path, reason) in &outcome.repaired.failed {
        println!("Could not repair {path}: {reason}");
    }
    if let Some(history) = &outcome.history {
        for (tool, counts) in &history.tools {
            println!(
                "Backfilled {} {} history files or sessions into '{}'; kept {} already there.",
                counts.copied,
                tool.label(),
                outcome.profile,
                counts.kept
            );
        }
    }
}

/// Claude Code stores its credentials against the directory it was pointed at,
/// and renaming moves that directory, so the sign-in cannot survive. Saying so
/// before the move beats leaving it to be discovered at the next launch.
fn rename_profile(store: &Store, current_name: &str, new_name: &str, json: bool) -> Result<()> {
    let current = store.load_profile(current_name)?;
    let signs_out = launch::auth_status(Tool::Claude, &current) == AuthStatus::SignedIn;
    if signs_out && !json {
        println!(
            "Claude Code ties its credentials to the profile directory, which this \
             rename moves,\nso '{current_name}' will be signed out."
        );
        println!();
    }

    let profile = store.rename_profile(current_name, new_name)?;
    report(
        json,
        || {
            json!({
                "renamed": true,
                "from": current_name,
                "profile": profile.name,
                // Reported rather than warned about: the caller has already
                // committed by the time this is read.
                "claude_signed_out": signs_out,
            })
        },
        || {
            println!("Renamed profile '{current_name}' to '{}'.", profile.name);
            if signs_out {
                println!();
                println!("Sign Claude Code back in with:");
                println!("  ditto-cli claude {} -- auth login", profile.name);
            }
        },
    );
    Ok(())
}

/// Deleting is the one command that destroys something, so it asks to be meant
/// rather than merely typed. The refusal names the directories so the caller can
/// see what the confirmation is actually for.
fn delete_profile(store: &Store, arguments: DeleteArgs, json: bool) -> Result<()> {
    let name = arguments.profile;
    // Load first, so a name that does not exist fails as a missing profile
    // rather than as a missing confirmation.
    store.load_profile(&name)?;
    let targets = store.deletion_targets(&name);
    let listed = targets
        .iter()
        .map(|path| format!("  {}", path.display()))
        .collect::<Vec<_>>()
        .join("\n");

    if !arguments.yes {
        bail!(
            "deleting '{name}' removes its credentials, settings, and session history \
             for good:\n{listed}\nPass --yes to confirm."
        );
    }

    store.delete_profile(&name)?;
    report(
        json,
        || {
            json!({
                "deleted": true,
                "profile": name,
                "removed": targets
                    .iter()
                    .map(|path| path.display().to_string())
                    .collect::<Vec<_>>(),
            })
        },
        || {
            println!("Deleted profile '{name}'.");
            println!("{listed}");
        },
    );
    Ok(())
}

/// Shows, pins, or releases the profile that commands fall back to. The pin is
/// otherwise reachable only by pressing `d` in the picker, which a script and an
/// agent have no way to do.
fn set_default_profile(
    store: &Store,
    workspaces: &Workspaces,
    arguments: DefaultArgs,
    json: bool,
) -> Result<()> {
    match arguments.action() {
        Some(DefaultAction::Pin(name)) => store.set_default_profile_name(Some(name))?,
        Some(DefaultAction::Clear) => store.set_default_profile_name(None)?,
        None => {}
    }

    let default_profile = store.default_profile_name()?;
    let binding = current_binding(workspaces);
    let fallback = effective_fallback(store, binding.as_ref())?;

    report(
        json,
        || {
            json!({
                "default_profile": default_profile,
                "fallback_profile": fallback,
                "workspace": binding_payload(binding.as_ref()),
            })
        },
        || {
            match &default_profile {
                Some(name) => println!("default profile: {name}"),
                // Naming what happens instead keeps the empty answer useful.
                None => println!("no default profile; commands fall back to {fallback}"),
            }
            // The pin is not what this directory would actually use, and saying
            // only the pin would read as though it were.
            if let Some(binding) = &binding {
                println!(
                    "here, {} outranks it and names '{}'",
                    binding.describe_origin(),
                    binding.profile
                );
            }
        },
    );
    Ok(())
}

/// Prints shell functions rather than a report, so it has no JSON form: the
/// output is a script for a shell to read, and wrapping it in JSON would leave
/// the caller to unwrap it before the shell could.
fn print_shell_init(arguments: ShellInitArgs) -> Result<()> {
    let shell = match arguments.shell {
        Some(shell) => shell,
        None => shell::detect()?,
    };
    print!("{}", shell::script(shell));
    Ok(())
}

fn set_indicator(
    store: &Store,
    workspaces: &Workspaces,
    arguments: IndicatorArgs,
    json: bool,
) -> Result<()> {
    let (profile, _) = resolve_profile(store, workspaces, arguments.profile.as_deref())?;
    let existing = if arguments.keep_mine {
        Existing::KeepAlongside
    } else {
        Existing::LeaveAlone
    };
    // Whether the status line will actually be seen depends on the directory
    // this was typed in, so it is answered here rather than by the profile.
    let outcome = indicator::shadowed(match arguments.action() {
        Some(IndicatorAction::On) => indicator::enable(&profile, existing)?,
        Some(IndicatorAction::Off) => indicator::disable(&profile)?,
        None => indicator::state(&profile)?,
    });

    report(
        json,
        || {
            json!({
                "profile": profile.name,
                "outcome": outcome.key(),
                "on": outcome.is_on(),
                "description": outcome.describe(),
            })
        },
        || println!("{}: {}", profile.name, outcome.describe()),
    );
    Ok(())
}

fn show_paths(
    store: &Store,
    workspaces: &Workspaces,
    requested_profile: Option<&str>,
    json: bool,
) -> Result<()> {
    let (profile, _) = resolve_profile(store, workspaces, requested_profile)?;
    report(
        json,
        || profile_paths(&profile),
        || {
            println!("profile={}", profile.name);
            println!("claude={}", profile.claude_home.display());
            println!("codex={}", profile.codex_home.display());
            println!("fx={}", profile.fx_dir().display());
            println!("opencode={}", profile.opencode.data_dir().display());
            println!(
                "opencode-config={}",
                profile.opencode.config_dir().display()
            );
            println!("omp={}", profile.omp_home.display());
            println!("prime-agent={}", profile.prime_agent_home.display());
            println!("pi={}", profile.pi_home.display());
            for spec in tools::ALL {
                println!("{}={}", spec.key, profile.tool_root(spec).display());
            }
        },
    );
    Ok(())
}

/// The directories a profile owns, in the shape both `paths` and `create`
/// report them.
fn profile_paths(profile: &Profile) -> Value {
    let mut paths = json!({
        "profile": profile.name,
        "managed": profile.managed,
        "claude": profile.claude_home.display().to_string(),
        "codex": profile.codex_home.display().to_string(),
        "fx": profile.fx_dir().display().to_string(),
        "opencode": profile.opencode.data_dir().display().to_string(),
        "opencode_config": profile.opencode.config_dir().display().to_string(),
        "omp": profile.omp_home.display().to_string(),
        "prime_agent": profile.prime_agent_home.display().to_string(),
        "pi": profile.pi_home.display().to_string(),
    });
    for spec in tools::ALL {
        paths[spec.key.replace('-', "_")] = json!(profile.tool_root(spec).display().to_string());
    }
    paths
}

fn launch_codex_app(store: &Store, workspaces: &Workspaces, arguments: CodexAppArgs) -> Result<()> {
    let open_directory = arguments.directory.is_some();
    let directory = directory_argument(arguments.directory)?;
    std::env::set_current_dir(&directory)
        .with_context(|| format!("could not enter {}", directory.display()))?;
    let directory = current_directory()?;
    let (profile, fell_back) = resolve_profile(store, workspaces, arguments.profile.as_deref())?;
    if let Some(fallback) = fell_back {
        eprintln!(
            "ditto-cli: using '{}'; nothing binds {}, and it is {}",
            profile.name,
            directory.display(),
            fallback.describe()
        );
    }
    launch::launch_codex_desktop(
        &profile,
        store.user_home(),
        open_directory.then_some(directory.as_path()),
    )?;
    store.save_last_profile(&profile.name)?;
    if open_directory {
        auto_bind(store, workspaces, &profile.name)?;
    }
    Ok(())
}

fn launch_direct(
    store: &Store,
    workspaces: &Workspaces,
    tool: Tool,
    arguments: LaunchArgs,
) -> Result<()> {
    let (profile, fell_back) = resolve_profile(store, workspaces, arguments.profile.as_deref())?;
    store.save_last_profile(&profile.name)?;

    // The saved fallback is the one answer nothing on screen points at: the
    // command did not name it and the directory does not either, which is how a
    // launch ends up in the wrong profile with nothing having said so. Saying it
    // before the tool takes the terminal is the last chance to notice. Reporting
    // commands stay quiet, since a fallback is their ordinary case and they are
    // run in loops.
    if let Some(fallback) = &fell_back {
        eprintln!(
            "ditto-cli: using '{}'; nothing binds this directory, and it is {}",
            profile.name,
            fallback.describe()
        );
    }

    let bound = auto_bind(store, workspaces, &profile.name)?;
    if fell_back.is_some() && !bound {
        eprintln!(
            "ditto-cli: bind this directory with `ditto-cli workspace use <profile>`, or name a \
             profile with `ditto-cli {} <profile>`",
            tool.key()
        );
    }

    launch::launch(tool, &profile, &arguments.args)
}

/// An explicit name always wins. Without one the directory decides, then the
/// saved fallback, and with nothing saved this is the user's existing CLI
/// configuration.
///
/// The second half of the answer is the saved value that chose the profile, and
/// only when neither the command nor the directory did. Callers that hand the
/// terminal to a tool report it; the rest have no reason to.
fn resolve_profile(
    store: &Store,
    workspaces: &Workspaces,
    requested_profile: Option<&str>,
) -> Result<(Profile, Option<Fallback>)> {
    let binding = current_binding(workspaces);

    if let Some(name) = requested_profile {
        let profile = store.load_profile(name)?;
        // Naming a profile inside a bound directory is a one-off, not a
        // rebinding, so the disagreement is worth saying out loud rather than
        // leaving to be noticed later.
        if let Some(binding) = &binding {
            if binding.profile != profile.name {
                eprintln!(
                    "ditto-cli: using '{}' for this run; {} still names '{}'",
                    profile.name,
                    binding.describe_origin(),
                    binding.profile
                );
            }
        }
        return Ok((profile, None));
    }

    if let Some(binding) = binding {
        match store.load_profile(&binding.profile) {
            Ok(profile) => return Ok((profile, None)),
            // A binding outlives the profile it names as soon as that profile
            // is deleted. Saying so and falling through beats refusing to
            // launch anything from the directory until the file is repaired.
            Err(error) => eprintln!(
                "ditto-cli: {} names profile '{}', which is unavailable: {error:#}",
                binding.describe_origin(),
                binding.profile
            ),
        }
    }

    let fallback = store.fallback_profile()?;
    let profile = store.load_profile(fallback.name())?;
    Ok((profile, Some(fallback)))
}

/// The profile a command naming none would use here: the directory's binding
/// when it has a usable one, and the saved fallback otherwise.
///
/// Both `list` and `default` report this, so the precedence rule is stated once
/// rather than restated wherever it is answered.
fn effective_fallback(store: &Store, binding: Option<&workspace::Binding>) -> Result<String> {
    if let Some(binding) = binding {
        // A binding naming a profile that no longer exists is one `resolve`
        // would fall through, so it is not the answer here either.
        if store.load_profile(&binding.profile).is_ok() {
            return Ok(binding.profile.clone());
        }
    }
    Ok(store.fallback_profile()?.name().to_owned())
}

/// The binding covering the current directory. A directory that cannot be read
/// or a file that cannot be parsed is reported and then ignored, because every
/// caller has a working answer without one and none of them is worth failing.
fn current_binding(workspaces: &Workspaces) -> Option<workspace::Binding> {
    match current_directory().and_then(|directory| workspaces.find(&directory)) {
        Ok(binding) => binding,
        Err(error) => {
            eprintln!("ditto-cli: ignoring this directory's profile: {error:#}");
            None
        }
    }
}

/// Records the profile a directory launched with, so the next launch from it
/// needs no name. A directory already answered for by itself or an ancestor is
/// left alone, which is what keeps every subdirectory of a bound project from
/// collecting a file of its own.
///
/// Answers whether the directory came out of this bound, so a caller does not
/// have to work out for itself which of the reasons for declining applied.
fn auto_bind(store: &Store, workspaces: &Workspaces, profile: &str) -> Result<bool> {
    if !store.workspace_auto_bind()? {
        return Ok(false);
    }
    let Ok(directory) = current_directory() else {
        return Ok(false);
    };
    if !workspaces.may_auto_bind(&directory) || workspaces.find(&directory)?.is_some() {
        return Ok(false);
    }

    match workspaces.bind_file(&directory, profile) {
        Ok(path) => {
            println!("Bound this directory to '{profile}' ({}).", path.display());
            Ok(true)
        }
        // A directory there is no permission to write in is not a reason to
        // refuse the launch that was actually asked for.
        Err(error) => {
            eprintln!("ditto-cli: could not bind this directory: {error:#}");
            Ok(false)
        }
    }
}

fn run_workspace(
    store: &Store,
    workspaces: &Workspaces,
    arguments: WorkspaceArgs,
    json: bool,
) -> Result<()> {
    match arguments.command {
        None => show_workspace(workspaces, json),
        Some(WorkspaceCommand::Use {
            profile,
            global,
            path,
        }) => bind_workspace(store, workspaces, &profile, global, path, json),
        Some(WorkspaceCommand::Clear { path }) => clear_workspace(workspaces, path, json),
        Some(WorkspaceCommand::List) => list_workspaces(workspaces, json),
        Some(WorkspaceCommand::Auto { state }) => set_auto_bind(store, state, json),
    }
}

/// A binding in the shape every workspace command reports it, or null where
/// there is none, so a caller can read one field rather than tell an absent
/// binding apart from a failed lookup.
fn binding_payload(binding: Option<&workspace::Binding>) -> Value {
    match binding {
        Some(binding) => json!({
            "profile": binding.profile,
            "directory": binding.directory.display().to_string(),
            "origin": binding.origin_key(),
            "source": binding.describe_origin(),
        }),
        None => Value::Null,
    }
}

fn show_workspace(workspaces: &Workspaces, json: bool) -> Result<()> {
    let directory = current_directory()?;
    let binding = workspaces.find(&directory)?;

    report(
        json,
        || {
            json!({
                "directory": directory.display().to_string(),
                "bound": binding.is_some(),
                "binding": binding_payload(binding.as_ref()),
            })
        },
        || {
            println!("directory={}", directory.display());
            match &binding {
                Some(binding) => {
                    println!("profile={}", binding.profile);
                    println!("source={}", binding.describe_origin());
                }
                None => println!("profile=<unbound>"),
            }
        },
    );
    Ok(())
}

fn bind_workspace(
    store: &Store,
    workspaces: &Workspaces,
    profile: &str,
    global: bool,
    path: Option<PathBuf>,
    json: bool,
) -> Result<()> {
    // Checked before anything is written, so a typo cannot leave a directory
    // bound to a profile that has never existed.
    let profile = store.load_profile(profile)?;
    let directory = directory_argument(path)?;

    let (directory, written) = if global {
        let directory = workspaces.bind_registry(&directory, &profile.name)?;
        let written = workspaces.registry_path().display().to_string();
        (directory, written)
    } else {
        let path = workspaces.bind_file(&directory, &profile.name)?;
        (directory, path.display().to_string())
    };

    report(
        json,
        || {
            json!({
                "profile": profile.name,
                "directory": directory.display().to_string(),
                "origin": if global { "registry" } else { "file" },
                "written": written,
            })
        },
        || {
            println!("Bound {} to '{}'.", directory.display(), profile.name);
            if global {
                println!("Recorded in {written}.");
            } else {
                println!("Wrote {written}.");
            }
        },
    );
    Ok(())
}

fn clear_workspace(workspaces: &Workspaces, path: Option<PathBuf>, json: bool) -> Result<()> {
    let directory = directory_argument(path)?;
    let removed = workspaces.clear(&directory)?;
    // Clearing only ever touches the one directory, so an ancestor can still be
    // answering for it and the caller should not have to re-run to discover it.
    let inherited = workspaces.find(&directory)?;

    report(
        json,
        || {
            json!({
                "directory": directory.display().to_string(),
                "removed": removed,
                "inherits": binding_payload(inherited.as_ref()),
            })
        },
        || {
            if removed.is_empty() {
                println!("{} was not bound.", directory.display());
            } else {
                for entry in &removed {
                    println!("Removed {entry}.");
                }
            }
            if let Some(binding) = &inherited {
                println!(
                    "{} now inherits '{}' from {}.",
                    directory.display(),
                    binding.profile,
                    binding.describe_origin()
                );
            }
        },
    );
    Ok(())
}

fn list_workspaces(workspaces: &Workspaces, json: bool) -> Result<()> {
    let entries = workspaces.entries()?;

    report(
        json,
        || {
            json!({
                "workspaces": entries
                    .iter()
                    .map(|(directory, profile)| json!({
                        "directory": directory.display().to_string(),
                        "profile": profile,
                    }))
                    .collect::<Vec<_>>(),
                "registry": workspaces.registry_path().display().to_string(),
                // Files are found by walking up from wherever Ditto runs, so
                // there is no set of them to enumerate. Saying so in the payload
                // keeps this from reading as every binding that exists.
                "includes_files": false,
            })
        },
        || {
            if entries.is_empty() {
                println!("No directories are recorded in the registry.");
            } else {
                for (directory, profile) in &entries {
                    println!("{:<48} {profile}", directory.display());
                }
            }
            println!();
            println!(
                "{WORKSPACE_FILE} files are not listed: they are found by walking up from the \
                 directory"
            );
            println!("Ditto runs in. Run `ditto-cli workspace` to see the one in effect here.");
        },
    );
    Ok(())
}

fn set_auto_bind(store: &Store, state: Option<AutoState>, json: bool) -> Result<()> {
    if let Some(state) = state {
        store.set_workspace_auto_bind(state.enabled())?;
    }

    let enabled = store.workspace_auto_bind()?;
    report(
        json,
        || json!({ "auto_bind": enabled }),
        || {
            println!(
                "Launching from an unbound directory {} it.",
                if enabled { "binds" } else { "does not bind" }
            );
        },
    );
    Ok(())
}

fn directory_argument(path: Option<PathBuf>) -> Result<PathBuf> {
    match path {
        Some(path) => {
            if !path.is_dir() {
                anyhow::bail!("{} is not a directory", path.display());
            }
            Ok(path)
        }
        None => current_directory(),
    }
}

fn current_directory() -> Result<PathBuf> {
    std::env::current_dir().context("could not determine the current directory")
}

fn print_login_instructions(profile: &Profile) {
    println!();
    println!(
        "Open `ditto-cli`, select '{}', then press l to sign in to Claude Code, Codex, fx, opencode, or Prime Agent.",
        profile.name
    );
    println!();
    println!("Or authenticate directly:");
    println!("  ditto-cli claude {} -- auth login", profile.name);
    println!("  ditto-cli codex {} -- login", profile.name);
    println!("  ditto-cli fx {} -- login", profile.name);
    println!("  ditto-cli opencode {} -- auth login", profile.name);
    println!("  ditto-cli prime-agent {} -- /login", profile.name);
    println!();
    println!("Launch OMP or Pi, then use `/login` inside it:");
    println!("  ditto-cli omp {}", profile.name);
    println!("  ditto-cli pi {}", profile.name);
    println!();
    println!("Every other agent runs the same way; `ditto-cli --help` lists them:");
    println!(
        "  ditto-cli <agent> {} -- <its login arguments>",
        profile.name
    );
}