worktrunk 0.42.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
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
//! Worktrunk error types and formatting
//!
//! This module provides typed error handling:
//!
//! - **`GitError`** - A typed enum for domain errors that can be pattern-matched
//!   and tested. Use `.into()` to convert to `anyhow::Error` while preserving the
//!   type for pattern matching. Display produces styled output for users.
//!
//! - **`WorktrunkError`** - A minimal enum for semantic errors that need
//!   special handling (exit codes, silent errors).

use std::borrow::Cow;
use std::path::PathBuf;

use color_print::{cformat, cwrite};
use shell_escape::escape;

use super::HookType;
use crate::path::format_path_for_display;
use crate::styling::{
    ERROR_SYMBOL, HINT_SYMBOL, error_message, format_bash_with_gutter, format_with_gutter,
    hint_message, info_message, suggest_command,
};

/// Platform-specific reference type (PR vs MR).
///
/// Used to unify error handling for GitHub PRs and GitLab MRs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefType {
    /// GitHub Pull Request
    Pr,
    /// GitLab Merge Request
    Mr,
}

impl RefType {
    /// Returns the number prefix symbol for this reference type.
    /// - PR: "#" (e.g., "PR #42")
    /// - MR: "!" (e.g., "MR !42")
    pub fn symbol(self) -> &'static str {
        match self {
            Self::Pr => "#",
            Self::Mr => "!",
        }
    }

    /// Returns the short name for this reference type.
    pub fn name(self) -> &'static str {
        match self {
            Self::Pr => "PR",
            Self::Mr => "MR",
        }
    }

    /// Returns the plural form of the short name.
    pub fn name_plural(self) -> &'static str {
        match self {
            Self::Pr => "PRs",
            Self::Mr => "MRs",
        }
    }

    /// Returns the CLI syntax prefix (e.g., "pr:" or "mr:").
    pub fn syntax(self) -> &'static str {
        match self {
            Self::Pr => "pr:",
            Self::Mr => "mr:",
        }
    }

    /// Returns a display string like "PR #42" or "MR !42".
    pub fn display(self, number: u32) -> String {
        format!("{} {}{}", self.name(), self.symbol(), number)
    }
}

/// Common display fields for PR/MR context.
///
/// Implemented by both `PrInfo` and `MrInfo` to enable unified formatting.
pub trait RefContext {
    fn ref_type(&self) -> RefType;
    fn number(&self) -> u32;
    fn title(&self) -> &str;
    fn author(&self) -> &str;
    fn state(&self) -> &str;
    fn draft(&self) -> bool;
    fn url(&self) -> &str;

    /// The source branch reference for display.
    ///
    /// For same-repo PRs/MRs: just the branch name (e.g., `feature-auth`)
    /// For fork PRs/MRs: `owner:branch` format (e.g., `contributor:feature-fix`)
    fn source_ref(&self) -> String;
}

/// Information about a failed command, for display in error messages.
///
/// Separates the command string from exit information so Display impls
/// can style each part differently (bold command, gray exit code).
#[derive(Debug, Clone)]
pub struct FailedCommand {
    /// The full command string, e.g., "git worktree add /path -b fix main"
    pub command: String,
    /// Exit information, e.g., "exit code 255" or "killed by signal"
    pub exit_info: String,
}

/// Extra CLI context for enriching `wt switch` suggestions in error hints.
///
/// When a switch error is raised deep in the planning layer, the error only knows
/// the branch name. The command handler wraps the error with this context so the
/// Display impl can produce a fully copy-pasteable suggestion including flags like
/// `--execute` and trailing args.
#[derive(Debug, Clone)]
pub struct SwitchSuggestionCtx {
    pub extra_flags: Vec<String>,
    pub trailing_args: Vec<String>,
}

impl SwitchSuggestionCtx {
    /// Append extra flags and trailing args to a suggested command string.
    ///
    /// Clap's `#[arg(last = true)]` on `execute_args` means `--` always routes
    /// to execute_args, so a dash-prefixed branch can't coexist with `--execute`
    /// via the CLI. The suggested command therefore never has a pre-existing `--`
    /// separator when this context is applied.
    fn apply(&self, cmd: String) -> String {
        let mut result = cmd;
        // Flags are pre-escaped at construction (handle_switch.rs uses shell_escape)
        for flag in &self.extra_flags {
            result.push(' ');
            result.push_str(flag);
        }
        if !self.trailing_args.is_empty() {
            result.push_str(" --");
            for arg in &self.trailing_args {
                result.push(' ');
                result.push_str(&escape(Cow::Borrowed(arg.as_str())));
            }
        }
        result
    }
}

/// Domain errors for git and worktree operations.
///
/// This enum provides structured error data that can be pattern-matched and tested.
/// Each variant stores the data needed to construct a user-facing error message.
/// Display produces styled output with emoji and colors.
///
/// # Usage
///
/// ```ignore
/// // Return a typed error (Display produces styled output)
/// return Err(GitError::DetachedHead { action: Some("merge".into()) }.into());
///
/// // Pattern match on errors
/// if let Some(GitError::BranchAlreadyExists { branch }) = err.downcast_ref() {
///     println!("Branch {} exists", branch);
/// }
/// ```
#[derive(Debug, Clone)]
pub enum GitError {
    // Git state errors
    DetachedHead {
        action: Option<String>,
    },
    UncommittedChanges {
        action: Option<String>,
        /// Branch name (for multi-worktree operations)
        branch: Option<String>,
        /// When true, hint mentions --force as an alternative to stashing
        force_hint: bool,
    },
    BranchAlreadyExists {
        branch: String,
    },
    BranchNotFound {
        branch: String,
        /// Show hint about creating the branch. Set to false for remove operations
        /// where suggesting creation doesn't make sense.
        show_create_hint: bool,
        /// Pre-formatted label for the last fetch time (e.g., "3h ago", "never").
        /// When present, the list-branches hint includes the fetch age as a parenthetical.
        last_fetch_ago: Option<String>,
    },
    /// Reference (branch, tag, commit) not found - used when any commit-ish is accepted
    ReferenceNotFound {
        reference: String,
    },
    /// Persisted `worktrunk.default-branch` points at a branch that no longer
    /// resolves locally. Surfaced when a command would use the default branch
    /// (no explicit `--target`) and the cached value is stale, so the user
    /// gets a cache-reset hint instead of a generic "branch not found".
    StaleDefaultBranch {
        branch: String,
    },

