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
use crate::common::{
    BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_files,
    configure_git_cmd, configure_git_env, directive_files, repo, setup_temp_snapshot_settings,
    wait_for_file, wait_for_file_content, wait_for_worktree_removed, wt_command,
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::Duration;
use worktrunk::shell_exec::Cmd;

#[test]
fn test_bare_repo_list_worktrees() {
    let test = BareRepoTest::new();

    // Create worktrees inside bare repo matching template: {{ branch }}
    // Worktrees are at repo/main and repo/feature
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit on main");

    let feature_worktree = test.create_worktree("feature", "feature");
    test.commit_in(&feature_worktree, "Work on feature");

    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        // Run wt list from the main worktree
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(&main_worktree);

        assert_cmd_snapshot!(cmd);
    });
}

#[test]
fn test_bare_repo_list_shows_no_bare_entry() {
    let test = BareRepoTest::new();

    // Create one worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Run wt list and verify bare repo is NOT shown (only main worktree appears)
    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(&main_worktree);

        assert_cmd_snapshot!(cmd);
    });
}

#[test]
fn test_bare_repo_switch_creates_worktree() {
    let test = BareRepoTest::new();

    // Create initial worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Run wt switch --create to create a new worktree
    // Config uses {{ branch }} template, so worktrees are created inside bare repo
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature"])
        .current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify the new worktree was created inside the bare repo
    // Template: {{ branch }} -> repo/feature
    let expected_path = test.bare_repo_path().join("feature");
    assert!(
        expected_path.exists(),
        "Expected worktree at {:?}",
        expected_path
    );

    // Verify git worktree list shows both worktrees (but not bare repo)
    let output = test
        .git_command(test.bare_repo_path())
        .args(["worktree", "list"])
        .run()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should show 3 entries: bare repo + 2 worktrees
    assert_eq!(stdout.lines().count(), 3);
}

#[test]
fn test_bare_repo_switch_with_configured_naming() {
    let test = BareRepoTest::new();

    // Create initial worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Config uses "{{ branch }}" template, so worktrees are created inside bare repo
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature"])
        .current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify worktree was created inside bare repo
    let expected_path = test.bare_repo_path().join("feature");
    assert!(
        expected_path.exists(),
        "Expected worktree at {:?}",
        expected_path
    );
}

#[test]
fn test_bare_repo_remove_worktree() {
    let test = BareRepoTest::new();

    // Create two worktrees
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    let feature_worktree = test.create_worktree("feature", "feature");
    test.commit_in(&feature_worktree, "Feature work");

    // Remove feature worktree from main worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["remove", "feature", "--foreground"])
        .current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt remove failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify feature worktree was removed
    assert!(
        !feature_worktree.exists(),
        "Feature worktree should be removed"
    );

    // Verify main worktree still exists
    assert!(main_worktree.exists());
}

#[test]
fn test_bare_repo_identifies_primary_correctly() {
    let test = BareRepoTest::new();

    // Create multiple worktrees
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Main commit");

    let _feature1 = test.create_worktree("feature1", "feature1");
    let _feature2 = test.create_worktree("feature2", "feature2");

    // Run wt list to see which is marked as primary
    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(&main_worktree);

        assert_cmd_snapshot!(cmd);
    });
}

#[test]
fn test_bare_repo_path_used_for_worktree_paths() {
    let test = BareRepoTest::new();

    // Create initial worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Create new worktree - config uses {{ branch }} template
    // Worktrees are created inside the bare repo directory
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "dev"])
        .current_dir(&main_worktree);

    cmd.output().unwrap();

    // Verify path is created inside bare repo (using repo_path as base)
    // Template: {{ branch }} -> repo/dev
    let expected = test.bare_repo_path().join("dev");
    assert!(
        expected.exists(),
        "Worktree should be created using repo_path: {:?}",
        expected
    );

    // Should NOT be relative to main worktree's directory (as if it were a non-bare repo)
    let wrong_path = main_worktree.parent().unwrap().join("main.dev");
    assert!(
        !wrong_path.exists(),
        "Worktree should not use worktree directory as base"
    );
}

#[test]
fn test_bare_repo_with_repo_path_variable() {
    // Test that {{ repo_path }} resolves correctly in bare repos
    // For bare repos, repo_path should be the bare repo directory itself
    let test = BareRepoTest::new();

    // Override config to use {{ repo_path }} explicitly
    fs::write(
        test.config_path(),
        "worktree-path = \"{{ repo_path }}/../worktrees/{{ branch | sanitize }}\"\n",
    )
    .unwrap();

    // Create initial worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Create new worktree using wt switch
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature/auth"])
        .current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify worktree was created at sibling path using {{ repo_path }}/../worktrees/
    // Bare repo is at /tmp/xxx/repo, so worktree should be at /tmp/xxx/worktrees/feature-auth
    let expected_path = test
        .bare_repo_path()
        .parent()
        .unwrap()
        .join("worktrees")
        .join("feature-auth");
    assert!(
        expected_path.exists(),
        "Expected worktree at {:?} (using repo_path variable)",
        expected_path
    );
}

