worktrunk 0.50.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
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
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
use std::collections::HashSet;
use std::io::Write;
use std::path::Path;

use anyhow::Context;
use clap::FromArgMatches;
use clap::error::ErrorKind as ClapErrorKind;
use color_print::{ceprintln, cformat};
use std::process;
use worktrunk::config::{Approvals, UserConfig, set_config_path};
use worktrunk::git::{
    ErrorExt, Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint,
    set_base_path,
};
use worktrunk::styling::{
    eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,
};

use commands::command_approval::approve_command_batch;
use commands::hooks::HookAnnouncer;
use commands::project_config::collect_remove_hook_commands;
use commands::worktree::RemoveResult;

mod cli;
mod commands;
mod completion;
mod diagnostic;
mod display;
mod help;
pub(crate) mod help_pager;
mod invocation;
mod llm;
mod log_files;
mod md_help;
mod output;
mod pager;
mod summary;

// Re-export invocation utilities at crate level for use by other modules
pub(crate) use invocation::{
    binary_name, invocation_path, is_git_subcommand, was_invoked_with_explicit_path,
};

pub(crate) use crate::cli::OutputFormat;

use commands::commit::HookGate;
#[cfg(unix)]
use commands::handle_picker;
use commands::repository_ext::RepositoryCliExt;
use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};
use commands::{
    HookCliArgs, MergeFlagOverrides, MergeOptions, OperationMode, RebaseResult, RemoveTarget,
    SquashResult, SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run,
    handle_alias_show, handle_claude_install, handle_claude_install_statusline,
    handle_claude_uninstall, handle_completions, handle_config_create, handle_config_show,
    handle_config_update, handle_configure_shell, handle_custom_command, handle_hints_clear,
    handle_hints_get, handle_hook_show, handle_init, handle_list, handle_logs_list, handle_merge,
    handle_opencode_install, handle_opencode_uninstall, handle_promote, handle_rebase,
    handle_show_theme, handle_squash, handle_state_clear, handle_state_clear_all, handle_state_get,
    handle_state_set, handle_state_show, handle_unconfigure_shell, handle_vars_clear,
    handle_vars_get, handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch,
    step_commit, step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate,
};
use output::handle_remove_output;
use worktrunk::git::BranchDeletionMode;

use cli::{
    ApprovalsCommand, CiStatusAction, Cli, Commands, ConfigAliasCommand, ConfigCommand,
    ConfigPluginsClaudeCommand, ConfigPluginsCommand, ConfigPluginsOpencodeCommand,
    ConfigShellCommand, DefaultBranchAction, HintsAction, HookCommand, HookOptions, ListArgs,
    ListSubcommand, LogsAction, MarkerAction, MergeArgs, PreviousBranchAction, RemoveArgs,
    StateCommand, StepCommand, SwitchArgs, SwitchFormat, VarsAction,
};

/// Render a clap error to stderr, appending a wt-specific nested-subcommand
/// tip when the unknown name matches something under `wt step` / `wt hook`
/// (e.g., `wt squash` → `wt step squash`). Shared between the diverging
/// `enhance_and_exit_error` (pre-dispatch) and the non-diverging
/// `enhance_clap_error` (post-dispatch).
fn print_enhanced_clap_error(err: &clap::Error) {
    if err.kind() == ClapErrorKind::InvalidSubcommand
        && let Some(unknown) = err.get(clap::error::ContextKind::InvalidSubcommand)
    {
        let cmd = cli::build_command();
        if let Some(suggestion) = cli::suggest_nested_subcommand(&cmd, &unknown.to_string()) {
            ceprintln!(
                "{}
  <yellow>tip:</>  perhaps <cyan,bold>{suggestion}</cyan,bold>?",
                err.render().ansi()
            );
            return;
        }
    }
    let _ = err.print();
}

/// Enhance clap errors with command-specific hints, then exit.
///
/// Used by the pre-dispatch parse path, where no `finish_command` cleanup has
/// been set up yet — `process::exit` directly is fine. Post-dispatch callers
/// (e.g. alias typos from `wt step <typo>` / `wt <typo>`) use
/// [`enhance_clap_error`] so they flow back through `handle_command_failure`
/// and run the diagnostic/output-reset cleanup.
pub(crate) fn enhance_and_exit_error(err: clap::Error) -> ! {
    print_enhanced_clap_error(&err);
    process::exit(err.exit_code());
}

/// Print an enhanced clap error and return `AlreadyDisplayed` so the caller
/// can propagate it through normal error handling, letting `finish_command`
/// run (diagnostic writes, ANSI reset for shell integration).
pub(crate) fn enhance_clap_error(err: clap::Error) -> anyhow::Error {
    let exit_code = err.exit_code();
    print_enhanced_clap_error(&err);
    WorktrunkError::AlreadyDisplayed { exit_code }.into()
}

#[cfg(not(unix))]
fn print_windows_picker_unavailable() {
    eprintln!(
        "{}",
        error_message("Interactive picker is not available on Windows")
    );
    eprintln!(
        "{}",
        hint_message(cformat!("Specify a branch: <underline>wt switch BRANCH</>"))
    );
}

pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
    match (positive, negative) {
        (true, _) => Some(true),
        (_, true) => Some(false),
        _ => None,
    }
}

fn warn_select_deprecated() {
    eprintln!(
        "{}",
        warning_message("wt select is deprecated; use wt switch instead")
    );
}

/// Resolve the `--no-hooks` / `--no-verify` pair: emit a deprecation warning
/// if the old flag was used, then return the effective verify value.
fn resolve_verify(verify: bool, no_verify_deprecated: bool) -> bool {
    if no_verify_deprecated {
        eprintln!(
            "{}",
            warning_message("--no-verify is deprecated; use --no-hooks instead")
        );
        false
    } else {
        verify
    }
}

fn handle_hook_command(action: HookCommand, yes: bool) -> anyhow::Result<()> {
    match action {
        HookCommand::Show {
            hook_type,
            expanded,
            format,
        } => handle_hook_show(hook_type.as_deref(), expanded, format),
        HookCommand::RunPipeline => commands::run_pipeline(),
        HookCommand::Approvals { action } => {
            eprintln!(
                "{}",
                warning_message("wt hook approvals is deprecated; use wt config approvals instead")
            );
            match action {
                ApprovalsCommand::Add { all } => add_approvals(all),
                ApprovalsCommand::Clear { global } => clear_approvals(global),
            }
        }
        HookCommand::Run(args) => {
            // `--help` / `-h` is handled upstream in `maybe_handle_help_with_pager`,
            // which parses against a clap tree augmented with hook-type
            // subcommand stubs and renders their help directly. Execution flow
            // only reaches here for non-help invocations.
            if args.first().and_then(|s| s.to_str()) == Some("post-create") {
                eprintln!(
                    "{}",
                    warning_message(
                        "wt hook post-create is deprecated; use wt hook pre-start instead"
                    )
                );
            }
            let opts = HookOptions::parse(&args)?;
            run_hook(
                opts.hook_type,
                yes || opts.yes,
                opts.foreground,
                opts.dry_run,
                HookCliArgs {
                    name_filters: &opts.name_filters,
                    explicit_vars: &opts.explicit_vars,
                    shorthand_vars: &opts.shorthand_vars,
                    forwarded_args: &opts.forwarded_args,
                },
            )
        }
    }
}

fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
    match action {
        StepCommand::Commit(args) => {
            let verify = resolve_verify(args.verify, args.no_verify_deprecated);
            let format = args.format;
            // `--show-prompt` and `--dry-run` emit raw text (rendered prompt or LLM
            // preview), which would corrupt a JSON consumer's stdout. Refuse the
            // combination rather than silently emit non-JSON.
            if format == SwitchFormat::Json && (args.show_prompt || args.dry_run) {
                anyhow::bail!("--show-prompt / --dry-run cannot be combined with --format=json");
            }
            let outcome = step_commit(
                args.branch,
                yes,
                verify,
                args.stage,
                args.show_prompt,
                args.dry_run,
            )?;
            if format == SwitchFormat::Json
                && let Some(outcome) = outcome
            {
                let payload = serde_json::json!({
                    "commit": outcome.sha,
                    "message": outcome.message,
                    "stage_mode": outcome.stage_mode,
                });
                println!("{}", serde_json::to_string_pretty(&payload)?);
            }
            Ok(())
        }
        StepCommand::Squash(args) => {
            let verify = resolve_verify(args.verify, args.no_verify_deprecated);
            // `--show-prompt` and `--dry-run` emit raw text (rendered prompt or LLM
            // preview), which would corrupt a JSON consumer's stdout.
            if args.format == SwitchFormat::Json && (args.show_prompt || args.dry_run) {
                anyhow::bail!("--show-prompt / --dry-run cannot be combined with --format=json");
            }
            // --show-prompt and --dry-run skip the squash and exit after preview output.
            if args.show_prompt {
                commands::step_show_squash_prompt(args.target.as_deref())
            } else if args.dry_run {
                commands::step_dry_run_squash(args.target.as_deref())
            } else {
                // Approval is handled inside handle_squash (like step_commit).
                let repo = Repository::current()?;
                let config = UserConfig::load().context("Failed to load config")?;
                let hooks = if verify {
                    HookGate::Run
                } else {
                    HookGate::NoHooksFlag
                };
                let mut announcer = HookAnnouncer::new(&repo, &config, false);
                let format = args.format;
                let result = handle_squash(
                    args.target.as_deref(),
                    yes,
                    hooks,
                    args.stage,
                    &mut announcer,
                )?;
                announcer.flush()?;
                if format == SwitchFormat::Json {
                    let payload = match &result {
                        SquashResult::Squashed {
                            sha,
                            message,
                            stage_mode,
                        } => serde_json::json!({
                            "outcome": "squashed",
                            "commit": sha,
                            "message": message,
                            "stage_mode": stage_mode,
                        }),
                        SquashResult::NoCommitsAhead(target) => serde_json::json!({
                            "outcome": "no_commits_ahead",
                            "target": target,
                        }),
                        SquashResult::AlreadySingleCommit => serde_json::json!({
                            "outcome": "already_single_commit",
                        }),
                        SquashResult::NoNetChanges => serde_json::json!({
                            "outcome": "no_net_changes",
                        }),
                    };
                    println!("{}", serde_json::to_string_pretty(&payload)?);
                } else {
                    match result {
                        SquashResult::Squashed { .. } | SquashResult::NoNetChanges => {}
                        SquashResult::NoCommitsAhead(branch) => {
                            eprintln!(
                                "{}",
                                info_message(cformat!(
                                    "Nothing to squash; no commits ahead of <bold>{branch}</>"
                                ))
                            );
                        }
                        SquashResult::AlreadySingleCommit => {
                            eprintln!(
                                "{}",
                                info_message("Nothing to squash; already a single commit")
                            );
                        }
                    }
                }
                Ok(())
            }
        }
        StepCommand::Push {
            target,
            no_ff,
            format,
            ..
        } => {
            let result = if no_ff {
                let repo = Repository::current()?;
                let current_branch = repo.require_current_branch("step push --no-ff")?;
                handle_no_ff_merge(target.as_deref(), None, &current_branch)?
            } else {
                handle_push(target.as_deref(), PushKind::Standalone, None)?
            };
            if format == SwitchFormat::Json {
                let PushResult {
                    target,
                    commit_count,
                    outcome,
                } = result;
                let mut payload = serde_json::json!({
                    "target": target,
                    "outcome": match outcome {
                        PushOutcome::FastForwarded => "fast_forwarded",
                        PushOutcome::UpToDate => "up_to_date",
                        PushOutcome::MergeCommit { .. } => "merge_commit",
                    },
                    "commits": commit_count,
                });
                if let PushOutcome::MergeCommit { merge_sha } = outcome {
                    payload["merge_sha"] = serde_json::Value::String(merge_sha);
                }
                println!("{}", serde_json::to_string_pretty(&payload)?);
            }
            Ok(())
        }
        StepCommand::Rebase { target, format } => {
            let result = handle_rebase(target.as_deref())?;
            if format == SwitchFormat::Json {
                let output = match &result {
                    RebaseResult::Rebased {
                        target,
                        fast_forward,
                    } => serde_json::json!({
                        "target": target,
                        "outcome": if *fast_forward { "fast_forwarded" } else { "rebased" },
                    }),
                    RebaseResult::UpToDate(target) => serde_json::json!({
                        "target": target,
                        "outcome": "up_to_date",
                    }),
                };
                println!("{}", serde_json::to_string_pretty(&output)?);
            } else if let RebaseResult::UpToDate(branch) = &result {
                eprintln!(
                    "{}",
                    info_message(cformat!("Already up to date with <bold>{branch}</>"))
                );
            }
            Ok(())
        }
        StepCommand::Diff { target, extra_args } => step_diff(target.as_deref(), &extra_args),
        StepCommand::CopyIgnored {
            from,
            to,
            dry_run,
            force,
            format,
        } => step_copy_ignored(from.as_deref(), to.as_deref(), dry_run, force, format),
        StepCommand::Eval { template, dry_run } => step_eval(&template, dry_run),
        StepCommand::ForEach { format, args } => step_for_each(args, format),
        StepCommand::Promote { branch } => {
            handle_promote(branch.as_deref()).map(|result| match result {
                commands::PromoteResult::Promoted => (),
                commands::PromoteResult::AlreadyInMain(branch) => {
                    eprintln!(
                        "{}",
                        info_message(cformat!(
                            "Branch <bold>{branch}</> is already in main worktree"
                        ))
                    );
                }
            })
        }
        StepCommand::Prune {
            dry_run,
            min_age,
            foreground,
            format,
        } => step_prune(dry_run, yes, &min_age, foreground, format),
        StepCommand::Relocate {
            branches,
            dry_run,
            commit,
            clobber,
            format,
        } => step_relocate(branches, dry_run, commit, clobber, format),
        StepCommand::External(args) => commands::step_alias(args, yes),
    }
}

/// Exit with a clap-style `ArgumentConflict` error when `--format` is combined
/// with a write action (set/clear) on the state subcommands where it has no
/// effect. Clap accepts the flag because `--format` is declared `global = true`
/// on the parent so the bareword and `get` forms work, but write actions don't
/// emit structured output — silent acceptance is a surprise.
///
/// Populates `InvalidArg` / `PriorArg` context rather than passing a raw
/// message so clap renders the arg name and subcommand with its own `invalid`
/// style, matching native conflict errors byte-for-byte.
fn guard_format_on_write(action_name: &str, format: SwitchFormat) {
    if format == SwitchFormat::Text {
        return;
    }
    let mut cmd = cli::build_command();
    let usage = cmd.render_usage();
    let mut err = clap::Error::new(ClapErrorKind::ArgumentConflict).with_cmd(&cmd);
    err.insert(
        clap::error::ContextKind::InvalidArg,
        clap::error::ContextValue::String("--format <FORMAT>".to_owned()),
    );
    err.insert(
        clap::error::ContextKind::PriorArg,
        clap::error::ContextValue::String(action_name.to_owned()),
    );
    err.insert(
        clap::error::ContextKind::Usage,
        clap::error::ContextValue::StyledStr(usage),
    );
    err.exit()
}