    // Worktree errors
    NotInWorktree {
        /// The action that requires being in a worktree
        action: Option<String>,
    },
    WorktreeMissing {
        branch: String,
    },
    RemoteOnlyBranch {
        branch: String,
        remote: String,
    },
    WorktreePathOccupied {
        branch: String,
        path: PathBuf,
        occupant: Option<String>,
    },
    WorktreePathExists {
        branch: String,
        path: PathBuf,
        create: bool,
    },
    WorktreeCreationFailed {
        branch: String,
        base_branch: Option<String>,
        error: String,
        /// The git command that failed, shown separately from git output
        command: Option<FailedCommand>,
    },
    WorktreeRemovalFailed {
        branch: String,
        path: PathBuf,
        error: String,
        /// Top-level entries remaining in the directory (for "Directory not empty" diagnostics)
        remaining_entries: Option<Vec<String>>,
    },
    CannotRemoveMainWorktree,
    CannotRemoveDefaultBranch {
        branch: String,
    },
    WorktreeLocked {
        branch: String,
        path: PathBuf,
        reason: Option<String>,
    },

    // Merge/push errors
    ConflictingChanges {
        target_branch: String,
        files: Vec<String>,
        worktree_path: PathBuf,
    },
    NotFastForward {
        target_branch: String,
        commits_formatted: String,
        in_merge_context: bool,
    },
    RebaseConflict {
        target_branch: String,
        git_output: String,
    },
    NotRebased {
        target_branch: String,
    },
    PushFailed {
        target_branch: String,
        error: String,
    },

    // Validation/other errors
    NotInteractive,
    HookCommandNotFound {
        name: String,
        available: Vec<String>,
    },
    ParseError {
        message: String,
    },
    WorktreeIncludeParseError {
        error: String,
    },
    LlmCommandFailed {
        command: String,
        error: String,
        /// Full command to reproduce the failure, e.g., "wt step commit --show-prompt | llm"
        reproduction_command: Option<String>,
    },
    ProjectConfigNotFound {
        config_path: PathBuf,
    },
    WorktreeNotFound {
        branch: String,
    },
    /// --create flag used with pr:/mr: syntax (conflict - branch already exists)
    RefCreateConflict {
        ref_type: RefType,
        number: u32,
        branch: String,
    },
    /// --base flag used with pr:/mr: syntax (conflict - base is predetermined)
    RefBaseConflict {
        ref_type: RefType,
        number: u32,
    },
    /// Branch exists but is tracking a different PR/MR
    BranchTracksDifferentRef {
        branch: String,
        ref_type: RefType,
        number: u32,
    },
    /// No remote found for the repository where the PR lives
    NoRemoteForRepo {
        owner: String,
        repo: String,
        /// Suggested URL to add as a remote (derived from primary remote's protocol/host)
        suggested_url: String,
    },
    /// CLI API command failed with unrecognized error (gh or glab)
    CliApiError {
        ref_type: RefType,
        /// Short description of what failed
        message: String,
        /// Full stderr output for debugging
        stderr: String,
    },
    Other {
        message: String,
    },

    /// Wrapper that enriches an inner error's switch suggestions with CLI context.
    ///
    /// The inner error renders normally, but any `wt switch` suggestion includes
    /// the extra flags and trailing args from the context.
    WithSwitchSuggestion {
        source: Box<GitError>,
        ctx: SwitchSuggestionCtx,
    },
}

impl std::error::Error for GitError {}

impl GitError {
    /// Format with optional switch suggestion context.
    ///
    /// Most variants ignore `ctx`. The three that render `wt switch` suggestions
    /// (`BranchAlreadyExists`, `BranchNotFound`, `WorktreePathExists`) use it
    /// to append extra flags and trailing args for a copy-pasteable command.
    fn fmt_with_ctx(
        &self,
        f: &mut std::fmt::Formatter<'_>,
        ctx: Option<&SwitchSuggestionCtx>,
    ) -> std::fmt::Result {
        match self {
            GitError::WithSwitchSuggestion { source, ctx } => source.fmt_with_ctx(f, Some(ctx)),

            GitError::DetachedHead { action } => {
                let message = match action {
                    Some(action) => cformat!("Cannot {action}: not on a branch (detached HEAD)"),
                    None => "Not on a branch (detached HEAD)".to_string(),
                };
                write!(
                    f,
                    "{}\n{}",
                    error_message(&message),
                    hint_message(cformat!(
                        "To switch to a branch, run <underline>git switch <<branch>></>"
                    ))
                )
            }

            GitError::UncommittedChanges {
                action,
                branch,
                force_hint,
            } => {
                let message = match (action, branch) {
                    (Some(action), Some(b)) => {
                        cformat!("Cannot {action}: <bold>{b}</> has uncommitted changes")
                    }
                    (Some(action), None) => {
                        cformat!("Cannot {action}: working tree has uncommitted changes")
                    }
                    (None, Some(b)) => {
                        cformat!("<bold>{b}</> has uncommitted changes")
                    }
                    (None, None) => cformat!("Working tree has uncommitted changes"),
                };
                let hint = if *force_hint {
                    // Construct full command: "wt remove [branch] --force"
                    let args: Vec<&str> = branch.as_deref().into_iter().collect();
                    let cmd = suggest_command("remove", &args, &["--force"]);
                    cformat!(
                        "Commit or stash changes first, or to lose uncommitted changes, run <underline>{cmd}</>"
                    )
                } else {
                    "Commit or stash changes first".to_string()
                };
                write!(f, "{}\n{}", error_message(&message), hint_message(hint))
            }

            GitError::BranchAlreadyExists { branch } => {
                let mut switch_cmd = suggest_command("switch", &[branch], &[]);
                if let Some(ctx) = ctx {
                    switch_cmd = ctx.apply(switch_cmd);
                }
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("Branch <bold>{branch}</> already exists")),
                    hint_message(cformat!(
                        "To switch to the existing branch, run without <underline>--create</>: <underline>{switch_cmd}</>"
                    ))
                )
            }