/// Regression test for #1914: when `wt` is invoked via a git shell alias
/// (`alias.wt = "!wt"`), git exports `GIT_DIR` — sometimes as a *relative*
/// path like `.git`. That relative path would otherwise re-resolve against
/// every child command's `current_dir`, breaking worktrunk's repo discovery
/// in bare-layout repositories. Worktrunk normalizes inherited relative
/// `GIT_*` path variables at startup so `{{ repo_path }}` resolves
/// identically whether `wt` is invoked directly or via a git alias.
#[test]
fn test_bare_repo_repo_path_with_inherited_relative_git_dir() {
    let test = BareRepoTest::new();

    // Configure a user-level alias that prints repo_path. We use user config
    // (not project config) so it's discoverable even when the command is
    // launched from the bare repo's parent directory.
    let user_config = test.temp_path().join("user-config.toml");
    fs::write(
        &user_config,
        "[aliases]\nprint-repo-path = \"echo REPO_PATH={{ repo_path }}\"\n",
    )
    .unwrap();

    // Create a linked worktree so there's somewhere to run from.
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Helper: run `wt step print-repo-path` and extract the
    // `REPO_PATH=...` value emitted by the alias. We compare these as-is
    // so platform-specific path formatting (e.g. msys-style paths that
    // Git Bash uses on Windows for `echo`) doesn't affect the test — we
    // only assert that both invocations produce the *same* value.
    // No `-y` needed: user-config aliases skip approval entirely.
    let extract_repo_path = |out: &std::process::Output| -> String {
        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        combined
            .lines()
            .find_map(|line| line.trim().strip_prefix("REPO_PATH=").map(str::to_owned))
            .unwrap_or_else(|| panic!("no REPO_PATH= line in output:\n{combined}"))
    };

    // Baseline: invoke `wt` normally from the main worktree.
    let mut baseline = wt_command();
    test.configure_wt_cmd(&mut baseline);
    baseline
        .env("WORKTRUNK_CONFIG_PATH", &user_config)
        .args(["step", "print-repo-path"])
        .current_dir(&main_worktree);
    let baseline_out = baseline.output().unwrap();
    assert!(
        baseline_out.status.success(),
        "baseline wt failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&baseline_out.stdout),
        String::from_utf8_lossy(&baseline_out.stderr)
    );
    let baseline_repo_path = extract_repo_path(&baseline_out);

    // Simulate a git alias invocation: git sets GIT_DIR (and GIT_PREFIX) for
    // shell aliases. From a linked worktree, git sets GIT_DIR to the
    // per-worktree admin dir — use a relative spelling to exercise the bug.
    let worktree_git_dir = test.bare_repo_path().join("worktrees").join("main");
    assert!(
        worktree_git_dir.exists(),
        "expected linked worktree admin dir at {worktree_git_dir:?}"
    );
    // Relative path from main_worktree to its per-worktree admin dir.
    let relative_git_dir = PathBuf::from("..").join("worktrees").join("main");

    let mut via_alias = wt_command();
    test.configure_wt_cmd(&mut via_alias);
    via_alias
        .env("WORKTRUNK_CONFIG_PATH", &user_config)
        .env("GIT_DIR", &relative_git_dir)
        .env("GIT_PREFIX", "")
        .args(["step", "print-repo-path"])
        .current_dir(&main_worktree);
    let via_alias_out = via_alias.output().unwrap();
    assert!(
        via_alias_out.status.success(),
        "wt via git alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&via_alias_out.stdout),
        String::from_utf8_lossy(&via_alias_out.stderr)
    );
    let via_alias_repo_path = extract_repo_path(&via_alias_out);

    assert_eq!(
        baseline_repo_path, via_alias_repo_path,
        "repo_path differed when invoked via a simulated git alias \
         (relative GIT_DIR was not normalized — see #1914)"
    );
}