fn handle_state_command(action: StateCommand) -> anyhow::Result<()> {
    match action {
        StateCommand::DefaultBranch { action } => match action {
            Some(DefaultBranchAction::Get) | None => {
                handle_state_get("default-branch", None, SwitchFormat::Text)
            }
            Some(DefaultBranchAction::Set { branch }) => {
                handle_state_set("default-branch", branch, None)
            }
            Some(DefaultBranchAction::Clear) => handle_state_clear("default-branch", None, false),
        },
        StateCommand::PreviousBranch { action } => match action {
            Some(PreviousBranchAction::Get) | None => {
                handle_state_get("previous-branch", None, SwitchFormat::Text)
            }
            Some(PreviousBranchAction::Set { branch }) => {
                handle_state_set("previous-branch", branch, None)
            }
            Some(PreviousBranchAction::Clear) => handle_state_clear("previous-branch", None, false),
        },
        StateCommand::CiStatus { action, format } => match action {
            Some(CiStatusAction::Get { branch }) => handle_state_get("ci-status", branch, format),
            None => handle_state_get("ci-status", None, format),
            Some(CiStatusAction::Clear { branch, all }) => {
                guard_format_on_write("clear", format);
                handle_state_clear("ci-status", branch, all)
            }
        },
        StateCommand::Marker { action, format } => match action {
            Some(MarkerAction::Get { branch }) => handle_state_get("marker", branch, format),
            None => handle_state_get("marker", None, format),
            Some(MarkerAction::Set { value, branch }) => {
                guard_format_on_write("set", format);
                handle_state_set("marker", value, branch)
            }
            Some(MarkerAction::Clear { branch, all }) => {
                guard_format_on_write("clear", format);
                handle_state_clear("marker", branch, all)
            }
        },
        StateCommand::Logs { action, format } => match action {
            Some(LogsAction::Get) | None => handle_logs_list(format),
            Some(LogsAction::Clear) => {
                guard_format_on_write("clear", format);
                handle_state_clear("logs", None, false)
            }
        },
        StateCommand::Hints { action, format } => match action {
            Some(HintsAction::Get) | None => handle_hints_get(format),
            Some(HintsAction::Clear { name }) => {
                guard_format_on_write("clear", format);
                handle_hints_clear(name)
            }
        },
        StateCommand::Vars { action } => match action {
            VarsAction::Get { key, branch } => handle_vars_get(&key, branch),
            VarsAction::Set {
                assignment: (key, value),
                branch,
            } => handle_vars_set(&key, &value, branch),
            VarsAction::List { branch, format } => handle_vars_list(branch, format),
            VarsAction::Clear { key, all, branch } => {
                handle_vars_clear(key.as_deref(), all, branch)
            }
        },
        StateCommand::Get { format } => handle_state_show(format),
        StateCommand::Clear => handle_state_clear_all(),
    }
}

fn handle_config_shell_command(action: ConfigShellCommand, yes: bool) -> anyhow::Result<()> {
    match action {
        ConfigShellCommand::Init { shell, cmd } => {
            // Generate shell code to stdout
            let cmd = cmd.unwrap_or_else(binary_name);
            handle_init(shell, cmd).map_err(|e| anyhow::anyhow!("{}", e))
        }
        ConfigShellCommand::Install {
            shell,
            dry_run,
            cmd,
        } => {
            // Auto-write to shell config files and completions
            let cmd = cmd.unwrap_or_else(binary_name);
            handle_configure_shell(shell, yes, dry_run, cmd)
                .map_err(|e| anyhow::anyhow!("{}", e))
                .and_then(|scan_result| {
                    // Exit with error if no shells configured
                    // Show skipped shells first so user knows what was tried
                    if scan_result.configured.is_empty() {
                        crate::output::print_skipped_shells(&scan_result.skipped);
                        return Err(worktrunk::git::GitError::Other {
                            message: "No shell config files found".into(),
                        }
                        .into());
                    }
                    // For --dry-run, preview was already shown by handler
                    if dry_run {
                        return Ok(());
                    }
                    crate::output::print_shell_install_result(&scan_result);
                    Ok(())
                })
        }
        ConfigShellCommand::Uninstall { shell, dry_run } => {
            let explicit_shell = shell.is_some();
            handle_unconfigure_shell(shell, yes, dry_run, &binary_name())
                .map_err(|e| anyhow::anyhow!("{}", e))
                .map(|result| {
                    if !dry_run {
                        crate::output::print_shell_uninstall_result(&result, explicit_shell);
                    }
                })
        }
        ConfigShellCommand::ShowTheme => {
            handle_show_theme();
            Ok(())
        }
        ConfigShellCommand::Completions { shell } => handle_completions(shell),
    }
}

fn handle_config_command(action: ConfigCommand, yes: bool) -> anyhow::Result<()> {
    match action {
        ConfigCommand::Shell { action } => handle_config_shell_command(action, yes),
        ConfigCommand::Create { project } => handle_config_create(project),
        ConfigCommand::Show { full, format } => handle_config_show(full, format),
        ConfigCommand::Update { print } => handle_config_update(yes, print),
        ConfigCommand::Approvals { action } => match action {
            ApprovalsCommand::Add { all } => add_approvals(all),
            ApprovalsCommand::Clear { global } => clear_approvals(global),
        },
        ConfigCommand::Alias { action } => match action {
            ConfigAliasCommand::Show { name } => handle_alias_show(name),
            ConfigAliasCommand::DryRun { name, args } => handle_alias_dry_run(name, args),
        },
        ConfigCommand::Plugins { action } => handle_plugins_command(action, yes),
        ConfigCommand::State { action } => handle_state_command(action),
    }
}

fn handle_plugins_command(action: ConfigPluginsCommand, yes: bool) -> anyhow::Result<()> {
    match action {
        ConfigPluginsCommand::Claude { action } => match action {
            ConfigPluginsClaudeCommand::Install => handle_claude_install(yes),
            ConfigPluginsClaudeCommand::Uninstall => handle_claude_uninstall(yes),
            ConfigPluginsClaudeCommand::InstallStatusline => handle_claude_install_statusline(yes),
        },
        ConfigPluginsCommand::Opencode { action } => match action {
            ConfigPluginsOpencodeCommand::Install => handle_opencode_install(yes),
            ConfigPluginsOpencodeCommand::Uninstall => handle_opencode_uninstall(yes),
        },
    }
}

fn handle_list_command(args: ListArgs) -> anyhow::Result<()> {
    match args.subcommand {
        Some(ListSubcommand::Statusline {
            format,
            claude_code,
        }) => {
            if claude_code {
                eprintln!(
                    "{}",
                    warning_message(
                        "--claude-code is deprecated; use --format=claude-code instead"
                    )
                );
            }
            // Hidden --claude-code flag only applies when format is default (Table)
            // Explicit --format=json takes precedence over --claude-code
            let effective_format = if claude_code && matches!(format, OutputFormat::Table) {
                OutputFormat::ClaudeCode
            } else {
                format
            };
            commands::statusline::run(effective_format)
        }
        None => {
            let (repo, _recovered) = current_or_recover()?;
            handle_list(
                repo,
                args.format,
                args.branches,
                args.remotes,
                args.full,
                flag_pair(args.progressive, args.no_progressive),
            )
        }
    }
}

#[cfg(unix)]
fn handle_select_command(branches: bool, remotes: bool) -> anyhow::Result<()> {
    // Deprecated: show warning and delegate to handle_picker
    warn_select_deprecated();
    worktrunk::config::suppress_warnings();
    handle_picker(branches, remotes, None)
}