            GitError::BranchNotFound {
                branch,
                show_create_hint,
                last_fetch_ago,
            } => {
                let list_cmd = suggest_command("list", &[], &["--branches", "--remotes"]);
                let hint = if *show_create_hint {
                    let mut create_cmd = suggest_command("switch", &[branch], &["--create"]);
                    if let Some(ctx) = ctx {
                        create_cmd = ctx.apply(create_cmd);
                    }
                    let fetch_note = last_fetch_ago.as_ref().map(|ago| cformat!(" ({ago})"));
                    cformat!(
                        "To create a new branch, run <underline>{create_cmd}</>; to list branches, run <underline>{list_cmd}</>{note}",
                        note = fetch_note.as_deref().unwrap_or("")
                    )
                } else {
                    cformat!("To list branches, run <underline>{list_cmd}</>")
                };
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("No branch named <bold>{branch}</>")),
                    hint_message(hint)
                )
            }

            GitError::ReferenceNotFound { reference } => {
                write!(
                    f,
                    "{}",
                    error_message(cformat!(
                        "No branch, tag, or commit named <bold>{reference}</>"
                    ))
                )
            }

            GitError::StaleDefaultBranch { branch } => {
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Default branch <bold>{branch}</> does not exist locally"
                    )),
                    hint_message(cformat!(
                        "Reset the cached value with <underline>wt config state default-branch clear</>, or set it explicitly with <underline>wt config state default-branch set BRANCH</>"
                    ))
                )
            }

            GitError::NotInWorktree { action } => {
                let message = match action {
                    Some(action) => cformat!("Cannot {action}: not in a worktree"),
                    None => "Not in a worktree".to_string(),
                };
                write!(
                    f,
                    "{}\n{}",
                    error_message(&message),
                    hint_message(cformat!(
                        "Run from inside a worktree, or specify a branch name"
                    ))
                )
            }

            GitError::WorktreeMissing { branch } => {
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("Worktree directory missing for <bold>{branch}</>")),
                    hint_message(cformat!(
                        "To clean up, run <underline>git worktree prune</>"
                    ))
                )
            }

            GitError::RemoteOnlyBranch { branch, remote } => {
                let cmd = suggest_command("switch", &[branch], &[]);
                cwrite!(
                    f,
                    "{ERROR_SYMBOL} <red>Branch <bold>{branch}</> exists only on remote ({remote}/{branch})</>\n{HINT_SYMBOL} <dim>To create a local worktree, run <underline>{cmd}</></>"
                )
            }

            GitError::WorktreePathOccupied {
                branch,
                path,
                occupant,
            } => {
                let path_display = format_path_for_display(path);
                let reason = if let Some(occupant_branch) = occupant {
                    cformat!(
                        "there's a worktree at the expected path <bold>{path_display}</> on branch <bold>{occupant_branch}</>"
                    )
                } else {
                    cformat!(
                        "there's a detached worktree at the expected path <bold>{path_display}</>"
                    )
                };
                let escaped_path = escape(path.to_string_lossy());
                let escaped_branch = escape(Cow::Borrowed(branch.as_str()));
                let command = format!("cd {escaped_path} && git switch {escaped_branch}");
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("Cannot switch to <bold>{branch}</> — {reason}")),
                    hint_message(cformat!(
                        "To switch the worktree at <underline>{path_display}</> to <underline>{branch}</>, run <underline>{command}</>"
                    ))
                )
            }

            GitError::WorktreePathExists {
                branch,
                path,
                create,
            } => {
                let path_display = format_path_for_display(path);
                let flags: &[&str] = if *create {
                    &["--create", "--clobber"]
                } else {
                    &["--clobber"]
                };
                let mut switch_cmd = suggest_command("switch", &[branch], flags);
                if let Some(ctx) = ctx {
                    switch_cmd = ctx.apply(switch_cmd);
                }
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Directory already exists: <bold>{path_display}</>"
                    )),
                    hint_message(cformat!(
                        "To remove manually, run <underline>rm -rf {path_display}</>; to overwrite (with backup), run <underline>{switch_cmd}</>"
                    ))
                )
            }

            GitError::WorktreeCreationFailed {
                branch,
                base_branch,
                error,
                command,
            } => {
                let header = if let Some(base) = base_branch {
                    error_message(cformat!(
                        "Failed to create worktree for <bold>{branch}</> from base <bold>{base}</>"
                    ))
                } else {
                    error_message(cformat!("Failed to create worktree for <bold>{branch}</>"))
                };
                write!(f, "{}", format_error_block(header, error))?;
                if let Some(cmd) = command {
                    write!(
                        f,
                        "\n{}\n{}",
                        hint_message(cformat!("Failed command, <underline>{}</>:", cmd.exit_info)),
                        format_bash_with_gutter(&cmd.command)
                    )?;
                }
                Ok(())
            }

            GitError::WorktreeRemovalFailed {
                branch,
                path,
                error,
                remaining_entries,
            } => {
                let path_display = format_path_for_display(path);
                let header = error_message(cformat!(
                    "Failed to remove worktree for <bold>{branch}</> @ <bold>{path_display}</>"
                ));
                write!(f, "{}", format_error_block(header, error))?;
                if let Some(entries) = remaining_entries {
                    const MAX_SHOWN: usize = 10;
                    let listing = if entries.len() > MAX_SHOWN {
                        let shown = entries[..MAX_SHOWN].join(", ");
                        let remaining = entries.len() - MAX_SHOWN;
                        format!("{shown}, and {remaining} more")
                    } else {
                        entries.join(", ")
                    };
                    write!(
                        f,
                        "\n{}",
                        hint_message(cformat!("Remaining in directory: <underline>{listing}</>"))
                    )?;
                }
                if error.contains("not empty") {
                    write!(
                        f,
                        "\n{}",
                        hint_message(cformat!(
                            "A background process may be writing files; try <underline>wt remove</> (without --foreground)"
                        ))
                    )?;
                }
                Ok(())
            }

            GitError::CannotRemoveMainWorktree => {
                write!(
                    f,
                    "{}",
                    error_message("The main worktree cannot be removed")
                )
            }

            GitError::CannotRemoveDefaultBranch { branch } => {
                let cmd = suggest_command("remove", &[branch], &["-D"]);
                write!(
                    f,
                    "{}",
                    error_message(cformat!(
                        "Cannot remove the default branch <bold>{branch}</>"
                    ))
                )?;
                write!(
                    f,
                    "\n{}",
                    hint_message(cformat!("To force-delete, run <underline>{cmd}</>"))
                )
            }

            GitError::WorktreeLocked {
                branch,
                path,
                reason,
            } => {
                let reason_text = match reason {
                    Some(r) if !r.is_empty() => format!(" ({r})"),
                    _ => String::new(),
                };
                let path_display = format_path_for_display(path);
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Cannot remove <bold>{branch}</>, worktree is locked{reason_text}"
                    )),
                    hint_message(cformat!(
                        "To unlock, run <underline>git worktree unlock {path_display}</>"
                    ))
                )
            }

            GitError::ConflictingChanges {
                target_branch,
                files,
                worktree_path,
            } => {
                write!(
                    f,
                    "{}",
                    error_message(cformat!(
                        "Can't push to local <bold>{target_branch}</> branch: conflicting uncommitted changes"
                    ))
                )?;
                if !files.is_empty() {
                    let joined_files = files.join("\n");
                    write!(f, "\n{}", format_with_gutter(&joined_files, None))?;
                }
                let path_display = format_path_for_display(worktree_path);
                write!(
                    f,
                    "\n{}",
                    hint_message(format!(
                        "Commit or stash these changes in {path_display} first"
                    ))
                )
            }

            GitError::NotFastForward {
                target_branch,
                commits_formatted,
                in_merge_context,
            } => {
                write!(
                    f,
                    "{}",
                    error_message(cformat!(
                        "Can't push to local <bold>{target_branch}</> branch: it has newer commits"
                    ))
                )?;
                if !commits_formatted.is_empty() {
                    write!(f, "\n{}", format_with_gutter(commits_formatted, None))?;
                }
                // Context-appropriate hint
                let merge_cmd = suggest_command("merge", &[target_branch], &[]);
                if *in_merge_context {
                    write!(
                        f,
                        "\n{}",
                        hint_message(cformat!(
                            "To incorporate these changes, run <underline>{merge_cmd}</> again"
                        ))
                    )
                } else {
                    let rebase_cmd = suggest_command("step", &["rebase", target_branch], &[]);
                    write!(
                        f,
                        "\n{}",
                        hint_message(cformat!(
                            "To rebase onto <underline>{target_branch}</>, run <underline>{rebase_cmd}</>"
                        ))
                    )
                }
            }

            GitError::RebaseConflict {
                target_branch,
                git_output,
            } => {
                write!(
                    f,
                    "{}",
                    error_message(cformat!("Rebase onto <bold>{target_branch}</> incomplete"))
                )?;
                if !git_output.is_empty() {
                    write!(f, "\n{}", format_with_gutter(git_output, None))
                } else {
                    write!(
                        f,
                        "\n{}\n{}",
                        hint_message(cformat!(
                            "To continue after resolving conflicts, run <underline>git rebase --continue</>"
                        )),
                        hint_message(cformat!("To abort, run <underline>git rebase --abort</>"))
                    )
                }
            }

            GitError::NotRebased { target_branch } => {
                let rebase_cmd = suggest_command("step", &["rebase", target_branch], &[]);
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("Branch not rebased onto <bold>{target_branch}</>")),
                    hint_message(cformat!(
                        "To rebase first, run <underline>{rebase_cmd}</>; or remove <underline>--no-rebase</>"
                    ))
                )
            }

            GitError::PushFailed {
                target_branch,
                error,
            } => {
                let header = error_message(cformat!(
                    "Can't push to local <bold>{target_branch}</> branch"
                ));
                write!(f, "{}", format_error_block(header, error))
            }

            GitError::NotInteractive => {
                let approvals_cmd = suggest_command("config", &["approvals", "add"], &[]);
                write!(
                    f,
                    "{}\n{}",
                    error_message("Cannot prompt for approval in non-interactive environment"),
                    hint_message(cformat!(
                        "To skip prompts in CI/CD, add <underline>--yes</>; to pre-approve commands, run <underline>{approvals_cmd}</>"
                    ))
                )
            }

            GitError::HookCommandNotFound { name, available } => {
                if available.is_empty() {
                    write!(
                        f,
                        "{}",
                        error_message(cformat!(
                            "No command named <bold>{name}</> (hook has no named commands)"
                        ))
                    )
                } else {
                    let available_str = available
                        .iter()
                        .map(|s| cformat!("<bold>{s}</>"))
                        .collect::<Vec<_>>()
                        .join(", ");
                    write!(
                        f,
                        "{}",
                        error_message(cformat!(
                            "No command named <bold>{name}</> (available: {available_str})"
                        ))
                    )
                }
            }

            GitError::LlmCommandFailed {
                command,
                error,
                reproduction_command,
            } => {
                let error_header = error_message("Commit generation command failed");
                let error_block = format_error_block(error_header, error);
                // Show full pipeline command if available, otherwise just the LLM command
                let display_command = reproduction_command.as_ref().unwrap_or(command);
                let command_gutter = format_with_gutter(display_command, None);
                write!(
                    f,
                    "{}\n{}\n{}",
                    error_block,
                    info_message("Ran command:"),
                    command_gutter
                )
            }

            GitError::ProjectConfigNotFound { config_path } => {
                let path_display = format_path_for_display(config_path);
                write!(
                    f,
                    "{}\n{}",
                    error_message("No project configuration found"),
                    hint_message(cformat!(
                        "Create a config file at: <underline>{path_display}</>"
                    ))
                )
            }

            GitError::ParseError { message } => {
                write!(f, "{}", error_message(message))
            }

            GitError::WorktreeIncludeParseError { error } => {
                let header = error_message(cformat!("Error parsing <bold>.worktreeinclude</>"));
                write!(f, "{}", format_error_block(header, error))
            }

            GitError::WorktreeNotFound { branch } => {
                let switch_cmd = suggest_command("switch", &[branch], &[]);
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("Branch <bold>{branch}</> has no worktree")),
                    hint_message(cformat!(
                        "To create a worktree, run <underline>{switch_cmd}</>"
                    ))
                )
            }

            GitError::RefCreateConflict {
                ref_type,
                number,
                branch,
            } => {
                let name = ref_type.name();
                let syntax = ref_type.syntax();
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Cannot create branch for <bold>{syntax}{number}</> — {name} already has branch <bold>{branch}</>"
                    )),
                    hint_message(cformat!(
                        "To switch to it: <underline>wt switch {syntax}{number}</>"
                    ))
                )
            }

            GitError::RefBaseConflict { ref_type, number } => {
                let syntax = ref_type.syntax();
                let name_plural = ref_type.name_plural();
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Cannot use <bold>--base</> with <bold>{syntax}{number}</>"
                    )),
                    hint_message(cformat!(
                        "{name_plural} already have a base; remove <underline>--base</>"
                    ))
                )
            }

            GitError::BranchTracksDifferentRef {
                branch,
                ref_type,
                number,
            } => {
                // The ref's branch name conflicts with an existing local branch.
                // We can't use a different local name because git push requires
                // the local and remote branch names to match (with push.default=current).
                let escaped = escape(Cow::Borrowed(branch.as_str()));
                let old_name = format!("{branch}-old");
                let escaped_old = escape(Cow::Borrowed(&old_name));
                let name = ref_type.name();
                let symbol = ref_type.symbol();
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!(
                        "Branch <bold>{branch}</> exists but doesn't track {name} {symbol}{number}"
                    )),
                    hint_message(cformat!(
                        "To free the name, run <underline>git branch -m -- {escaped} {escaped_old}</>"
                    ))
                )
            }

            GitError::NoRemoteForRepo {
                owner,
                repo,
                suggested_url,
            } => {
                write!(
                    f,
                    "{}\n{}",
                    error_message(cformat!("No remote found for <bold>{owner}/{repo}</>")),
                    hint_message(cformat!(
                        "Add the remote: <underline>git remote add upstream {suggested_url}</>"
                    ))
                )
            }

            GitError::CliApiError {
                message, stderr, ..
            } => {
                write!(f, "{}", format_error_block(error_message(message), stderr))
            }

            GitError::Other { message } => {
                write!(f, "{}", error_message(message))
            }
        }
    }
}