/// Companion to `test_bare_repo_repo_path_with_inherited_relative_git_dir`
/// that exercises the full `git wt …` → `sh -c` → `wt` path using a *real*
/// git alias instead of hand-crafted `GIT_*` env vars.
///
/// To actually trigger #1914, the layout must match the issue reporter's:
/// `repo/.git` is the bare repository and `repo/main` is a linked worktree.
/// Running `git wt …` from `repo/` causes git to export `GIT_DIR=.git`
/// (relative), which is the bug vector — `BareRepoTest` uses a different
/// layout (`repo/` *is* the bare) where git exports an absolute `GIT_DIR`
/// and the bug doesn't reproduce, so we build the layout by hand here.
///
/// Unix-only: git aliases execute via `sh -c`, and shell-quoting the wt
/// binary path for Windows' bundled sh is fiddly. The underlying fix in
/// `shell_exec.rs` has no platform-specific code, so the simulated-env
/// companion test still exercises the normalization on Windows.
#[cfg(not(windows))]
#[test]
fn test_repo_path_via_real_git_alias_bare_dot_git_layout() {
    use crate::common::{configure_git_env, wt_bin};

    let temp_dir = tempfile::TempDir::new().unwrap();
    let temp_path = canonicalize(temp_dir.path()).unwrap();

    // Isolated gitconfig so we don't leak the user's real git settings.
    let git_config_path = temp_path.join("test-gitconfig");
    fs::write(
        &git_config_path,
        "[user]\n\tname = Test User\n\temail = test@example.com\n\
         [init]\n\tdefaultBranch = main\n",
    )
    .unwrap();

    // Layout: repo/.git (bare) + repo/main (linked worktree).
    let repo_dir = temp_path.join("repo");
    fs::create_dir(&repo_dir).unwrap();
    let bare_git = repo_dir.join(".git");

    let git = |dir: &Path| configure_git_env(Cmd::new("git"), &git_config_path).current_dir(dir);

    git(&temp_path)
        .args(["init", "--bare", "--initial-branch", "main"])
        .arg(bare_git.to_str().unwrap())
        .run()
        .unwrap();
    git(&bare_git)
        .args(["worktree", "add", "../main"])
        .run()
        .unwrap();

    let main_worktree = repo_dir.join("main");
    fs::write(main_worktree.join("a.txt"), "hello").unwrap();
    git(&main_worktree).args(["add", "a.txt"]).run().unwrap();
    git(&main_worktree)
        .args(["commit", "-m", "Initial commit"])
        .run()
        .unwrap();

    // wt config with worktree-path template and the `print-repo-path` alias.
    let user_config = temp_path.join("test-config.toml");
    fs::write(
        &user_config,
        "worktree-path = \"{{ branch }}\"\n\
         [aliases]\nprint-repo-path = \"echo REPO_PATH={{ repo_path }}\"\n",
    )
    .unwrap();
    let approvals_path = temp_path.join("test-approvals.toml");

    // Register the real git alias in the bare repo's config.
    let wt_path = wt_bin();
    let wt_path_lossy = wt_path.to_string_lossy();
    let wt_path_escaped = shell_escape::unix::escape(wt_path_lossy);
    git(&bare_git)
        .args(["config", "alias.wt", &format!("!{wt_path_escaped}")])
        .run()
        .unwrap();

    let extract_repo_path = |out: &std::process::Output| -> String {
        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        combined
            .lines()
            .find_map(|line| line.trim().strip_prefix("REPO_PATH=").map(str::to_owned))
            .unwrap_or_else(|| panic!("no REPO_PATH= line in output:\n{combined}"))
    };

    // Shared wt env applied to both the direct and aliased invocations.
    let apply_wt_env = |cmd: &mut Command| {
        configure_git_cmd(cmd, &git_config_path);
        cmd.env("WORKTRUNK_CONFIG_PATH", &user_config)
            .env(
                "WORKTRUNK_SYSTEM_CONFIG_PATH",
                "/etc/xdg/worktrunk/config.toml",
            )
            .env("WORKTRUNK_APPROVALS_PATH", &approvals_path)
            .env_remove("NO_COLOR")
            .env_remove("CLICOLOR_FORCE");
    };

    // Baseline: invoke `wt` directly from `repo/`. Git discovers the bare
    // `.git` automatically without exporting any `GIT_*` path vars.
    let mut baseline = Command::new(wt_bin());
    apply_wt_env(&mut baseline);
    baseline
        .args(["step", "print-repo-path"])
        .current_dir(&repo_dir);
    let baseline_out = baseline.output().unwrap();
    assert!(
        baseline_out.status.success(),
        "baseline wt failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&baseline_out.stdout),
        String::from_utf8_lossy(&baseline_out.stderr)
    );
    let baseline_repo_path = extract_repo_path(&baseline_out);

    // Via the real git alias: `git wt step print-repo-path`. From the
    // `repo/` dir (not inside the worktree), git sets `GIT_DIR=.git`
    // (relative) when exporting the alias environment — the exact bug vector
    // from #1914.
    let mut via_alias = Command::new("git");
    apply_wt_env(&mut via_alias);
    via_alias
        .args(["wt", "step", "print-repo-path"])
        .current_dir(&repo_dir);
    let via_alias_out = via_alias.output().unwrap();
    assert!(
        via_alias_out.status.success(),
        "git wt via real alias failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&via_alias_out.stdout),
        String::from_utf8_lossy(&via_alias_out.stderr)
    );
    let via_alias_repo_path = extract_repo_path(&via_alias_out);

    assert_eq!(
        baseline_repo_path, via_alias_repo_path,
        "repo_path differed when invoked via a real `git wt` alias — see #1914"
    );
}

#[rstest]
fn test_bare_repo_equivalent_to_normal_repo(repo: TestRepo) {
    // This test verifies that bare repos behave identically to normal repos
    // from the user's perspective

    // Remove fixture worktrees to get a clean state with just main
    for branch in &["feature-a", "feature-b", "feature-c"] {
        let worktree_path = repo
            .root_path()
            .parent()
            .unwrap()
            .join(format!("repo.{}", branch));
        if worktree_path.exists() {
            repo.git_command()
                .args([
                    "worktree",
                    "remove",
                    "--force",
                    worktree_path.to_str().unwrap(),
                ])
                .run()
                .unwrap();
        }
    }

    // Set up bare repo
    let bare_test = BareRepoTest::new();
    let bare_main = bare_test.create_worktree("main", "main");
    bare_test.commit_in(&bare_main, "Commit in bare repo");

    // Set up normal repo (using fixture)
    repo.commit("Commit in normal repo");

    // Configure both with same worktree path pattern
    let config = r#"
worktree-path = "{{ branch }}"
"#;
    fs::write(bare_test.config_path(), config).unwrap();
    fs::write(repo.test_config_path(), config).unwrap();

    // List worktrees in both - should show similar structure
    let mut bare_list = wt_command();
    bare_test.configure_wt_cmd(&mut bare_list);
    bare_list.arg("list").current_dir(&bare_main);

    let mut normal_list = wt_command();
    repo.configure_wt_cmd(&mut normal_list);
    normal_list.arg("list").current_dir(repo.root_path());

    let bare_output = bare_list.output().unwrap();
    let normal_output = normal_list.output().unwrap();

    // Both should show 1 worktree (main/main) - table output is on stdout
    let bare_stdout = String::from_utf8_lossy(&bare_output.stdout);
    let normal_stdout = String::from_utf8_lossy(&normal_output.stdout);

    assert!(bare_stdout.contains("main"));
    assert!(normal_stdout.contains("main"));
    assert_eq!(bare_stdout.lines().count(), normal_stdout.lines().count());
}

#[test]
fn test_bare_repo_commands_from_bare_directory() {
    let test = BareRepoTest::new();

    // Create a worktree so the repo has some content
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Run wt list from the bare repo directory itself (not from a worktree)
    // Should list the worktree even when run from bare repo, not showing bare repo itself
    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(test.bare_repo_path());

        assert_cmd_snapshot!(cmd);
    });
}