#[cfg(not(unix))]
fn handle_select_command(_branches: bool, _remotes: bool) -> anyhow::Result<()> {
    use worktrunk::git::WorktrunkError;
    warn_select_deprecated();
    print_windows_picker_unavailable();
    Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())
}

fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()> {
    let verify = resolve_verify(args.verify, args.no_verify_deprecated);

    // With no branch argument, `wt switch` opens a TUI picker — config
    // deprecation warnings would render above the picker and push it down.
    // They're still shown by other commands (`wt list`, `wt merge`, …).
    if args.branch.is_none() {
        worktrunk::config::suppress_warnings();
    }

    UserConfig::load()
        .context("Failed to load config")
        .and_then(|mut config| {
            // No branch argument: open interactive picker
            let change_dir_flag = flag_pair(args.cd, args.no_cd);

            let Some(branch) = args.branch else {
                #[cfg(unix)]
                {
                    return handle_picker(args.branches, args.remotes, change_dir_flag);
                }

                #[cfg(not(unix))]
                {
                    use worktrunk::git::WorktrunkError;
                    // Suppress unused variable warnings on Windows
                    let _ = (args.branches, args.remotes, change_dir_flag);

                    print_windows_picker_unavailable();
                    return Err(WorktrunkError::AlreadyDisplayed { exit_code: 2 }.into());
                }
            };

            run_switch(
                SwitchOptions {
                    branch: &branch,
                    create: args.create,
                    base: args.base.as_deref(),
                    execute: args.execute.as_deref(),
                    execute_args: &args.execute_args,
                    yes,
                    clobber: args.clobber,
                    change_dir: change_dir_flag,
                    verify,
                    format: args.format,
                },
                &mut config,
                &binary_name(),
            )
        })
}

/// Validated removal plans, categorized for ordered execution.
///
/// Multi-worktree removal validates all targets upfront, then executes in order:
/// other worktrees first, branch-only cases next, current worktree last.
struct RemovePlans {
    others: Vec<RemoveResult>,
    branch_only: Vec<RemoveResult>,
    current: Option<RemoveResult>,
    errors: Vec<anyhow::Error>,
}

impl RemovePlans {
    fn has_valid_plans(&self) -> bool {
        !self.others.is_empty() || !self.branch_only.is_empty() || self.current.is_some()
    }

    fn record_error(&mut self, e: anyhow::Error) {
        // The remove command collects per-target errors and surfaces each
        // individually (partial-success path). Render the typed
        // diagnostic block when present so locked/dirty/etc. errors
        // carry their hint, falling back to the short label otherwise.
        let rendered = e.render_diagnostic().unwrap_or_else(|| e.to_string());
        if !rendered.is_empty() {
            eprintln!("{rendered}");
        }
        self.errors.push(e);
    }
}

/// Validate all removal targets, returning categorized plans.
///
/// Resolves each branch name, determines whether it's the current worktree,
/// another worktree, or branch-only, and prepares the removal plan.
/// Errors are collected (not fatal) to support partial success.
fn validate_remove_targets(
    repo: &Repository,
    branches: Vec<String>,
    config: &UserConfig,
    keep_branch: bool,
    force_delete: bool,
    force: bool,
) -> RemovePlans {
    let current_worktree = repo
        .current_worktree()
        .root()
        .ok()
        .and_then(|p| dunce::canonicalize(&p).ok());

    // Dedupe inputs to avoid redundant planning/execution
    let branches: Vec<_> = {
        let mut seen = HashSet::new();
        branches
            .into_iter()
            .filter(|b| seen.insert(b.clone()))
            .collect()
    };

    let deletion_mode = BranchDeletionMode::from_flags(keep_branch, force_delete);
    let worktrees = repo.list_worktrees().ok();

    // Capture once for the validation loop. Validation only reads — actual
    // removals run later in `handle_remove_output`, so ref state is stable
    // across candidates here. Errors propagate to per-candidate calls, which
    // fall back to capturing internally when None.
    let snapshot = repo.capture_refs().ok();

    let mut plans = RemovePlans {
        others: Vec::new(),
        branch_only: Vec::new(),
        current: None,
        errors: Vec::new(),
    };

    for branch_name in &branches {
        let resolved = match resolve_worktree_arg(repo, branch_name, config, OperationMode::Remove)
        {
            Ok(r) => r,
            Err(e) => {
                plans.record_error(e);
                continue;
            }
        };

        match resolved {
            ResolvedWorktree::Worktree { path, branch } => {
                // Use canonical paths to avoid symlink/normalization mismatches
                let path_canonical = dunce::canonicalize(&path).unwrap_or(path);
                let is_current = current_worktree.as_ref() == Some(&path_canonical);

                if is_current {
                    match repo.prepare_worktree_removal(
                        RemoveTarget::Current,
                        deletion_mode,
                        force,
                        config,
                        None,
                        worktrees,
                        snapshot.as_ref(),
                    ) {
                        Ok(result) => plans.current = Some(result),
                        Err(e) => plans.record_error(e),
                    }
                    continue;
                }

                // Non-current worktree: remove by branch name, or by path for
                // detached worktrees (which have no branch).
                let target = if let Some(ref branch_name) = branch {
                    RemoveTarget::Branch(branch_name)
                } else {
                    RemoveTarget::Path(&path_canonical)
                };
                match repo.prepare_worktree_removal(
                    target,
                    deletion_mode,
                    force,
                    config,
                    None,
                    worktrees,
                    snapshot.as_ref(),
                ) {
                    Ok(result) => plans.others.push(result),
                    Err(e) => plans.record_error(e),
                }
            }
            ResolvedWorktree::BranchOnly { branch } => {
                match repo.prepare_worktree_removal(
                    RemoveTarget::Branch(&branch),
                    deletion_mode,
                    force,
                    config,
                    None,
                    worktrees,
                    snapshot.as_ref(),
                ) {
                    Ok(result) => plans.branch_only.push(result),
                    Err(e) => plans.record_error(e),
                }
            }
        }
    }

    plans
}