impl std::fmt::Display for GitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.fmt_with_ctx(f, None)
    }
}

/// Semantic errors that require special handling in main.rs
///
/// Most errors use anyhow::bail! with formatted messages. This enum is only
/// for cases that need exit code extraction or special handling.
#[derive(Debug)]
pub enum WorktrunkError {
    /// Child process exited with non-zero code (preserves exit code for signals).
    ///
    /// `signal` is `Some(sig)` when the process was terminated by a signal
    /// (on Unix), `None` for a normal non-zero exit. Callers that must treat
    /// interrupts differently from ordinary failures (e.g., aborting a loop
    /// on Ctrl-C) check `signal` rather than inferring from `code`.
    ChildProcessExited {
        code: i32,
        message: String,
        signal: Option<i32>,
    },
    /// Hook command failed
    HookCommandFailed {
        hook_type: HookType,
        command_name: Option<String>,
        error: String,
        exit_code: Option<i32>,
    },
    /// Command was not approved by user (silent error)
    CommandNotApproved,
    /// Error already displayed, just exit with given code (silent error)
    AlreadyDisplayed { exit_code: i32 },
}

impl std::fmt::Display for WorktrunkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorktrunkError::ChildProcessExited { message, .. } => {
                write!(f, "{}", error_message(message))
            }
            WorktrunkError::HookCommandFailed {
                hook_type,
                command_name,
                error,
                ..
            } => {
                // Note: Callers that support --no-hooks should add the hint themselves
                if let Some(name) = command_name {
                    write!(
                        f,
                        "{}",
                        error_message(cformat!(
                            "{hook_type} command failed: <bold>{name}</>: {error}"
                        ))
                    )
                } else {
                    write!(
                        f,
                        "{}",
                        error_message(format!("{hook_type} command failed: {error}"))
                    )
                }
            }
            WorktrunkError::CommandNotApproved => {
                Ok(()) // on_skip callback handles the printing
            }
            WorktrunkError::AlreadyDisplayed { .. } => {
                Ok(()) // error already shown via output functions
            }
        }
    }
}