///
/// Skipped on Windows due to file locking issues that prevent worktree removal
/// during background cleanup after merge. The merge functionality itself works
/// correctly - this is a timing/cleanup issue specific to Windows file handles.
#[test]
fn test_bare_repo_merge_workflow() {
    let test = BareRepoTest::new();

    // Create main worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit on main");

    // Create feature branch worktree using wt switch
    // Config uses {{ branch }} template, so worktrees are inside bare repo
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature"])
        .current_dir(&main_worktree);
    cmd.output().unwrap();

    // Get feature worktree path (template: {{ branch }} -> repo/feature)
    let feature_worktree = test.bare_repo_path().join("feature");
    assert!(feature_worktree.exists());

    // Make a commit in feature worktree
    test.commit_in(&feature_worktree, "Feature work");

    // Merge feature into main (explicitly specify target)
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args([
        "merge",
        "main",        // Explicitly specify target branch
        "--no-squash", // Skip squash to avoid LLM dependency
        "--no-hooks",  // Skip pre-merge hooks
    ])
    .current_dir(&feature_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt merge failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Wait for background removal to complete
    // Use the "gone or empty placeholder" predicate — the instant-removal
    // path leaves an empty dir behind if the background `rmdir` silently
    // fails (stray `.DS_Store`, scheduling delay under parallel load).
    // That placeholder is production-harmless but trips a strict
    // `!exists()` check.
    wait_for_worktree_removed(&feature_worktree);

    // Verify main worktree still exists and has the feature commit
    assert!(main_worktree.exists());

    // Check that feature branch commit is now in main
    let log_output = test
        .git_command(&main_worktree)
        .args(["log", "--oneline"])
        .run()
        .unwrap();

    let log = String::from_utf8_lossy(&log_output.stdout);
    assert!(
        log.contains("Feature work"),
        "Main should contain feature commit after merge"
    );
}

#[test]
fn test_bare_repo_background_logs_location() {
    // This test verifies that background operation logs go to the correct location
    // in bare repos (bare_repo/wt/logs/ instead of worktree/.git/wt/logs/)
    let test = BareRepoTest::new();

    // Create main worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Create feature worktree
    let feature_worktree = test.create_worktree("feature", "feature");
    test.commit_in(&feature_worktree, "Feature work");

    // Run remove in background to test log file location
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["remove", "feature"]).current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt remove failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Wait for background process to create log file (poll instead of fixed sleep)
    // The key test is that the path is correct, not that content was written
    // (background processes are flaky in tests). Logs live at:
    // `{bare_repo}/wt/logs/{sanitized-branch}/internal/remove.log`
    let log_dir = test.bare_repo_path().join("wt/logs");
    let remove_log = log_dir
        .join(worktrunk::path::sanitize_for_filename("feature"))
        .join("internal")
        .join("remove.log");
    wait_for_file(&remove_log);
    assert!(
        remove_log.exists(),
        "Expected remove log at {}",
        remove_log.display()
    );

    // Verify it's NOT in the worktree's .git directory (which doesn't exist for linked worktrees)
    let wrong_dir = main_worktree.join(".git/wt/logs");
    assert!(
        !wrong_dir.exists()
            || std::fs::read_dir(&wrong_dir)
                .map(|d| d.count())
                .unwrap_or(0)
                == 0,
        "Log should NOT be in worktree's .git directory"
    );
}

#[test]
fn test_bare_repo_project_config_found_from_bare_root() {
    // Regression test for #1691: project config in the primary worktree should be
    // found when running from the bare repo root directory, not just from within
    // a worktree that contains the config.
    let test = BareRepoTest::new();

    // Create main worktree (the primary worktree for bare repos)
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Place project config in the primary worktree's .config/wt.toml
    let config_dir = main_worktree.join(".config");
    fs::create_dir_all(&config_dir).unwrap();

    // Use a marker file to prove the hook ran
    let marker_path = test.bare_repo_path().join("hook-ran.marker");
    let marker_str = marker_path.to_str().unwrap().replace('\\', "/");
    fs::write(
        config_dir.join("wt.toml"),
        format!("post-start = \"echo hook-executed > '{}'\"\n", marker_str),
    )
    .unwrap();

    // Commit the config so it's part of the worktree
    let output = test
        .git_command(&main_worktree)
        .args(["add", ".config/wt.toml"])
        .run()
        .unwrap();
    assert!(output.status.success());
    test.commit_in(&main_worktree, "Add project config");

    // Now run `wt switch --create feature` from the bare repo root (NOT from main worktree)
    // This is the scenario described in #1691
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature", "--yes"])
        .current_dir(test.bare_repo_path());

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // The hook from the primary worktree's config should have executed
    wait_for_file_content(&marker_path);
    let content = fs::read_to_string(&marker_path).unwrap();
    assert!(
        content.contains("hook-executed"),
        "Hook from primary worktree config should run when command is invoked from bare root. \
         Marker file content: {:?}",
        content
    );
}

#[test]
fn test_bare_repo_project_config_found_with_dash_c_flag() {
    // Regression test for #1691 (comment): project config in the primary worktree
    // should be found when using `-C <repo>` from an unrelated directory.
    let test = BareRepoTest::new();

    // Create main worktree (the primary worktree for bare repos)
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Place project config in the primary worktree's .config/wt.toml
    let config_dir = main_worktree.join(".config");
    fs::create_dir_all(&config_dir).unwrap();

    // Use a marker file to prove the hook ran
    let marker_path = test.bare_repo_path().join("hook-ran-c-flag.marker");
    let marker_str = marker_path.to_str().unwrap().replace('\\', "/");
    fs::write(
        config_dir.join("wt.toml"),
        format!("post-start = \"echo hook-executed > '{}'\"\n", marker_str),
    )
    .unwrap();

    // Commit the config so it's part of the worktree
    let output = test
        .git_command(&main_worktree)
        .args(["add", ".config/wt.toml"])
        .run()
        .unwrap();
    assert!(output.status.success());
    test.commit_in(&main_worktree, "Add project config");

    // Run from a completely unrelated directory using -C to point at the bare repo
    let unrelated_dir = tempfile::tempdir().unwrap();
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args([
        "-C",
        test.bare_repo_path().to_str().unwrap(),
        "switch",
        "--create",
        "feature-c-flag",
        "--yes",
    ])
    .current_dir(unrelated_dir.path());

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch -C failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // The hook from the primary worktree's config should have executed
    wait_for_file_content(&marker_path);
    let content = fs::read_to_string(&marker_path).unwrap();
    assert!(
        content.contains("hook-executed"),
        "Hook from primary worktree config should run when using -C flag. \
         Marker file content: {:?}",
        content
    );
}