/// Entry point for the `wt remove` command.
///
/// # Command flow
///
/// 1. **Validate** all target worktrees up front via `prepare_worktree_removal`
///    (clean check, branch-deletion-safety check, force-flag handling).
/// 2. **Approve hooks** (`pre-remove`, `post-remove`, `post-switch`) if
///    running interactively and any hooks are configured.
/// 3. **Dispatch to `handle_remove_output`** per target. For each, the output
///    handler runs `pre-remove` hooks in the worktree, then either:
///    - **Foreground** (`--foreground`): stop fsmonitor → rename into
///      `.git/wt/trash/<name>-<timestamp>/` → prune metadata → delete branch
///      → synchronous `remove_dir_all` on the staged directory.
///    - **Background** (default): stop fsmonitor → rename + prune +
///      synchronous branch delete → spawn detached `rm -rf` on the staged
///      directory. Cross-filesystem or locked worktrees fall back to
///      `git worktree remove` in the detached process.
/// 4. **Post-remove hooks** run in the background after dispatch.
/// 5. **Sweep stale trash** (fire-and-forget, after primary output): entries
///    in `.git/wt/trash/` older than 24 hours are removed by a detached
///    `rm -rf`. Runs last so it never delays the user-visible progress or
///    success message. See [`commands::process::sweep_stale_trash`].
fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
    let json_mode = args.format == SwitchFormat::Json;
    let verify = resolve_verify(args.verify, args.no_verify_deprecated);
    UserConfig::load()
        .context("Failed to load config")
        .and_then(|config| {
            let repo = Repository::current().context("Failed to remove worktree")?;

            // CLI flags override config; otherwise fall through to [remove] delete-branch
            // (defaults to true).
            let project = repo.project_identifier().ok();
            let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);
            let delete_branch =
                cli_override.unwrap_or_else(|| config.remove(project.as_deref()).delete_branch());

            // Validate conflicting flags
            if !delete_branch && args.force_delete {
                return Err(worktrunk::git::GitError::Other {
                    message: "Cannot use --force-delete with delete-branch=false (set via --no-delete-branch or [remove] delete-branch = false)".into(),
                }
                .into());
            }

            // Helper: approve every command the removal will run, in one batch.
            // `pre-remove` / `post-remove` resolve their `.config/wt.toml` from
            // each worktree being removed (`removed_worktree_paths`); `post-switch`
            // resolves from each removal's post-removal destination
            // (`destination_paths` — `RemoveResult::destination_path()`, normally
            // the primary worktree, cwd when the primary worktree is itself the
            // removal target). No fallback between worktrees, same rule as the
            // executors. The shared helper assembles them all, dedup'd by template.
            // Returns `true` when the prompt was accepted or there was nothing to
            // approve.
            let approve_remove =
                |removed_worktree_paths: &[&Path], destination_paths: &[&Path], yes: bool| -> anyhow::Result<bool> {
                    let commands = collect_remove_hook_commands(
                        removed_worktree_paths,
                        destination_paths,
                    )?;
                    if commands.is_empty() {
                        return Ok(true);
                    }
                    let project_id = repo.project_identifier()?;
                    let approvals = Approvals::load().context("Failed to load approvals")?;
                    let approved =
                        approve_command_batch(&commands, &project_id, &approvals, yes, false)?;
                    if !approved {
                        eprintln!("{}", info_message("Commands declined, continuing removal"));
                    }
                    Ok(approved)
                };

            let branches = args.branches;

            if branches.is_empty() {
                // Single worktree removal: validate FIRST, then approve, then execute
                let result = repo
                    .prepare_worktree_removal(
                        RemoveTarget::Current,
                        BranchDeletionMode::from_flags(!delete_branch, args.force_delete),
                        args.force,
                        &config,
                        None,
                        None,
                        None,
                    )
                    .context("Failed to remove worktree")?;

                // Early exit for benchmarking time-to-first-output
                if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
                    return Ok(());
                }

                // "Approve at the Gate": approval happens AFTER validation passes
                let run_hooks = verify
                    && approve_remove(
                        result.removed_worktree_path().as_slice(),
                        result.destination_path().as_slice(),
                        yes,
                    )?;

                let mut announcer = HookAnnouncer::new(&repo, &config, false);
                handle_remove_output(
                    &result,
                    args.foreground,
                    run_hooks,
                    false,
                    false,
                    &mut announcer,
                )?;
                announcer.flush()?;
                if json_mode {
                    let json = serde_json::json!([result.to_json()]);
                    println!("{}", serde_json::to_string_pretty(&json)?);
                }
                // Fire-and-forget cleanup of stale `.git/wt/trash/` entries —
                // runs after primary output so it never delays the user-visible
                // progress/success message.
                commands::process::sweep_stale_trash(&repo);
                Ok(())
            } else {
                // Multi-worktree removal: validate ALL first, then approve, then execute
                let plans = validate_remove_targets(
                    &repo,
                    branches,
                    &config,
                    !delete_branch,
                    args.force_delete,
                    args.force,
                );

                if !plans.has_valid_plans() {
                    anyhow::bail!("");
                }

                // Early exit for benchmarking time-to-first-output
                if std::env::var_os("WORKTRUNK_FIRST_OUTPUT").is_some() {
                    return Ok(());
                }

                // Approve hooks (only if we have valid plans). Each removed
                // worktree's `pre-remove` / `post-remove` is approved against
                // that worktree's config, and its `post-switch` against the
                // worktree the user lands in — see `approve_remove` above.
                // (`destination_targets` is mostly the primary worktree
                // repeated; the helper dedups by template.)
                let all_plans = || {
                    plans
                        .others
                        .iter()
                        .chain(&plans.branch_only)
                        .chain(plans.current.iter())
                };
                let removed_targets: Vec<&Path> =
                    all_plans().filter_map(|r| r.removed_worktree_path()).collect();
                let destination_targets: Vec<&Path> =
                    all_plans().filter_map(|r| r.destination_path()).collect();
                let run_hooks =
                    verify && approve_remove(&removed_targets, &destination_targets, yes)?;

                // Execute all validated plans: others first, branch-only next, current last
                let show_branch =
                    plans.others.len() + plans.branch_only.len() + plans.current.iter().len() > 1;
                let run = |result: &RemoveResult| -> anyhow::Result<()> {
                    let mut announcer = HookAnnouncer::new(&repo, &config, show_branch);
                    handle_remove_output(
                        result,
                        args.foreground,
                        run_hooks,
                        false,
                        false,
                        &mut announcer,
                    )?;
                    announcer.flush()
                };
                for result in &plans.others {
                    run(result)?;
                }
                for result in &plans.branch_only {
                    run(result)?;
                }
                if let Some(ref result) = plans.current {
                    run(result)?;
                }

                if json_mode {
                    let json_items: Vec<serde_json::Value> = plans
                        .others
                        .iter()
                        .chain(&plans.branch_only)
                        .chain(plans.current.as_ref())
                        .map(RemoveResult::to_json)
                        .collect();
                    println!("{}", serde_json::to_string_pretty(&json_items)?);
                }

                // Fire-and-forget cleanup of stale `.git/wt/trash/` entries —
                // runs after primary output so it never delays the user-visible
                // progress/success messages.
                commands::process::sweep_stale_trash(&repo);

                if !plans.errors.is_empty() {
                    anyhow::bail!("");
                }

                Ok(())
            }
        })
}

/// Rayon thread count sized for mixed git+network I/O workloads.
///
/// `wt list` and the picker's preview pre-compute both run git subprocesses
/// (often blocked on pipe reads) alongside occasional network requests. 2x CPU
/// cores lets threads waiting on I/O overlap with compute work without excessive
/// context-switch overhead.
///
/// 3x CPU was benchmarked against `divergent_branches/warm` (branch-heavy) and
/// `worktree_scaling/warm/8` (worktree-heavy) on packed fixtures. 3x is at or
/// within noise of the optimum on both workloads; 2x trails by 0-5% (divergent:
/// 259ms vs 257ms, CIs overlap; worktree: 86.6ms vs 82.4ms, ~5% gap). 4x
/// regresses on branch-heavy workloads. We stay at 2x because the win is small
/// in absolute terms (≤ 5ms) and 2x has been validated in production across
/// hardware we haven't benchmarked.
pub(crate) fn rayon_thread_count() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get() * 2)
        .unwrap_or(8)
}

fn init_rayon_thread_pool() {
    // Override with RAYON_NUM_THREADS=N for benchmarking.
    let num_threads = if std::env::var_os("RAYON_NUM_THREADS").is_some() {
        0 // Let Rayon handle the env var (includes validation)
    } else {
        rayon_thread_count()
    };
    let _ = rayon::ThreadPoolBuilder::new()
        .num_threads(num_threads)
        .build_global();
}