impl std::error::Error for WorktrunkError {}

/// Extract exit code from WorktrunkError, if applicable
pub fn exit_code(err: &anyhow::Error) -> Option<i32> {
    // Check for wrapped HookErrorWithHint first
    if let Some(wrapper) = err.downcast_ref::<HookErrorWithHint>() {
        return exit_code(&wrapper.inner);
    }
    err.downcast_ref::<WorktrunkError>().and_then(|e| match e {
        WorktrunkError::ChildProcessExited { code, .. } => Some(*code),
        WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,
        WorktrunkError::CommandNotApproved => None,
        WorktrunkError::AlreadyDisplayed { exit_code } => Some(*exit_code),
    })
}

/// If `err` is a signal-derived child exit, return the equivalent shell exit
/// code (`128 + signal`).
///
/// Implements the Ctrl-C cancellation policy: command loops call this on every
/// per-iteration failure and, when it returns `Some`, abort the loop rather
/// than continuing to the next iteration. The returned code is what wt itself
/// should exit with, preserving the standard `128 + sig` shell convention
/// (130 for SIGINT, 143 for SIGTERM).
///
/// See the "Signal Handling" section of the project `CLAUDE.md` for the
/// rationale and the full list of loops that apply this policy.
pub fn interrupt_exit_code(err: &anyhow::Error) -> Option<i32> {
    if let Some(WorktrunkError::ChildProcessExited {
        signal: Some(sig), ..
    }) = err.downcast_ref::<WorktrunkError>()
    {
        Some(128 + sig)
    } else {
        None
    }
}

/// If the error is a HookCommandFailed, wrap it to add a hint about using --no-hooks.
///
/// ## When to use
///
/// Use this for commands where a hook runs as a side effect of the user's intent:
/// - `wt merge` - user wants to merge, hooks run as part of that
/// - `wt commit` - user wants to commit, pre-commit hooks run
/// - `wt switch --create` - user wants a worktree, post-create hooks run
///
/// ## When NOT to use
///
/// Don't use for `wt hook <type>` - the user explicitly asked to run hooks,
/// so suggesting `--no-hooks` makes no sense.
pub fn add_hook_skip_hint(err: anyhow::Error) -> anyhow::Error {
    // Extract hook_type first (if applicable), then decide whether to wrap
    let hook_type = err
        .downcast_ref::<WorktrunkError>()
        .and_then(|wt_err| match wt_err {
            WorktrunkError::HookCommandFailed { hook_type, .. } => Some(*hook_type),
            _ => None,
        });

    match hook_type {
        Some(hook_type) => HookErrorWithHint {
            inner: err,
            hook_type,
        }
        .into(),
        None => err,
    }
}

/// Wrapper that displays a HookCommandFailed error with the --no-hooks hint.
/// Created by `add_hook_skip_hint()` for commands that support `--no-hooks`.
#[derive(Debug)]
pub struct HookErrorWithHint {
    inner: anyhow::Error,
    hook_type: HookType,
}