#[test]
fn test_bare_repo_ignores_config_in_bare_root() {
    // Regression test for #1691: a `.config/wt.toml` placed in the bare repo root
    // directory should NOT be picked up. Only the primary worktree's config matters.
    let test = BareRepoTest::new();

    // Create main worktree (the primary worktree for bare repos) — no config here
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Place config in the bare repo root (NOT in a worktree)
    let config_dir = test.bare_repo_path().join(".config");
    fs::create_dir_all(&config_dir).unwrap();

    let marker_path = test.bare_repo_path().join("hook-should-not-run.marker");
    let marker_str = marker_path.to_str().unwrap().replace('\\', "/");
    fs::write(
        config_dir.join("wt.toml"),
        format!("post-start = \"echo bad > '{}'\"\n", marker_str),
    )
    .unwrap();

    // Run `wt switch --create feature` from the bare repo root
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature", "--yes"])
        .current_dir(test.bare_repo_path());

    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "wt switch failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    // The hook from the bare root config should NOT have executed
    thread::sleep(Duration::from_millis(500));
    assert!(
        !marker_path.exists(),
        "Config in bare repo root should be ignored — only primary worktree config should be used"
    );
}

#[test]
fn test_bare_repo_slashed_branch_with_sanitize() {
    // Test that slashed branch names work with bare repos and the sanitize filter
    // This matches the documented workflow in tips-patterns.md
    let test = BareRepoTest::new();

    // Override config to use sanitize filter (matches documented config)
    fs::write(
        test.config_path(),
        "worktree-path = \"{{ branch | sanitize }}\"\n",
    )
    .unwrap();

    // Create main worktree
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit");

    // Create feature branch with slash using wt switch
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature/auth"])
        .current_dir(&main_worktree);

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify worktree was created with sanitized name (feature-auth, not feature/auth)
    let expected_path = test.bare_repo_path().join("feature-auth");
    assert!(
        expected_path.exists(),
        "Expected worktree at {:?} (sanitized from feature/auth)",
        expected_path
    );

    // Verify slashed path was NOT created
    let wrong_path = test.bare_repo_path().join("feature/auth");
    assert!(
        !wrong_path.exists(),
        "Should not create nested directory for slashed branch"
    );

    // Verify git branch name is preserved (not sanitized)
    let branch_output = test
        .git_command(&expected_path)
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .run()
        .unwrap();
    assert_eq!(
        String::from_utf8_lossy(&branch_output.stdout).trim(),
        "feature/auth",
        "Git branch name should be preserved as feature/auth"
    );
}

/// Helper to create a nested bare repository test setup (project/.git pattern)
///
/// This tests the pattern from GitHub issue #313 where users clone with:
/// `git clone --bare <url> project/.git`
struct NestedBareRepoTest {
    temp_dir: tempfile::TempDir,
    /// Path to the parent directory (project/)
    project_path: PathBuf,
    /// Path to the bare repo (project/.git/)
    bare_repo_path: PathBuf,
    test_config_path: PathBuf,
    git_config_path: PathBuf,
}