fn parse_cli() -> Option<Cli> {
    if completion::maybe_handle_env_completion() {
        return None;
    }

    // Apply -C / --config before help handling so `wt -C other --help`
    // and `wt --config custom.toml step --help` resolve aliases against the
    // requested repo and user config (not the process cwd / default config).
    // The same early parse also tells us whether this is help for the top
    // level or `wt step`, so the splice path in `augment_help` has no
    // separate arg scanner.
    let (directory, config, alias_help_context) = parse_early_globals();
    apply_global_options(directory, config);

    // Handle --help with pager before clap processes it.
    // Exits the process on a help/version/doc request; otherwise returns.
    help::maybe_handle_help_with_pager(alias_help_context);

    // TODO: Enhance error messages to show possible values for missing enum arguments
    // Currently `wt config shell init` doesn't show available shells, but `wt config shell init invalid` does.
    // Clap doesn't support this natively yet - see https://github.com/clap-rs/clap/issues/3320
    // When available, use built-in setting. Until then, could use try_parse() to intercept
    // MissingRequiredArgument errors and print custom messages with ValueEnum::value_variants().
    let cmd = cli::build_command();
    let matches = cmd
        .try_get_matches_from(std::env::args_os())
        .unwrap_or_else(|e| {
            enhance_and_exit_error(e);
        });
    Some(Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()))
}

fn apply_global_options(directory: Option<std::path::PathBuf>, config: Option<std::path::PathBuf>) {
    // Initialize base path from -C flag if provided
    if let Some(path) = directory {
        set_base_path(path);
    }

    // Initialize config path from --config flag if provided
    if let Some(path) = config {
        set_config_path(path);
    }
}

/// Parse global options (`-C`, `--config`) and detect whether this invocation
/// renders help that should include the configured aliases — in a single pass
/// against the real `Cli` definition.
///
/// Uses `ignore_errors(true)` so unknown args, missing values, and `--help`
/// don't abort parsing — we just read what matched. This lets `wt -C other
/// --help` apply `-C` before the help path renders, so `augment_help`
/// resolves aliases against the requested repo instead of the process cwd.
///
/// Using `cli::build_command()` rather than a hand-rolled mini-command keeps
/// the global-flag definitions in one place (the derive on `Cli`), so renaming
/// `-C` or adding a value-taking global doesn't silently desync this path.
fn parse_early_globals() -> (
    Option<std::path::PathBuf>,
    Option<std::path::PathBuf>,
    Option<commands::HelpContext>,
) {
    let cmd = cli::build_command()
        .ignore_errors(true)
        .disable_help_flag(true);
    let Ok(matches) = cmd.try_get_matches_from(std::env::args_os()) else {
        return (None, None, None);
    };
    let directory = matches.get_one::<std::path::PathBuf>("directory").cloned();
    let config = matches.get_one::<std::path::PathBuf>("config").cloned();
    // Top-level help: `wt --help` (or `-h`, or bare `wt` via `arg_required_else_help`)
    // lands here with no subcommand matched. Step help: `wt step --help` (or
    // `-h`, or bare `wt step`) matches `step` with nothing past it. Other
    // subcommands' help renders plain clap output without the aliases splice.
    let alias_help_context = match matches.subcommand() {
        None => Some(commands::HelpContext::TopLevel),
        Some(("step", sub)) if sub.subcommand_name().is_none() => Some(commands::HelpContext::Step),
        _ => None,
    };
    (directory, config, alias_help_context)
}

fn init_command_log(command_line: &str) {
    // Initialize command log for always-on logging of hooks and LLM commands.
    // Directory and file are created lazily on first log_command() call.
    if let Ok(repo) = worktrunk::git::Repository::current() {
        worktrunk::command_log::init(&repo.wt_logs_dir(), command_line);
    }
}

fn thread_label() -> char {
    let thread_id = format!("{:?}", std::thread::current().id());
    thread_id
        .strip_prefix("ThreadId(")
        .and_then(|s| s.strip_suffix(")"))
        .and_then(|s| s.parse::<usize>().ok())
        .map(|n| {
            if n == 0 {
                '0'
            } else if n <= 26 {
                char::from(b'a' + (n - 1) as u8)
            } else if n <= 52 {
                char::from(b'A' + (n - 27) as u8)
            } else {
                '?'
            }
        })
        .unwrap_or('?')
}

fn init_logging(verbose_level: u8) {
    // Configure logging based on --verbose flag or RUST_LOG env var.
    // Level map: -v → Info, -vv+ → Debug (stderr, with subprocess output
    // capped). At -vv, `.git/wt/logs/trace.log` mirrors stderr and
    // `.git/wt/logs/output.log` receives the uncapped subprocess bodies
    // routed via `shell_exec::SUBPROCESS_FULL_TARGET`.
    //
    // env_logger registers the logger via `.init()` at the bottom of this
    // function. `log_files::init()` runs after that so the
    // `Repository::current()` it triggers (cold cache: 4ms `git rev-parse
    // --git-common-dir`) is visible in `[wt-trace]` output.
    output::set_verbosity(verbose_level);

    let mut builder = match verbose_level {
        0 => env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("off")),
        1 => {
            let mut b = env_logger::Builder::new();
            b.filter_level(log::LevelFilter::Info);
            b
        }
        _ => {
            let mut b = env_logger::Builder::new();
            b.filter_level(log::LevelFilter::Debug);
            b
        }
    };

    builder
        .format(|buf, record| {
            let route = log_files::route(record.target());
            if matches!(route, log_files::Route::Drop) {
                return Ok(());
            }

            let thread_num = thread_label();
            let msg = record.args().to_string();
            let file_line = format!("[{thread_num}] {msg}");

            if let log_files::Route::File(sink) = route {
                sink.write_line(&file_line);
                return Ok(());
            }
            // Route::Stderr: mirror to trace.log (no-op when inactive), then
            // write the ANSI-formatted version to stderr below.
            log_files::TRACE.write_line(&file_line);

            // Commands start with $, make only the command bold (not $ or [worktree])
            if let Some(rest) = msg.strip_prefix("$ ") {
                // Split: "git command [worktree]" -> ("git command", " [worktree]")
                if let Some(bracket_pos) = rest.find(" [") {
                    let command = &rest[..bracket_pos];
                    let worktree = &rest[bracket_pos..];
                    writeln!(
                        buf,
                        "{}",
                        cformat!("<dim>[{thread_num}]</> $ <bold>{command}</>{worktree}")
                    )
                } else {
                    writeln!(
                        buf,
                        "{}",
                        cformat!("<dim>[{thread_num}]</> $ <bold>{rest}</>")
                    )
                }
            } else if msg.starts_with("  ! ") {
                // Error output - show in red
                writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> <red>{msg}</>"))
            } else {
                // Regular output with thread ID
                writeln!(buf, "{}", cformat!("<dim>[{thread_num}]</> {msg}"))
            }
        })
        .init();

    // Open per-file log sinks AFTER env_logger is registered so the
    // `Repository::current()` rev-parse fired by `try_create` is captured
    // in the trace.
    if verbose_level >= 2 {
        log_files::init();
    }
}

fn handle_merge_command(args: MergeArgs, yes: bool) -> anyhow::Result<()> {
    if args.no_verify {
        eprintln!(
            "{}",
            warning_message("--no-verify is deprecated; use --no-hooks instead")
        );
    }
    handle_merge(MergeOptions {
        target: args.target.as_deref(),
        flags: MergeFlagOverrides::from_cli(&args),
        yes,
        stage: args.stage,
        format: args.format,
    })
}