impl std::fmt::Display for HookErrorWithHint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Display the original error (always HookCommandFailed - validated by add_hook_skip_hint)
        write!(f, "{}", self.inner)?;
        // Can't derive command from hook type (e.g., PreRemove is used by both `wt remove` and `wt merge`)
        write!(
            f,
            "\n{}",
            hint_message(cformat!(
                "To skip {} hooks, re-run with <underline>--no-hooks</>",
                self.hook_type
            ))
        )
    }
}

impl std::error::Error for HookErrorWithHint {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.inner.source()
    }
}

/// Format an error with header and gutter content
fn format_error_block(header: impl Into<String>, error: &str) -> String {
    let header = header.into();
    let trimmed = error.trim();
    if trimmed.is_empty() {
        header
    } else {
        format!("{header}\n{}", format_with_gutter(trimmed, None))
    }
}

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

    #[test]
    fn snapshot_into_preserves_type_for_display() {
        // .into() preserves type so we can downcast and use Display
        let err: anyhow::Error = GitError::BranchAlreadyExists {
            branch: "main".into(),
        }
        .into();

        let downcast = err.downcast_ref::<GitError>().expect("Should downcast");
        assert_snapshot!(downcast.to_string(), @"
        ✗ Branch main already exists
        ↳ To switch to the existing branch, run without --create: wt switch main
        ");
    }

    #[test]
    fn test_pattern_matching_with_into() {
        let err: anyhow::Error = GitError::BranchAlreadyExists {
            branch: "main".into(),
        }
        .into();

        if let Some(GitError::BranchAlreadyExists { branch }) = err.downcast_ref::<GitError>() {
            assert_eq!(branch, "main");
        } else {
            panic!("Failed to downcast and pattern match");
        }
    }

    #[test]
    fn snapshot_worktree_error_with_path_and_create() {
        let err = GitError::WorktreePathExists {
            branch: "feature".to_string(),
            path: PathBuf::from("/some/path"),
            create: true,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Directory already exists: /some/path
        ↳ To remove manually, run rm -rf /some/path; to overwrite (with backup), run wt switch --create --clobber feature
        ");
    }

    #[test]
    fn test_exit_code() {
        // ChildProcessExited
        let err: anyhow::Error = WorktrunkError::ChildProcessExited {
            code: 42,
            message: "test".into(),
            signal: None,
        }
        .into();
        assert_eq!(exit_code(&err), Some(42));

        // HookCommandFailed with code
        let err: anyhow::Error = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreMerge,
            command_name: Some("test".into()),
            error: "failed".into(),
            exit_code: Some(1),
        }
        .into();
        assert_eq!(exit_code(&err), Some(1));

        // HookCommandFailed without code
        let err: anyhow::Error = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreMerge,
            command_name: None,
            error: "failed".into(),
            exit_code: None,
        }
        .into();
        assert_eq!(exit_code(&err), None);

        // CommandNotApproved, AlreadyDisplayed, GitError
        assert_eq!(exit_code(&WorktrunkError::CommandNotApproved.into()), None);
        assert_eq!(
            exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 5 }.into()),
            Some(5)
        );
        assert_eq!(
            exit_code(&GitError::DetachedHead { action: None }.into()),
            None
        );

        // Wrapped hook error
        let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreCommit,
            command_name: Some("lint".into()),
            error: "failed".into(),
            exit_code: Some(7),
        }
        .into();
        assert_eq!(exit_code(&add_hook_skip_hint(inner)), Some(7));
    }

    #[test]
    fn test_interrupt_exit_code() {
        // Signal-derived child exit → 128 + sig
        let err: anyhow::Error = WorktrunkError::ChildProcessExited {
            code: 130,
            message: "terminated by signal 2".into(),
            signal: Some(2),
        }
        .into();
        assert_eq!(interrupt_exit_code(&err), Some(130));

        let err: anyhow::Error = WorktrunkError::ChildProcessExited {
            code: 143,
            message: "terminated by signal 15".into(),
            signal: Some(15),
        }
        .into();
        assert_eq!(interrupt_exit_code(&err), Some(143));

        // Ordinary non-zero exit → not an interrupt
        let err: anyhow::Error = WorktrunkError::ChildProcessExited {
            code: 1,
            message: "exit status: 1".into(),
            signal: None,
        }
        .into();
        assert_eq!(interrupt_exit_code(&err), None);

        // Other WorktrunkError variants → not an interrupt
        assert_eq!(
            interrupt_exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 130 }.into()),
            None,
        );
        assert_eq!(
            interrupt_exit_code(&WorktrunkError::CommandNotApproved.into()),
            None,
        );

        // Plain anyhow error → not an interrupt
        assert_eq!(
            interrupt_exit_code(&anyhow::anyhow!("some unrelated failure")),
            None,
        );
    }

    #[test]
    fn snapshot_add_hook_skip_hint() {
        // Wraps HookCommandFailed with --no-hooks hint
        let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreMerge,
            command_name: Some("test".into()),
            error: "failed".into(),
            exit_code: Some(1),
        }
        .into();
        assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
        ✗ pre-merge command failed: test: failed
        ↳ To skip pre-merge hooks, re-run with --no-hooks
        ");

        // pre-commit hook type
        let inner: anyhow::Error = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreCommit,
            command_name: Some("build".into()),
            error: "Build failed".into(),
            exit_code: Some(1),
        }
        .into();
        assert_snapshot!(add_hook_skip_hint(inner).to_string(), @"
        ✗ pre-commit command failed: build: Build failed
        ↳ To skip pre-commit hooks, re-run with --no-hooks
        ");

        // Passes through non-hook errors unchanged (no --no-hooks hint)
        let err: anyhow::Error = WorktrunkError::ChildProcessExited {
            code: 1,
            message: "test".into(),
            signal: None,
        }
        .into();
        assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));

        let err: anyhow::Error = GitError::DetachedHead { action: None }.into();
        assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));

        let err: anyhow::Error = GitError::Other {
            message: "some error".into(),
        }
        .into();
        assert!(!add_hook_skip_hint(err).to_string().contains("--no-hooks"));
    }

    #[test]
    fn test_format_error_block() {
        let header = "Error occurred".to_string();
        assert_snapshot!(format_error_block(header.clone(), "  some error text  "), @"
        Error occurred
          some error text
        ");

        // Empty/whitespace returns header only
        assert_eq!(format_error_block(header.clone(), ""), header);
        assert_eq!(format_error_block(header.clone(), "   \n\t  "), header);
    }

    #[test]
    fn snapshot_worktrunk_error_display() {
        let err = WorktrunkError::ChildProcessExited {
            code: 1,
            message: "Command failed".into(),
            signal: None,
        };
        assert_snapshot!(err.to_string(), @"✗ Command failed");

        let err = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreMerge,
            command_name: Some("lint".into()),
            error: "lint failed".into(),
            exit_code: Some(1),
        };
        assert_snapshot!(err.to_string(), @"✗ pre-merge command failed: lint: lint failed");

        let err = WorktrunkError::HookCommandFailed {
            hook_type: HookType::PreStart,
            command_name: None,
            error: "setup failed".into(),
            exit_code: None,
        };
        assert_snapshot!(err.to_string(), @"✗ pre-start command failed: setup failed");

        // Silent errors produce empty output
        assert_eq!(format!("{}", WorktrunkError::CommandNotApproved), "");
        assert_eq!(
            format!("{}", WorktrunkError::AlreadyDisplayed { exit_code: 1 }),
            ""
        );
    }

    #[test]
    fn snapshot_not_in_worktree() {
        let err = GitError::NotInWorktree {
            action: Some("resolve @".into()),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Cannot resolve @: not in a worktree
        ↳ Run from inside a worktree, or specify a branch name
        ");

        let err = GitError::NotInWorktree { action: None };
        assert_snapshot!(err.to_string(), @"
        ✗ Not in a worktree
        ↳ Run from inside a worktree, or specify a branch name
        ");
    }

    #[test]
    fn snapshot_worktree_path_occupied() {
        let err = GitError::WorktreePathOccupied {
            branch: "feature".into(),
            path: PathBuf::from("/tmp/repo"),
            occupant: Some("main".into()),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Cannot switch to feature — there's a worktree at the expected path /tmp/repo on branch main
        ↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
        ");

        let err = GitError::WorktreePathOccupied {
            branch: "feature".into(),
            path: PathBuf::from("/tmp/repo"),
            occupant: None,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Cannot switch to feature — there's a detached worktree at the expected path /tmp/repo
        ↳ To switch the worktree at /tmp/repo to feature, run cd /tmp/repo && git switch feature
        ");
    }

    #[test]
    fn snapshot_worktree_path_occupied_special_chars() {
        // Spaces in path and branch name require shell escaping in the hint command
        let err = GitError::WorktreePathOccupied {
            branch: "feature/my branch".into(),
            path: PathBuf::from("/tmp/my repo"),
            occupant: Some("main".into()),
        };
        let output = err.to_string();
        // The hint command must quote the path and branch for safe shell execution
        assert!(
            output.contains("cd '/tmp/my repo' && git switch 'feature/my branch'"),
            "expected shell-escaped command in hint, got: {output}"
        );
    }

    #[test]
    fn snapshot_worktree_creation_failed() {
        let err = GitError::WorktreeCreationFailed {
            branch: "feature".into(),
            base_branch: Some("main".into()),
            error: "git error".into(),
            command: None,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Failed to create worktree for feature from base main
          git error
        ");

        let err = GitError::WorktreeCreationFailed {
            branch: "feature".into(),
            base_branch: None,
            error: "git error".into(),
            command: None,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Failed to create worktree for feature
          git error
        ");

        let err = GitError::WorktreeCreationFailed {
            branch: "feature".into(),
            base_branch: Some("main".into()),
            error: "fatal: ref exists".into(),
            command: Some(FailedCommand {
                command: "git worktree add /path -b feature main".into(),
                exit_info: "exit code 128".into(),
            }),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Failed to create worktree for feature from base main
          fatal: ref exists
        ↳ Failed command, exit code 128:
          git worktree add /path -b feature main
        ");
    }

    #[test]
    fn snapshot_worktree_locked() {
        let err = GitError::WorktreeLocked {
            branch: "feature".into(),
            path: PathBuf::from("/tmp/repo.feature"),
            reason: Some("Testing lock".into()),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Cannot remove feature, worktree is locked (Testing lock)
        ↳ To unlock, run git worktree unlock /tmp/repo.feature
        ");

        // Empty reason should not show parentheses
        let err = GitError::WorktreeLocked {
            branch: "feature".into(),
            path: PathBuf::from("/tmp/repo.feature"),
            reason: Some("".into()),
        };
        let display = err.to_string();
        assert_snapshot!(display, @"
        ✗ Cannot remove feature, worktree is locked
        ↳ To unlock, run git worktree unlock /tmp/repo.feature
        ");
        assert!(
            !display.contains("locked ("),
            "should not show parentheses without reason"
        );
    }

    #[test]
    fn snapshot_not_rebased() {
        let err = GitError::NotRebased {
            target_branch: "main".into(),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Branch not rebased onto main
        ↳ To rebase first, run wt step rebase main; or remove --no-rebase
        ");
    }

    #[test]
    fn snapshot_hook_command_not_found() {
        let err = GitError::HookCommandNotFound {
            name: "unknown".into(),
            available: vec!["lint".into(), "test".into()],
        };
        assert_snapshot!(err.to_string(), @"✗ No command named unknown (available: lint, test)");

        let err = GitError::HookCommandNotFound {
            name: "unknown".into(),
            available: vec![],
        };
        assert_snapshot!(err.to_string(), @"✗ No command named unknown (hook has no named commands)");
    }

    #[test]
    fn snapshot_llm_command_failed() {
        let err = GitError::LlmCommandFailed {
            command: "llm".into(),
            error: "connection failed".into(),
            reproduction_command: Some("wt step commit --show-prompt | llm".into()),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Commit generation command failed
          connection failed
        ○ Ran command:
          wt step commit --show-prompt | llm
        ");

        let err = GitError::LlmCommandFailed {
            command: "llm --model gpt-4".into(),
            error: "timeout".into(),
            reproduction_command: None,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Commit generation command failed
          timeout
        ○ Ran command:
          llm --model gpt-4
        ");
    }

    #[test]
    fn snapshot_uncommitted_changes() {
        // Action only (negative assertion kept: no --force)
        let err = GitError::UncommittedChanges {
            action: Some("push".into()),
            branch: None,
            force_hint: false,
        };
        let display = err.to_string();
        assert_snapshot!(display, @"
        ✗ Cannot push: working tree has uncommitted changes
        ↳ Commit or stash changes first
        ");
        assert!(!display.contains("--force"));

        // Branch only
        let err = GitError::UncommittedChanges {
            action: None,
            branch: Some("feature".into()),
            force_hint: false,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ feature has uncommitted changes
        ↳ Commit or stash changes first
        ");

        // Neither action nor branch
        let err = GitError::UncommittedChanges {
            action: None,
            branch: None,
            force_hint: false,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Working tree has uncommitted changes
        ↳ Commit or stash changes first
        ");

        // With force_hint
        let err = GitError::UncommittedChanges {
            action: Some("remove worktree".into()),
            branch: Some("feature".into()),
            force_hint: true,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Cannot remove worktree: feature has uncommitted changes
        ↳ Commit or stash changes first, or to lose uncommitted changes, run wt remove --force feature
        ");
    }

    #[test]
    fn snapshot_not_fast_forward() {
        // Empty commits, outside merge context
        let err = GitError::NotFastForward {
            target_branch: "main".into(),
            commits_formatted: "".into(),
            in_merge_context: false,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Can't push to local main branch: it has newer commits
        ↳ To rebase onto main, run wt step rebase main
        ");

        // With commits, outside merge context
        let err = GitError::NotFastForward {
            target_branch: "develop".into(),
            commits_formatted: "abc123 Some commit".into(),
            in_merge_context: false,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Can't push to local develop branch: it has newer commits
          abc123 Some commit
        ↳ To rebase onto develop, run wt step rebase develop
        ");

        // In merge context
        let err = GitError::NotFastForward {
            target_branch: "main".into(),
            commits_formatted: "def456 Another commit".into(),
            in_merge_context: true,
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Can't push to local main branch: it has newer commits
          def456 Another commit
        ↳ To incorporate these changes, run wt merge main again
        ");
    }

    #[test]
    fn snapshot_conflicting_changes_empty_files() {
        let err = GitError::ConflictingChanges {
            target_branch: "main".into(),
            files: vec![],
            worktree_path: PathBuf::from("/tmp/repo"),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Can't push to local main branch: conflicting uncommitted changes
        ↳ Commit or stash these changes in /tmp/repo first
        ");
    }

    #[test]
    fn snapshot_cli_api_error() {
        let err = GitError::CliApiError {
            ref_type: RefType::Pr,
            message: "gh api failed for PR #42".into(),
            stderr: "error: unexpected response\ncode: 500".into(),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ gh api failed for PR #42
          error: unexpected response
          code: 500
        ");
    }

    #[test]
    fn snapshot_no_remote_for_repo() {
        let err = GitError::NoRemoteForRepo {
            owner: "upstream-owner".into(),
            repo: "upstream-repo".into(),
            suggested_url: "https://github.com/upstream-owner/upstream-repo.git".into(),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ No remote found for upstream-owner/upstream-repo
        ↳ Add the remote: git remote add upstream https://github.com/upstream-owner/upstream-repo.git
        ");
    }

    #[test]
    fn snapshot_rebase_conflict_empty_output() {
        let err = GitError::RebaseConflict {
            target_branch: "main".into(),
            git_output: "".into(),
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Rebase onto main incomplete
        ↳ To continue after resolving conflicts, run git rebase --continue
        ↳ To abort, run git rebase --abort
        ");
    }

    #[test]
    fn snapshot_with_switch_suggestion_branch_already_exists() {
        let err = GitError::WithSwitchSuggestion {
            source: Box::new(GitError::BranchAlreadyExists {
                branch: "emails".into(),
            }),
            ctx: SwitchSuggestionCtx {
                extra_flags: vec!["--execute=claude".into()],
                trailing_args: vec!["Check my emails".into()],
            },
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Branch emails already exists
        ↳ To switch to the existing branch, run without --create: wt switch emails --execute=claude -- 'Check my emails'
        ");
    }

    #[test]
    fn snapshot_with_switch_suggestion_worktree_path_exists() {
        let err = GitError::WithSwitchSuggestion {
            source: Box::new(GitError::WorktreePathExists {
                branch: "emails".into(),
                path: PathBuf::from("/tmp/repo.emails"),
                create: true,
            }),
            ctx: SwitchSuggestionCtx {
                extra_flags: vec!["--execute=claude".into()],
                trailing_args: vec!["Check my emails".into()],
            },
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Directory already exists: /tmp/repo.emails
        ↳ To remove manually, run rm -rf /tmp/repo.emails; to overwrite (with backup), run wt switch --create --clobber emails --execute=claude -- 'Check my emails'
        ");
    }

    #[test]
    fn snapshot_with_switch_suggestion_no_trailing_args() {
        let err = GitError::WithSwitchSuggestion {
            source: Box::new(GitError::BranchAlreadyExists {
                branch: "emails".into(),
            }),
            ctx: SwitchSuggestionCtx {
                extra_flags: vec!["--execute=claude".into()],
                trailing_args: vec![],
            },
        };
        assert_snapshot!(err.to_string(), @"
        ✗ Branch emails already exists
        ↳ To switch to the existing branch, run without --create: wt switch emails --execute=claude
        ");
    }

    #[test]
    fn snapshot_with_switch_suggestion_branch_not_found() {
        let err = GitError::WithSwitchSuggestion {
            source: Box::new(GitError::BranchNotFound {
                branch: "emails".into(),
                show_create_hint: true,
                last_fetch_ago: None,
            }),
            ctx: SwitchSuggestionCtx {
                extra_flags: vec!["--execute=claude".into()],
                trailing_args: vec!["Check my emails".into()],
            },
        };
        assert_snapshot!(err.to_string(), @"
        ✗ No branch named emails
        ↳ To create a new branch, run wt switch --create emails --execute=claude -- 'Check my emails'; to list branches, run wt list --branches --remotes
        ");
    }

    #[test]
    fn test_with_switch_suggestion_unwrapped_errors_unaffected() {
        // Non-switch-suggestion errors should be completely unaffected by the wrapper
        let inner = GitError::DetachedHead {
            action: Some("merge".into()),
        };
        let wrapped = GitError::WithSwitchSuggestion {
            source: Box::new(inner.clone()),
            ctx: SwitchSuggestionCtx {
                extra_flags: vec!["--execute=claude".into()],
                trailing_args: vec!["Check my emails".into()],
            },
        };
        // Errors without switch suggestions should render identically
        assert_eq!(inner.to_string(), wrapped.to_string());
    }
}