impl NestedBareRepoTest {
    fn new() -> Self {
        let temp_dir = tempfile::TempDir::new().unwrap();
        // Create project directory
        let project_path = temp_dir.path().join("project");
        fs::create_dir(&project_path).unwrap();

        // Bare repo inside project directory as .git
        let bare_repo_path = project_path.join(".git");
        let test_config_path = temp_dir.path().join("test-config.toml");
        let git_config_path = temp_dir.path().join("test-gitconfig");

        // Write git config with user settings (like TestRepo)
        fs::write(
            &git_config_path,
            "[user]\n\tname = Test User\n\temail = test@example.com\n\
             [advice]\n\tmergeConflict = false\n\tresolveConflict = false\n\
             [init]\n\tdefaultBranch = main\n",
        )
        .unwrap();

        let mut test = Self {
            temp_dir,
            project_path,
            bare_repo_path,
            test_config_path,
            git_config_path,
        };

        // Create bare repository at project/.git
        let output = configure_git_env(Cmd::new("git"), &test.git_config_path)
            .args(["init", "--bare", "--initial-branch", "main"])
            .arg(test.bare_repo_path.to_str().unwrap())
            .run()
            .unwrap();

        if !output.status.success() {
            panic!(
                "Failed to init nested bare repo:\nstdout: {}\nstderr: {}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Canonicalize paths
        test.project_path = canonicalize(&test.project_path).unwrap();
        test.bare_repo_path = canonicalize(&test.bare_repo_path).unwrap();

        // Write config with template for worktrees as siblings to .git
        // For nested bare repos (project/.git), we use "../{{ branch }}" to create
        // worktrees at project/main, project/feature (siblings to .git)
        fs::write(
            &test.test_config_path,
            "worktree-path = \"../{{ branch }}\"\n",
        )
        .unwrap();

        test
    }

    fn project_path(&self) -> &PathBuf {
        &self.project_path
    }

    fn bare_repo_path(&self) -> &PathBuf {
        &self.bare_repo_path
    }

    fn config_path(&self) -> &Path {
        &self.test_config_path
    }

    fn temp_path(&self) -> &Path {
        self.temp_dir.path()
    }

    /// Configure a wt command with test environment
    fn configure_wt_cmd(&self, cmd: &mut Command) {
        self.configure_git_cmd(cmd);
        cmd.env("WORKTRUNK_CONFIG_PATH", &self.test_config_path)
            .env_remove("NO_COLOR")
            .env_remove("CLICOLOR_FORCE");
    }

    /// Get test environment variables as a vector for PTY tests.
    #[cfg(all(unix, feature = "shell-integration-tests"))]
    fn test_env_vars(&self) -> Vec<(String, String)> {
        use crate::common::{NULL_DEVICE, STATIC_TEST_ENV_VARS, TEST_EPOCH};

        let mut vars: Vec<(String, String)> = STATIC_TEST_ENV_VARS
            .iter()
            .map(|&(k, v)| (k.to_string(), v.to_string()))
            .collect();

        // HOME and XDG_CONFIG_HOME are needed for config lookups in env_clear'd PTY
        let home = self.temp_dir.path().join("home");
        std::fs::create_dir_all(&home).ok();

        vars.extend([
            (
                "GIT_CONFIG_GLOBAL".to_string(),
                self.git_config_path.display().to_string(),
            ),
            ("GIT_CONFIG_SYSTEM".to_string(), NULL_DEVICE.to_string()),
            (
                "GIT_AUTHOR_DATE".to_string(),
                "2025-01-01T00:00:00Z".to_string(),
            ),
            (
                "GIT_COMMITTER_DATE".to_string(),
                "2025-01-01T00:00:00Z".to_string(),
            ),
            ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
            ("HOME".to_string(), home.display().to_string()),
            (
                "XDG_CONFIG_HOME".to_string(),
                home.join(".config").display().to_string(),
            ),
            ("WORKTRUNK_TEST_EPOCH".to_string(), TEST_EPOCH.to_string()),
            (
                "WORKTRUNK_CONFIG_PATH".to_string(),
                self.test_config_path.display().to_string(),
            ),
            (
                "WORKTRUNK_SYSTEM_CONFIG_PATH".to_string(),
                "/etc/xdg/worktrunk/config.toml".to_string(),
            ),
            (
                "WORKTRUNK_APPROVALS_PATH".to_string(),
                self.temp_dir
                    .path()
                    .join("test-approvals.toml")
                    .display()
                    .to_string(),
            ),
        ]);

        vars
    }
}

impl TestRepoBase for NestedBareRepoTest {
    fn git_config_path(&self) -> &Path {
        &self.git_config_path
    }
}

/// instead of project/.git/ (GitHub issue #313)
#[test]
fn test_nested_bare_repo_worktree_path() {
    let test = NestedBareRepoTest::new();

    // Create first worktree using wt switch --create
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "main"])
        .current_dir(test.bare_repo_path());

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch --create main failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // CRITICAL: Worktree should be at project/main, NOT project/.git/main
    let expected_path = test.project_path().join("main");
    let wrong_path = test.bare_repo_path().join("main");

    assert!(
        expected_path.exists(),
        "Expected worktree at {:?} (sibling to .git)",
        expected_path
    );
    assert!(
        !wrong_path.exists(),
        "Worktree should NOT be inside .git directory at {:?}",
        wrong_path
    );
}

#[test]
fn test_nested_bare_repo_full_workflow() {
    let test = NestedBareRepoTest::new();

    // Create main worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "main"])
        .current_dir(test.bare_repo_path());
    cmd.output().unwrap();

    let main_worktree = test.project_path().join("main");
    assert!(main_worktree.exists());
    test.commit_in(&main_worktree, "Initial");

    // Create feature worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature"])
        .current_dir(&main_worktree);
    cmd.output().unwrap();

    // Feature worktree should be at project/feature
    let feature_worktree = test.project_path().join("feature");
    assert!(
        feature_worktree.exists(),
        "Feature worktree should be at project/feature"
    );

    // List should show both worktrees
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    cmd.arg("list").current_dir(&main_worktree);
    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert!(stdout.contains("main"), "Should list main worktree");
    assert!(stdout.contains("feature"), "Should list feature worktree");

    // Remove feature worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["remove", "feature", "--foreground"])
        .current_dir(&main_worktree);
    cmd.output().unwrap();

    assert!(
        !feature_worktree.exists(),
        "Feature worktree should be removed"
    );
    assert!(main_worktree.exists());
}

#[test]
fn test_nested_bare_repo_list_snapshot() {
    let test = NestedBareRepoTest::new();

    // Create main worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "main"])
        .current_dir(test.bare_repo_path());
    cmd.output().unwrap();

    let main_worktree = test.project_path().join("main");
    test.commit_in(&main_worktree, "Initial");

    // Create feature worktree
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "feature"])
        .current_dir(&main_worktree);
    cmd.output().unwrap();

    // Take snapshot of list output
    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        cmd.arg("list").current_dir(&main_worktree);
        assert_cmd_snapshot!(cmd);
    });
}