/// True when the parsed command should silence prewarm-time deprecation
/// warnings. Two reasons qualify:
///
/// - **TUI / stderr-sensitive output** (`select`, `switch` picker mode,
///   `list statusline`) — warnings on stderr would land above the picker
///   or shell prompt and visually break it.
/// - **`config update`** — the handler renders the deprecations and a diff
///   itself, so the prewarm-time warning + `wt config update` hint is
///   redundant noise above its own UI.
///
/// Read from `Cli::command` before `Repository::prewarm` so the suppress
/// latch beats `prewarm_user_config`'s warning-emission path. The handler
/// for each of these commands also calls `suppress_warnings()` locally;
/// both calls hit the same `OnceLock` so the second is a no-op.
fn command_suppresses_warnings(command: Option<&Commands>) -> bool {
    match command {
        Some(Commands::Select { .. }) => true,
        Some(Commands::Switch(args)) => args.branch.is_none(),
        Some(Commands::List(args)) => {
            matches!(args.subcommand, Some(ListSubcommand::Statusline { .. }))
        }
        Some(Commands::Config {
            action: ConfigCommand::Update { .. },
        }) => true,
        _ => false,
    }
}

fn dispatch_command(
    command: Commands,
    working_dir: Option<std::path::PathBuf>,
    yes: bool,
) -> anyhow::Result<()> {
    match command {
        Commands::Config { action } => handle_config_command(action, yes),
        Commands::Step { action } => handle_step_command(action, yes),
        Commands::Hook { action } => handle_hook_command(action, yes),
        Commands::Select { branches, remotes } => handle_select_command(branches, remotes),
        Commands::List(args) => handle_list_command(args),
        Commands::Switch(args) => handle_switch_command(args, yes),
        Commands::Remove(args) => handle_remove_command(args, yes),
        Commands::Merge(args) => handle_merge_command(args, yes),
        // `working_dir` is the top-level `-C <path>` flag, applied as the
        // child's current directory so global `-C` works for custom
        // subcommands the same way it does for built-ins.
        Commands::Custom(args) => handle_custom_command(args, working_dir, yes),
    }
}

fn print_command_error(error: &anyhow::Error) {
    let formatted = format_command_error(error);
    if !formatted.is_empty() {
        // Route through `worktrunk::styling::eprintln` (anstream) so ANSI
        // codes are stripped when stderr isn't a TTY. Building a String
        // and using `std::eprint!` would bypass the strip stream and leak
        // raw escape sequences into snapshots.
        eprintln!("{}", formatted.trim_end_matches('\n'));
    }
}

/// Render an error for terminal display. Returns the full formatted output
/// (including a trailing newline when non-empty) so tests can assert on it
/// without capturing stderr.
fn format_command_error(error: &anyhow::Error) -> String {
    use std::fmt::Write;
    let mut out = String::new();

    // Locate the first error in the chain that implements `Diagnostic`.
    // Most typed errors render directly even when wrapped in
    // `.context(...)`: their styled block is self-contained and the
    // wrapping context (if any) was added to enrich logs, not the
    // user-facing message. The exception is `CommandError`: its captured
    // stderr/stdout pairs naturally with the wrapping context to form a
    // header + body block (e.g., header `"running prune"`, body git's
    // actual error).
    let diagnostic_hit = error.chain().enumerate().find_map(|(i, cause)| {
        worktrunk::git::try_render_diagnostic(cause)
            .map(|r| (i, r, cause.is::<worktrunk::git::CommandError>()))
    });

    let wrapped_command_error = matches!(diagnostic_hit, Some((pos, _, true)) if pos > 0);

    match diagnostic_hit {
        Some((_, rendered, _)) if !wrapped_command_error => {
            // The type's `render()` produces a complete styled block —
            // emit it directly. Empty rendering (AlreadyDisplayed,
            // CommandNotApproved) is a signal to skip output entirely.
            if !rendered.is_empty() {
                let _ = writeln!(out, "{rendered}");
            }
        }
        Some(_) => {
            // Wrapped `CommandError`: outermost context becomes the
            // header, intermediate contexts plus the captured
            // stderr/stdout join the gutter so wrapped failures like
            // `.context("listing worktrees").context("running prune")`
            // keep their diagnostic context while still surfacing git's
            // actual stderr.
            let _ = writeln!(out, "{}", error_message(error.to_string()));
            let mut gutter_parts: Vec<String> = Vec::new();
            let mut command_handled = false;
            for cause in error.chain().skip(1) {
                if !command_handled
                    && let Some(cmd_err) = cause.downcast_ref::<worktrunk::git::CommandError>()
                {
                    let body = cmd_err.combined_output();
                    gutter_parts.push(if body.is_empty() {
                        cmd_err.to_string()
                    } else {
                        body
                    });
                    command_handled = true;
                } else {
                    gutter_parts.push(cause.to_string());
                }
            }
            if !gutter_parts.is_empty() {
                let _ = writeln!(
                    out,
                    "{}",
                    format_with_gutter(&gutter_parts.join("\n"), None)
                );
            }
        }
        None => {
            // Anyhow error formatting:
            // - With context: show context as header, root cause in gutter
            // - Simple error: inline with emoji
            // - Empty error: skip (errors already printed elsewhere)
            let msg = error.to_string();
            if !msg.is_empty() {
                let chain: Vec<String> = error.chain().skip(1).map(|e| e.to_string()).collect();
                if !chain.is_empty() {
                    let _ = writeln!(out, "{}", error_message(&msg));
                    let chain_text = chain.join("\n");
                    let _ = writeln!(out, "{}", format_with_gutter(&chain_text, None));
                } else if msg.contains('\n') || msg.contains('\r') {
                    // A multi-line error reached this branch without being wrapped
                    // in a typed `CommandError` and without `.context(...)` on top.
                    // Buffered command failures should always surface as
                    // `CommandError`; if you hit this assert, route the failing
                    // path through `Repository::run_command` /
                    // `WorkingTree::run_command` (or construct a
                    // `worktrunk::git::CommandError` directly) instead of
                    // `bail!("{stderr}")`.
                    debug_assert!(
                        false,
                        "Multiline error without CommandError or context: {msg}"
                    );
                    log::warn!("Multiline error without CommandError or context: {msg}");
                    let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");
                    let _ = writeln!(out, "{}", error_message("Command failed"));
                    let _ = writeln!(out, "{}", format_with_gutter(&normalized, None));
                } else {
                    let _ = writeln!(out, "{}", error_message(&msg));
                }
            }
        }
    }
    out
}

fn print_cwd_removed_hint_if_needed() {
    // If the CWD has been deleted, hint the user about recovery options.
    // Check both: (1) explicit flag set by merge/remove when it knows the CWD
    // worktree was removed (reliable on all platforms), and (2) OS-level detection
    // for cases not covered by the flag (e.g., external worktree removal).
    let cwd_gone = output::was_cwd_removed() || std::env::current_dir().is_err();
    if cwd_gone {
        if let Some(hint) = cwd_removed_hint() {
            eprintln!("{}", hint_message(hint));
        } else {
            eprintln!("{}", info_message("Current directory was removed"));
        }
    }
}

fn finish_command(verbose_level: u8, command_line: &str, error: Option<&anyhow::Error>) {
    let error_text = error.map(|err| err.to_string());
    diagnostic::write_if_verbose(verbose_level, command_line, error_text.as_deref());
    let _ = output::terminate_output();
}

fn handle_command_failure(error: anyhow::Error, verbose_level: u8, command_line: &str) -> ! {
    print_command_error(&error);
    print_cwd_removed_hint_if_needed();

    // Preserve exit code from child processes (especially for signals like SIGINT)
    let code = error.exit_code().unwrap_or(1);
    finish_command(verbose_level, command_line, Some(&error));
    process::exit(code);
}

fn print_help_to_stderr() {
    // No subcommand provided - print help to stderr (stdout is eval'd by shell wrapper)
    let mut cmd = cli::build_command();
    let help = cmd.render_help().ansi().to_string();
    eprintln!("{help}");
}