#[test]
fn test_bare_repo_bootstrap_first_worktree() {
    // Test that we can create the first worktree in a bare repo using wt switch --create
    // without needing to manually run `git worktree add` first.
    // This tests that load_project_config() returns None for bare repos without worktrees,
    // allowing the bootstrap workflow to proceed.
    let test = BareRepoTest::new();

    // Unlike other tests, we do NOT create any worktrees first.
    // We run wt switch --create directly on the bare repo.

    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "main"])
        .current_dir(test.bare_repo_path());

    let output = cmd.output().unwrap();

    if !output.status.success() {
        panic!(
            "wt switch --create main from bare repo with no worktrees failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    // Verify the worktree was created inside the bare repo
    // Template: {{ branch }} -> repo/main
    let expected_path = test.bare_repo_path().join("main");
    assert!(
        expected_path.exists(),
        "Expected first worktree at {:?}",
        expected_path
    );

    // Verify git worktree list shows the new worktree
    let output = test
        .git_command(test.bare_repo_path())
        .args(["worktree", "list"])
        .run()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Should show 2 entries: bare repo + main worktree
    assert_eq!(
        stdout.lines().count(),
        2,
        "Should have bare repo + 1 worktree"
    );
    assert!(stdout.contains("main"), "Should list main worktree");
}

/// Regression test: `wt list` from a `git clone --bare` repo must not run
/// `git status` on the bare entry. Before the fix, this produced:
///   "fatal: this operation must be run in a work tree"
///
/// Uses `git clone --bare` (real-world pattern) rather than `git init --bare`
/// (used by BareRepoTest) to cover the exact reported scenario.
#[test]
fn test_clone_bare_repo_list_no_status_errors() {
    let temp_dir = tempfile::TempDir::new().unwrap();
    let git_config_path = temp_dir.path().join("test-gitconfig");
    let test_config_path = temp_dir.path().join("test-config.toml");
    fs::write(
        &git_config_path,
        "[user]\n\tname = Test User\n\temail = test@example.com\n\
         [init]\n\tdefaultBranch = main\n",
    )
    .unwrap();
    fs::write(&test_config_path, "").unwrap();

    let run_git = |dir: &Path, args: &[&str]| {
        let output = configure_git_env(Cmd::new("git"), &git_config_path)
            .args(args.iter().copied())
            .current_dir(dir)
            .run()
            .unwrap();
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    };

    // Create a source repo with a commit (clone --bare needs history)
    let source = temp_dir.path().join("source");
    run_git(
        temp_dir.path(),
        &["init", "--initial-branch", "main", source.to_str().unwrap()],
    );
    fs::write(source.join("file.txt"), "content").unwrap();
    run_git(&source, &["add", "file.txt"]);
    run_git(&source, &["commit", "-m", "Initial commit"]);

    // Clone as bare — the exact pattern from the bug report
    let bare_path = temp_dir.path().join("project.bare");
    run_git(
        temp_dir.path(),
        &[
            "clone",
            "--bare",
            source.to_str().unwrap(),
            bare_path.to_str().unwrap(),
        ],
    );

    // Create linked worktrees (outside the bare dir, matching real usage)
    let main_wt = temp_dir.path().join("main");
    let feature_wt = temp_dir.path().join("feature");
    run_git(
        &bare_path,
        &["worktree", "add", main_wt.to_str().unwrap(), "main"],
    );
    run_git(&bare_path, &["branch", "feature", "main"]);
    run_git(
        &bare_path,
        &["worktree", "add", feature_wt.to_str().unwrap(), "feature"],
    );

    // Run wt list from the bare repo directory (the reported scenario)
    let mut cmd = wt_command();
    configure_git_cmd(&mut cmd, &git_config_path);
    cmd.env("WORKTRUNK_CONFIG_PATH", &test_config_path)
        .arg("list")
        .current_dir(&bare_path);
    let output = cmd.output().unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "wt list should succeed.\nstderr: {stderr}"
    );
    assert!(
        !stderr.contains("must be run in a work tree"),
        "Should not get 'must be run in a work tree' error.\nstderr: {stderr}"
    );
    assert!(
        !stderr.contains("git operations failed"),
        "Should not have git operation failures.\nstderr: {stderr}"
    );
}

/// Regression test for #1618: `wt merge` must not remove the default branch
/// worktree in a bare repo. In bare repos all worktrees are linked, so the
/// `is_linked()` check alone can't protect the primary worktree.
#[test]
fn test_bare_repo_merge_preserves_default_branch_worktree() {
    let test = BareRepoTest::new();

    // Create main (default branch) worktree and a feature worktree at the same commit
    let main_worktree = test.create_worktree("main", "main");
    test.commit_in(&main_worktree, "Initial commit on main");

    // Create feature branch at the same commit as main
    let _feature_worktree = test.create_worktree("feature", "feature");

    // Run `wt merge feature` from the main (default branch) worktree.
    // This attempts to merge main into feature — the important thing is that
    // the main worktree must NOT be removed even though is_linked() returns true.
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args([
        "merge",
        "feature",     // Target = feature branch
        "--no-squash", // Skip squash to avoid LLM dependency
        "--no-hooks",  // Skip hooks
    ])
    .current_dir(&main_worktree);

    let output = cmd.output().unwrap();
    let stderr = String::from_utf8_lossy(&output.stderr);

    // The merge itself may succeed or show "already up to date", but the key
    // assertion is that the main worktree is preserved (not removed).
    assert!(
        main_worktree.exists(),
        "Default branch worktree must not be removed.\nstderr: {stderr}"
    );

    // Should show "primary worktree" preservation message
    assert!(
        stderr.contains("primary worktree"),
        "Should show primary worktree preservation message.\nstderr: {stderr}"
    );
}

/// Helper: create a NestedBareRepoTest with no worktree-path configured and a main worktree.
///
/// Reuses NestedBareRepoTest's bare repo setup but clears the worktree-path config,
/// so the default template (which references `{{ repo }}`) triggers the bare repo prompt.
fn setup_unconfigured_nested_bare_repo() -> NestedBareRepoTest {
    let test = NestedBareRepoTest::new();

    // Temporarily set worktree-path so the main worktree lands at project/main
    // (without this, the default {{ repo }} template produces .git.main).
    fs::write(
        test.config_path(),
        "worktree-path = \"../{{ branch | sanitize }}\"\n",
    )
    .unwrap();

    // Create main worktree with a commit (needed as a starting point for switch)
    let (cd_path, exec_path, _guard) = directive_files();
    let mut cmd = wt_command();
    test.configure_wt_cmd(&mut cmd);
    configure_directive_files(&mut cmd, &cd_path, &exec_path);
    cmd.args(["switch", "--create", "main", "--yes"])
        .current_dir(test.bare_repo_path());
    let output = cmd.output().unwrap();
    assert!(
        output.status.success(),
        "Failed to create main worktree:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Clear config so the default template applies — the test subject is the bare repo prompt.
    // Skip shell integration prompt so it doesn't interfere (especially in PTY tests).
    fs::write(test.config_path(), "skip-shell-integration-prompt = true\n").unwrap();

    test
}

/// Test that --yes does NOT auto-accept the bare repo config change — it shows
/// the warning and creates the worktree at the unconfigured (bad) path.
#[test]
fn test_bare_repo_worktree_path_prompt_auto_accept() {
    let test = setup_unconfigured_nested_bare_repo();
    let main_worktree = test.project_path().join("main");

    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let (cd_path, exec_path, _guard) = directive_files();
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        configure_directive_files(&mut cmd, &cd_path, &exec_path);
        cmd.args(["switch", "--create", "feature", "--yes"])
            .current_dir(&main_worktree);

        assert_cmd_snapshot!(cmd);
    });

    // Config should NOT have worktree-path — --yes skips the config prompt
    let config_content = fs::read_to_string(test.config_path()).unwrap();
    assert!(
        !config_content.contains("worktree-path"),
        "Config should NOT contain worktree-path — --yes should not auto-configure.\nConfig: {config_content}"
    );

    // Worktree created at the unconfigured path (bad but expected without config)
    let bad_path = test.project_path().join(".git.feature");
    assert!(
        bad_path.exists(),
        "Worktree should be at {:?} (unconfigured default path)",
        bad_path
    );
}

/// Test that non-interactive (piped stdin) shows warning instead of prompt.
#[test]
fn test_bare_repo_worktree_path_prompt_non_interactive_warning() {
    let test = setup_unconfigured_nested_bare_repo();
    let main_worktree = test.project_path().join("main");

    let settings = setup_temp_snapshot_settings(test.temp_path());
    settings.bind(|| {
        let (cd_path, exec_path, _guard) = directive_files();
        let mut cmd = wt_command();
        test.configure_wt_cmd(&mut cmd);
        configure_directive_files(&mut cmd, &cd_path, &exec_path);
        // No --yes, but stdin is piped (non-interactive) since assert_cmd_snapshot
        // doesn't attach a TTY
        cmd.args(["switch", "--create", "feature"])
            .current_dir(&main_worktree);

        assert_cmd_snapshot!(cmd);
    });
}

// =============================================================================
// PTY-based interactive prompt tests
// =============================================================================

#[cfg(all(unix, feature = "shell-integration-tests"))]
mod bare_repo_prompt_pty {
    use super::*;
    use crate::common::pty::{build_pty_command, exec_cmd_in_pty_prompted};
    use crate::common::{add_pty_binary_path_filters, add_pty_filters, wt_bin};
    use insta::assert_snapshot;

    fn prompt_pty_settings(temp_path: &Path) -> insta::Settings {
        let mut settings = setup_temp_snapshot_settings(temp_path);
        add_pty_filters(&mut settings);
        add_pty_binary_path_filters(&mut settings);
        settings
    }

    #[test]
    fn test_bare_repo_worktree_path_prompt_accept_pty() {
        let test = setup_unconfigured_nested_bare_repo();
        let main_worktree = test.project_path().join("main");
        let env_vars = test.test_env_vars();

        let cmd = build_pty_command(
            wt_bin().to_str().unwrap(),
            &["switch", "--create", "feature"],
            &main_worktree,
            &env_vars,
            None,
        );
        let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["y\n"], "[y/N");

        assert_eq!(exit_code, 0);
        prompt_pty_settings(test.temp_path()).bind(|| {
            assert_snapshot!("bare_repo_prompt_accept", &output);
        });

        // Verify config was written
        let config_content = fs::read_to_string(test.config_path()).unwrap();
        assert!(
            config_content.contains("worktree-path"),
            "Config should contain worktree-path override.\nConfig: {config_content}"
        );
    }

    #[test]
    fn test_bare_repo_worktree_path_prompt_decline_pty() {
        let test = setup_unconfigured_nested_bare_repo();
        let main_worktree = test.project_path().join("main");
        let env_vars = test.test_env_vars();

        let cmd = build_pty_command(
            wt_bin().to_str().unwrap(),
            &["switch", "--create", "feature"],
            &main_worktree,
            &env_vars,
            None,
        );
        let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["n\n"], "[y/N");

        assert_eq!(exit_code, 0);
        prompt_pty_settings(test.temp_path()).bind(|| {
            assert_snapshot!("bare_repo_prompt_decline", &output);
        });

        // Verify skip flag was saved in git config
        let git_config_output = Cmd::new("git")
            .args(["config", "worktrunk.skip-bare-repo-prompt"])
            .current_dir(&main_worktree)
            .env("GIT_CONFIG_GLOBAL", test.git_config_path())
            .run()
            .unwrap();
        let value = String::from_utf8_lossy(&git_config_output.stdout);
        assert_eq!(
            value.trim(),
            "true",
            "Skip flag should be saved in git config"
        );
    }

    #[test]
    fn test_bare_repo_worktree_path_prompt_preview_pty() {
        let test = setup_unconfigured_nested_bare_repo();
        let main_worktree = test.project_path().join("main");
        let env_vars = test.test_env_vars();

        let cmd = build_pty_command(
            wt_bin().to_str().unwrap(),
            &["switch", "--create", "feature"],
            &main_worktree,
            &env_vars,
            None,
        );
        // Send ? first to see preview, then n to decline
        let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["?\n", "n\n"], "[y/N");

        assert_eq!(exit_code, 0);
        prompt_pty_settings(test.temp_path()).bind(|| {
            assert_snapshot!("bare_repo_prompt_preview", &output);
        });
    }
}