fn main() {
    // Capture the startup working directory before anything else. This is
    // used by shell_exec to resolve relative `GIT_*` path variables inherited
    // from a parent `git` (e.g. when invoked via `git wt ...` with
    // `alias.wt = "!wt"`) against a stable reference, rather than against
    // each child command's `current_dir`. See issue #1914.
    //
    // `[wt-trace]` spans before the logger is registered would silently
    // no-op, so the prelude up to `init_logging` — `init_startup_cwd`,
    // `init_rayon_thread_pool`, `force_color_output`, `parse_cli` — isn't
    // attributed. If startup itself becomes the suspect, capture it as
    // wall-clock minus the sum of post-init spans.
    worktrunk::shell_exec::init_startup_cwd();

    init_rayon_thread_pool();

    // Tell crossterm to always emit ANSI sequences
    crossterm::style::force_color_output(true);

    let Some(cli) = parse_cli() else {
        return;
    };

    let Cli {
        directory,
        config,
        verbose,
        yes,
        command,
    } = cli;
    // Globals were already applied in `parse_cli` before help rendering;
    // OnceLock makes this call a no-op, but keeping it avoids touching the
    // existing destructure pattern.
    apply_global_options(directory.clone(), config);

    // Latch warning suppression for commands whose UX is broken by stderr
    // noise — TUI pickers (`switch` without a branch, `select`) and
    // statusline output rendered above each shell prompt. Must fire before
    // `Repository::prewarm` since `prewarm_user_config` loads `UserConfig`
    // eagerly and would otherwise emit deprecation warnings before the
    // command handler's own `suppress_warnings()` call could latch.
    // Handlers keep their `suppress_warnings()` calls — `OnceLock` is
    // idempotent and the local call documents the intent at the use site.
    if command_suppresses_warnings(command.as_ref()) {
        worktrunk::config::suppress_warnings();
    }

    // `init_logging` registers the logger. Run it before `init_command_log`
    // so the latter's `Repository::current()` → `git rev-parse
    // --git-common-dir` subprocess is visible in `[wt-trace]` output. With
    // the previous order the rev-parse fired before any logger was
    // registered, leaving a 4ms hole in the trace where the subprocess
    // actually ran. Same reason `init_logging` itself reorders to
    // register env_logger before opening per-file log sinks.
    {
        let _span = worktrunk::trace::Span::new("init_logging");
        init_logging(verbose);
    }

    // Fold the two cold-path rev-parses (`--git-common-dir` from
    // `init_command_log`, the `prewarm_info` batch from `try_alias` →
    // `project_config_path`) into one fork. Best-effort — failure leaves both
    // on-demand callers unchanged.
    Repository::prewarm();

    let command_line = std::env::args().collect::<Vec<_>>().join(" ");
    {
        let _span = worktrunk::trace::Span::new("init_command_log");
        init_command_log(&command_line);
    }

    let Some(command) = command else {
        print_help_to_stderr();
        return;
    };

    let result = dispatch_command(command, directory, yes);

    match result {
        Ok(()) => finish_command(verbose, &command_line, None),
        Err(error) => handle_command_failure(error, verbose, &command_line),
    }
}

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

    fn permission_denied_command_error() -> CommandError {
        // Faithful reproduction of the failure shape from issue #2564:
        // git emits a multi-line stderr (warning + fatal) and exits 128.
        CommandError {
            program: "git".into(),
            args: vec!["worktree".into(), "list".into()],
            stderr: "warning: unable to access '.git/config': Permission denied\nfatal: unknown error occurred while reading the configuration files".into(),
            stdout: String::new(),
            exit_code: Some(128),
        }
    }

    /// Regression for #2564: a buffered `git` failure surfaces as a typed
    /// `CommandError`. The single-line summary becomes the header and the
    /// multi-line stderr lands in the gutter — no `debug_assert!` panic.
    #[test]
    fn renders_command_error_without_context() {
        let err: anyhow::Error = permission_denied_command_error().into();
        let out = format_command_error(&err);
        assert!(out.contains("git worktree list failed (exit 128)"));
        assert!(out.contains("Permission denied"));
        assert!(out.contains("unknown error occurred while reading"));
    }

    /// One `.context(...)` layer above the `CommandError` — the context is
    /// the header, captured stderr is the body.
    #[test]
    fn renders_command_error_with_one_context() {
        let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())
            .context("listing worktrees")
            .unwrap_err();
        let out = format_command_error(&err);
        assert!(out.contains("listing worktrees"));
        assert!(out.contains("Permission denied"));
    }

    /// Codex P3: when a `CommandError` is wrapped by *multiple*
    /// `.context(...)` layers, intermediate context entries must appear in
    /// the gutter — they were dropped by an earlier rev that only used the
    /// top-level message.
    #[test]
    fn renders_command_error_preserves_intermediate_context() {
        let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())
            .context("listing worktrees")
            .context("running prune")
            .unwrap_err();
        let out = format_command_error(&err);
        // Outer context is the header
        assert!(
            out.contains("running prune"),
            "missing outer context: {out}"
        );
        // Intermediate context survives — the bug Codex flagged
        assert!(
            out.contains("listing worktrees"),
            "intermediate context dropped: {out}",
        );
        // Stderr body still rendered
        assert!(out.contains("Permission denied"), "stderr lost: {out}",);
        // The `CommandError` summary itself shouldn't appear when its
        // body replaced its slot — we want git's actual error, not our
        // wrapper.
        assert!(
            !out.contains("git worktree list failed"),
            "summary surfaced alongside stderr: {out}",
        );
    }

    /// A `CommandError` with empty stderr/stdout (e.g., a child killed by
    /// a signal before producing output) wrapped in context: the gutter
    /// should fall back to the `CommandError` summary so the user sees
    /// something more than just the outer context. Exercises the
    /// empty-body branch of the renderer's gutter assembly.
    #[test]
    fn renders_command_error_with_empty_body() {
        let empty = CommandError {
            program: "git".into(),
            args: vec!["fetch".into()],
            stderr: String::new(),
            stdout: String::new(),
            exit_code: None,
        };
        let err: anyhow::Error = Err::<(), _>(empty).context("syncing remotes").unwrap_err();
        let out = format_command_error(&err);
        assert!(out.contains("syncing remotes"));
        // No body to render, so the summary is what we surface.
        assert!(out.contains("git fetch failed"));
    }

    /// Codex P2: typed `GitError` wrappers (e.g., `WorktreeRemovalFailed`,
    /// `PushFailed`) embed a stringified sub-error into their `error`
    /// field. With `display_message`, that field carries git's stderr
    /// rather than our `CommandError` summary.
    #[test]
    fn display_message_prefers_command_error_stderr_over_summary() {
        let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())
            .context("creating worktree")
            .unwrap_err();
        let detail = err.display_message();
        assert!(detail.contains("Permission denied"));
        assert!(detail.contains("unknown error occurred while reading"));
        // Without `CommandError::find_in` this would be "creating worktree".
        assert!(!detail.starts_with("creating worktree"));
    }

    /// When a `CommandError` has empty stderr/stdout (signal-killed before
    /// output, or git silent on a non-zero exit), `display_message` falls
    /// back to the command summary so the embedding error doesn't end up
    /// with a blank detail.
    #[test]
    fn display_message_falls_back_to_summary_when_capture_empty() {
        let empty = CommandError {
            program: "git".into(),
            args: vec!["fetch".into()],
            stderr: String::new(),
            stdout: String::new(),
            exit_code: None,
        };
        let err: anyhow::Error = empty.into();
        assert_eq!(err.display_message(), "git fetch failed");
    }
}