worktrunk 0.43.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
use crate::common::{
    TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,
    resolve_git_common_dir, set_temp_home_env, setup_snapshot_settings, wait_for_file,
    wait_for_file_content, wait_for_file_count, wait_for_file_lines, wait_for_valid_json,
};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
use std::thread;
use std::time::Duration; // Used for SLEEP_FOR_ABSENCE_CHECK
use tempfile::TempDir;

/// Wait duration when checking file absence (testing command did NOT run).
/// Must be long enough that a background command would have started and created
/// the file if it were going to. 500ms gives CI systems breathing room.
const SLEEP_FOR_ABSENCE_CHECK: Duration = Duration::from_millis(500);

/// Helper to create snapshot with normalized paths and SHAs
///
/// Tests should write to repo.test_config_path() to pre-approve commands.
/// Uses an isolated HOME to prevent tests from being affected by developer's shell config.
fn snapshot_switch(test_name: &str, repo: &TestRepo, args: &[&str]) {
    // Create isolated HOME to ensure test determinism
    let temp_home = TempDir::new().unwrap();

    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "switch", args, None);
        set_temp_home_env(&mut cmd, temp_home.path());
        assert_cmd_snapshot!(test_name, cmd);
    });
}

// ============================================================================
// Post-Create Command Tests (sequential, blocking)
// ============================================================================

#[rstest]
fn test_post_create_no_config(repo: TestRepo) {
    // Switch without project config should work normally
    snapshot_switch("post_create_no_config", &repo, &["--create", "feature"]);
}

#[rstest]
fn test_post_create_single_command(repo: TestRepo) {
    // Create project config with a single command (string format)
    repo.write_project_config(r#"post-create = "echo 'Setup complete'""#);

    repo.commit("Add config");

    // Pre-approve the command by writing to the isolated test config
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'Setup complete'"]
"#,
    );

    // Command should execute without prompting
    snapshot_switch(
        "post_create_single_command",
        &repo,
        &["--create", "feature"],
    );
}

#[rstest]
fn test_post_create_named_commands(repo: TestRepo) {
    // Create project config with named commands (table format)
    repo.write_project_config(
        r#"[post-create]
install = "echo 'Installing deps'"
setup = "echo 'Running setup'"
"#,
    );

    repo.commit("Add config with named commands");

    // Pre-approve both commands in temp HOME
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Installing deps'",
    "echo 'Running setup'",
]
"#,
    );

    // Commands should execute sequentially
    snapshot_switch(
        "post_create_named_commands",
        &repo,
        &["--create", "feature"],
    );
}

#[rstest]
fn test_post_create_failing_command(repo: TestRepo) {
    // Create project config with a command that will fail
    repo.write_project_config(r#"post-create = "exit 1""#);

    repo.commit("Add config with failing command");

    // Pre-approve the command in temp HOME
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["exit 1"]
"#,
    );

    // Failing pre-start hook (via deprecated post-create name) aborts with FailFast
    snapshot_switch(
        "post_create_failing_command",
        &repo,
        &["--create", "feature"],
    );
}

#[rstest]
fn test_post_create_template_expansion(repo: TestRepo) {
    // Create project config with template variables
    repo.write_project_config(
        r#"[post-create]
repo = "echo 'Repo: {{ repo }}' > info.txt"
branch = "echo 'Branch: {{ branch }}' >> info.txt"
hash_port = "echo 'Port: {{ branch | hash_port }}' >> info.txt"
worktree = "echo 'Worktree: {{ worktree_path }}' >> info.txt"
root = "echo 'Root: {{ repo_path }}' >> info.txt"
"#,
    );

    repo.commit("Add config with templates");

    // Pre-approve all commands in isolated test config
    let repo_name = "repo";
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}""#);
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Repo: {{ repo }}' > info.txt",
    "echo 'Branch: {{ branch }}' >> info.txt",
    "echo 'Port: {{ branch | hash_port }}' >> info.txt",
    "echo 'Worktree: {{ worktree_path }}' >> info.txt",
    "echo 'Root: {{ repo_path }}' >> info.txt",
]
"#,
    );

    // Commands should execute with expanded templates
    snapshot_switch(
        "post_create_template_expansion",
        &repo,
        &["--create", "feature/test"],
    );

    // Verify template expansion actually worked by checking the output file
    let worktree_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join(format!("{}.feature-test", repo_name));
    let info_file = worktree_path.join("info.txt");

    assert!(
        info_file.exists(),
        "info.txt should have been created in the worktree"
    );

    let contents = fs::read_to_string(&info_file).unwrap();

    // Verify that template variables were actually expanded
    assert!(
        contents.contains(&format!("Repo: {}", repo_name)),
        "Should contain expanded repo name, got: {}",
        contents
    );
    assert!(
        contents.contains("Branch: feature/test"),
        "Should contain raw branch name, got: {}",
        contents
    );

    // Verify port is a valid number in the expected range (10000-19999)
    let port_line = contents
        .lines()
        .find(|l| l.starts_with("Port: "))
        .expect("Should contain port line");
    let port: u16 = port_line
        .strip_prefix("Port: ")
        .unwrap()
        .parse()
        .expect("Port should be a valid number");
    assert!(
        (10000..20000).contains(&port),
        "Port should be in range 10000-19999, got: {}",
        port
    );
}

#[rstest]
fn test_post_create_verbose_template_expansion(repo: TestRepo) {
    // Test that -v shows template expansion for post-create hooks
    repo.write_project_config(
        r#"[post-create]
setup = "echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'"
"#,
    );

    repo.commit("Add config with templates");

    // Pre-approve commands
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch | sanitize }}""#);
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Setting up {{ branch | sanitize }} in {{ worktree_path }}'",
]
"#,
    );

    // Create isolated HOME to ensure test determinism
    let temp_home = tempfile::TempDir::new().unwrap();

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd_with_global_flags(
            &repo,
            "switch",
            &["--create", "verbose-hooks"],
            None,
            &["-v"],
        );
        set_temp_home_env(&mut cmd, temp_home.path());
        assert_cmd_snapshot!("post_create_verbose_template_expansion", cmd);
    });
}

#[rstest]
fn test_post_create_default_branch_template(repo: TestRepo) {
    // Create project config with default_branch template variable
    repo.write_project_config(
        r#"post-create = "echo 'Default: {{ default_branch }}' > default.txt""#,
    );

    repo.commit("Add config with default_branch template");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'Default: {{ default_branch }}' > default.txt"]
"#,
    );

    // Create a feature branch worktree (--yes skips approval prompt)
    snapshot_switch(
        "post_create_default_branch_template",
        &repo,
        &["--create", "feature", "--yes"],
    );

    // Verify template expansion actually worked
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let default_file = worktree_path.join("default.txt");

    assert!(
        default_file.exists(),
        "default.txt should have been created in the worktree"
    );

    let contents = fs::read_to_string(&default_file).unwrap();
    assert!(
        contents.contains("Default: main"),
        "Should contain expanded default_branch, got: {}",
        contents
    );
}

#[rstest]
fn test_post_create_git_variables_template(#[from(repo_with_remote)] repo: TestRepo) {
    // Set up an upstream tracking branch
    repo.git_command()
        .args(["push", "-u", "origin", "main"])
        .run()
        .expect("failed to push");

    // Create project config with git-related template variables
    repo.write_project_config(
        r#"[post-create]
commit = "echo 'Commit: {{ commit }}' > git_vars.txt"
short = "echo 'Short: {{ short_commit }}' >> git_vars.txt"
remote = "echo 'Remote: {{ remote }}' >> git_vars.txt"
worktree_name = "echo 'Worktree Name: {{ worktree_name }}' >> git_vars.txt"
"#,
    );

    repo.commit("Add config with git template variables");

    // Create a feature branch worktree (--yes skips approval prompt)
    snapshot_switch(
        "post_create_git_variables_template",
        &repo,
        &["--create", "feature", "--yes"],
    );

    // Verify template expansion actually worked
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let vars_file = worktree_path.join("git_vars.txt");

    assert!(
        vars_file.exists(),
        "git_vars.txt should have been created in the worktree"
    );

    let contents = fs::read_to_string(&vars_file).unwrap();

    // Verify commit variable (should be 40 char hex)
    assert!(
        contents.contains("Commit: ")
            && contents.lines().any(|l| {
                l.starts_with("Commit: ") && l.len() == 48 // "Commit: " (8) + 40 hex chars
            }),
        "Should contain expanded commit SHA, got: {}",
        contents
    );

    // Verify short_commit variable (should be 7 char hex)
    assert!(
        contents.contains("Short: ")
            && contents.lines().any(|l| {
                l.starts_with("Short: ") && l.len() == 14 // "Short: " (7) + 7 hex chars
            }),
        "Should contain expanded short_commit SHA, got: {}",
        contents
    );

    // Verify remote variable
    assert!(
        contents.contains("Remote: origin"),
        "Should contain expanded remote name, got: {}",
        contents
    );

    // Verify worktree_name variable (basename of worktree path)
    assert!(
        contents.contains("Worktree Name: repo.feature"),
        "Should contain expanded worktree_name, got: {}",
        contents
    );
}

#[rstest]
fn test_post_create_upstream_template(#[from(repo_with_remote)] repo: TestRepo) {
    // Push main to set up tracking
    repo.git_command()
        .args(["push", "-u", "origin", "main"])
        .run()
        .expect("failed to push main");

    // Create project config with upstream template variable
    // Note: {{ upstream }} errors when the new branch has no upstream tracking.
    // The new feature branch won't have an upstream until it's pushed with -u.
    // This test verifies the error case - see test_post_create_upstream_conditional for the fix.
    repo.write_project_config(r#"post-create = "echo 'Upstream: {{ upstream }}' > upstream.txt""#);

    repo.commit("Add config with upstream template");

    // Create a feature branch - it won't have upstream tracking configured yet
    snapshot_switch(
        "post_create_upstream_template",
        &repo,
        &["--create", "feature", "--yes"],
    );

    // Hook command should have errored due to undefined `upstream` variable
    // (new branches don't have upstream tracking until pushed with -u)
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let upstream_file = worktree_path.join("upstream.txt");

    assert!(
        !upstream_file.exists(),
        "upstream.txt should NOT have been created (command errored)"
    );
}

#[rstest]
fn test_post_create_upstream_conditional(#[from(repo_with_remote)] repo: TestRepo) {
    // Push main to set up tracking
    repo.git_command()
        .args(["push", "-u", "origin", "main"])
        .run()
        .expect("failed to push main");

    // Create project config with conditional upstream check
    // Using {% if not upstream %} allows safe handling of undefined variables
    repo.write_project_config(
        r#"post-create = "{% if not upstream %}echo 'no-upstream' > upstream.txt{% else %}echo '{{ upstream }}' > upstream.txt{% endif %}""#,
    );

    repo.commit("Add config with conditional upstream");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["{% if not upstream %}echo 'no-upstream' > upstream.txt{% else %}echo '{{ upstream }}' > upstream.txt{% endif %}"]
"#,
    );

    // Create a feature branch - it won't have upstream tracking configured yet
    snapshot_switch(
        "post_create_upstream_conditional",
        &repo,
        &["--create", "feature", "--yes"],
    );

    // Verify the conditional worked - new branch has no upstream, so "no-upstream" should be written
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let upstream_file = worktree_path.join("upstream.txt");

    assert!(
        upstream_file.exists(),
        "upstream.txt should have been created (conditional worked)"
    );

    let contents = fs::read_to_string(&upstream_file).unwrap();
    assert_eq!(
        contents.trim(),
        "no-upstream",
        "Should contain 'no-upstream' since feature branch has no upstream tracking"
    );
}

#[rstest]
fn test_post_create_base_variables(repo: TestRepo) {
    // Create project config with base template variables
    repo.write_project_config(
        r#"[post-create]
base = "echo 'Base: {{ base }}' > base_info.txt"
base_path = "echo 'Base Path: {{ base_worktree_path }}' >> base_info.txt"
"#,
    );

    repo.commit("Add config with base template variables");

    // Pre-approve the commands
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Base: {{ base }}' > base_info.txt",
    "echo 'Base Path: {{ base_worktree_path }}' >> base_info.txt",
]
"#,
    );

    // Create a feature branch worktree from main
    snapshot_switch(
        "post_create_base_variables",
        &repo,
        &["--create", "feature", "--base", "main"],
    );

    // Verify template expansion actually worked
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let base_file = worktree_path.join("base_info.txt");

    assert!(
        base_file.exists(),
        "base_info.txt should have been created in the worktree"
    );

    let contents = fs::read_to_string(&base_file).unwrap();

    // Verify base variable (branch name we branched from)
    assert!(
        contents.contains("Base: main"),
        "Should contain expanded base branch, got: {}",
        contents
    );

    // Verify base_worktree_path variable (path to main worktree)
    // The path should contain the repo root (main worktree is at repo root)
    assert!(
        contents.contains("Base Path: "),
        "Should have base_worktree_path line, got: {}",
        contents
    );

    // The base_worktree_path should be the main worktree's path (POSIX format)
    let base_path_line = contents
        .lines()
        .find(|l| l.starts_with("Base Path: "))
        .expect("Should have Base Path line");
    let base_path = base_path_line.strip_prefix("Base Path: ").unwrap();

    // Convert expected path to POSIX format for comparison
    let expected_base_path = worktrunk::path::to_posix_path(&repo.root_path().to_string_lossy());
    assert_eq!(
        base_path, expected_base_path,
        "Base path should match main worktree path"
    );
}

#[rstest]
fn test_post_create_json_stdin(repo: TestRepo) {
    use crate::common::wt_command;

    // Create project config with a command that reads JSON from stdin
    // Use cat to capture stdin to a file
    repo.write_project_config(r#"post-create = "cat > context.json""#);

    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["cat > context.json"]
"#,
    );

    // Create worktree - this should pipe JSON to the hook's stdin
    let temp_home = TempDir::new().unwrap();
    let mut cmd = wt_command();
    cmd.args(["switch", "--create", "feature-json"])
        .current_dir(repo.root_path())
        .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
        .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
    set_temp_home_env(&mut cmd, temp_home.path());
    let output = cmd.output().expect("failed to run wt switch");

    assert!(
        output.status.success(),
        "wt switch should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Find the worktree and read the JSON
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature-json");
    let json_file = worktree_path.join("context.json");

    assert!(
        json_file.exists(),
        "context.json should have been created from stdin"
    );

    let contents = fs::read_to_string(&json_file).unwrap();

    // Parse and verify the JSON contains expected fields
    let json: serde_json::Value = serde_json::from_str(&contents)
        .unwrap_or_else(|e| panic!("Should be valid JSON: {}\nContents: {}", e, contents));

    assert!(
        json.get("repo").is_some(),
        "JSON should contain 'repo' field"
    );
    assert!(
        json.get("branch").is_some(),
        "JSON should contain 'branch' field"
    );
    assert_eq!(
        json["branch"].as_str(),
        Some("feature-json"),
        "Branch should be sanitized (feature-json)"
    );
    assert!(
        json.get("worktree").is_some(),
        "JSON should contain 'worktree' field"
    );
    assert!(
        json.get("repo_root").is_some(),
        "JSON should contain 'repo_root' field"
    );
    assert_eq!(
        json["hook_type"].as_str(),
        Some("pre-start"),
        "JSON should contain hook_type"
    );
}

#[rstest]
#[cfg(unix)]
fn test_post_create_script_reads_json(repo: TestRepo) {
    use crate::common::wt_command;
    use std::os::unix::fs::PermissionsExt;

    // Create a scripts directory and a Python script that reads JSON from stdin
    let scripts_dir = repo.root_path().join("scripts");
    fs::create_dir_all(&scripts_dir).unwrap();

    let script_content = r#"#!/usr/bin/env python3
import json
import sys

ctx = json.load(sys.stdin)
with open('hook_output.txt', 'w') as f:
    f.write(f"repo={ctx['repo']}\n")
    f.write(f"branch={ctx['branch']}\n")
    f.write(f"hook_type={ctx['hook_type']}\n")
    f.write(f"hook_name={ctx.get('hook_name', 'unnamed')}\n")
"#;
    let script_path = scripts_dir.join("setup.py");
    fs::write(&script_path, script_content).unwrap();
    fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755)).unwrap();

    // Create project config that runs the script
    repo.write_project_config(
        r#"[post-create]
setup = "./scripts/setup.py"
"#,
    );

    repo.commit("Add setup script and config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["./scripts/setup.py"]
"#,
    );

    // Create worktree
    let temp_home = TempDir::new().unwrap();
    let mut cmd = wt_command();
    cmd.args(["switch", "--create", "feature-script"])
        .current_dir(repo.root_path())
        .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
        .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
    set_temp_home_env(&mut cmd, temp_home.path());
    let output = cmd.output().expect("failed to run wt switch");

    assert!(
        output.status.success(),
        "wt switch should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Find the worktree and verify the script wrote the expected output
    let worktree_path = repo
        .root_path()
        .parent()
        .unwrap()
        .join("repo.feature-script");
    let output_file = worktree_path.join("hook_output.txt");

    assert!(
        output_file.exists(),
        "Script should have created hook_output.txt"
    );

    let contents = fs::read_to_string(&output_file).unwrap();
    assert!(
        contents.contains("repo=repo"),
        "Output should contain repo name: {}",
        contents
    );
    assert!(
        contents.contains("branch=feature-script"),
        "Output should contain branch: {}",
        contents
    );
    assert!(
        contents.contains("hook_type=pre-start"),
        "Output should contain hook_type: {}",
        contents
    );
    assert!(
        contents.contains("hook_name=setup"),
        "Output should contain hook_name: {}",
        contents
    );
}

#[rstest]
fn test_post_start_json_stdin(repo: TestRepo) {
    use crate::common::wt_command;

    // Create project config with a background command that reads JSON from stdin
    repo.write_project_config(r#"post-start = "cat > context.json""#);

    repo.commit("Add config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["cat > context.json"]
"#,
    );

    // Create worktree
    let temp_home = TempDir::new().unwrap();
    let mut cmd = wt_command();
    cmd.args(["switch", "--create", "bg-json"])
        .current_dir(repo.root_path())
        .env("WORKTRUNK_CONFIG_PATH", repo.test_config_path())
        .env("WORKTRUNK_APPROVALS_PATH", repo.test_approvals_path());
    set_temp_home_env(&mut cmd, temp_home.path());
    let output = cmd.output().expect("failed to run wt switch");

    assert!(
        output.status.success(),
        "wt switch should succeed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Find the worktree and wait for valid JSON (polls until cat finishes writing)
    let worktree_path = repo.root_path().parent().unwrap().join("repo.bg-json");
    let json_file = worktree_path.join("context.json");
    let json = wait_for_valid_json(&json_file);

    assert_eq!(
        json["branch"].as_str(),
        Some("bg-json"),
        "Background hook should receive JSON with branch"
    );
    assert!(
        json.get("repo").is_some(),
        "Background hook should receive JSON with repo"
    );
    assert_eq!(
        json["hook_type"].as_str(),
        Some("post-start"),
        "Background hook should receive hook_type"
    );
}

// ============================================================================
// Post-Start Command Tests (parallel, background)
// ============================================================================

#[rstest]
fn test_post_start_single_background_command(repo: TestRepo) {
    // Create project config with a background command
    repo.write_project_config(
        r#"post-start = "sleep 0.1 && echo 'Background task done' > background.txt""#,
    );

    repo.commit("Add background command");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["sleep 0.1 && echo 'Background task done' > background.txt"]
"#,
    );

    // Command should spawn in background (wt exits immediately)
    snapshot_switch(
        "post_start_single_background",
        &repo,
        &["--create", "feature"],
    );

    // Verify log file was created in the common git directory
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let git_common_dir = resolve_git_common_dir(&worktree_path);
    let log_dir = git_common_dir.join("wt/logs");
    assert!(log_dir.exists());

    // Wait for the background command to complete
    let output_file = worktree_path.join("background.txt");
    wait_for_file(output_file.as_path());
}

/// Test that -v shows verbose per-hook output for background hooks
#[rstest]
fn test_post_start_verbose_shows_per_hook_output(repo: TestRepo) {
    // Create project config with a background command
    repo.write_project_config(
        r#"[post-start]
setup = "echo 'verbose test' > verbose.txt"
"#,
    );

    repo.commit("Add background command");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'verbose test' > verbose.txt"]
"#,
    );

    // With -v, should show detailed per-hook output with command in gutter
    snapshot_switch(
        "post_start_verbose_output",
        &repo,
        &["-v", "--create", "feature"],
    );
}

#[rstest]
fn test_post_start_multiple_background_commands(repo: TestRepo) {
    // Create project config with multiple background commands (table format)
    repo.write_project_config(
        r#"[post-start]
task1 = "echo 'Task 1 running' > task1.txt"
task2 = "echo 'Task 2 running' > task2.txt"
"#,
    );

    repo.commit("Add multiple background commands");

    // Pre-approve both commands
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Task 1 running' > task1.txt",
    "echo 'Task 2 running' > task2.txt",
]
"#,
    );

    // Commands should spawn in parallel
    snapshot_switch(
        "post_start_multiple_background",
        &repo,
        &["--create", "feature"],
    );

    // Wait for both background commands
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    wait_for_file(worktree_path.join("task1.txt").as_path());
    wait_for_file(worktree_path.join("task2.txt").as_path());
}

#[rstest]
fn test_both_post_create_and_post_start(repo: TestRepo) {
    // Create project config with both command types
    repo.write_project_config(
        r#"post-create = "echo 'Setup done' > setup.txt"

[post-start]
server = "sleep 0.05 && echo 'Server running' > server.txt"
"#,
    );

    repo.commit("Add both command types");

    // Pre-approve all commands
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'Setup done' > setup.txt",
    "sleep 0.05 && echo 'Server running' > server.txt",
]
"#,
    );

    // Post-create should run first (blocking), then post-start (background)
    snapshot_switch("both_create_and_start", &repo, &["--create", "feature"]);

    // Setup file should exist immediately (post-create is blocking)
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    assert!(
        worktree_path.join("setup.txt").exists(),
        "Post-create command should have completed before wt exits"
    );

    // Wait for background command
    wait_for_file(worktree_path.join("server.txt").as_path());
}

#[rstest]
fn test_invalid_toml(repo: TestRepo) {
    // Create invalid TOML
    repo.write_project_config("post-create = [invalid syntax\n");

    repo.commit("Add invalid config");

    // Should continue without executing commands, showing warning
    snapshot_switch("invalid_toml", &repo, &["--create", "feature"]);
}

// ============================================================================
// Additional Coverage Tests
// ============================================================================

#[rstest]
fn test_post_start_log_file_captures_output(repo: TestRepo) {
    // Create command that writes to both stdout and stderr
    repo.write_project_config(r#"post-start = "echo 'stdout output' && echo 'stderr output' >&2""#);

    repo.commit("Add command with stdout/stderr");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'stdout output' && echo 'stderr output' >&2"]
"#,
    );

    snapshot_switch(
        "post_start_log_captures_output",
        &repo,
        &["--create", "feature"],
    );

    // Wait for log file to be created (not just the directory)
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let git_common_dir = resolve_git_common_dir(&worktree_path);
    let log_dir = git_common_dir.join("wt/logs");
    // 2 log files: runner log + per-command log (cmd-0, unnamed single command)
    wait_for_file_count(&log_dir, "log", 2);

    // Find the command log file at `{branch}/project/post-start/cmd-0-*.log`.
    let post_start_dir = log_dir
        .join(worktrunk::path::sanitize_for_filename("feature"))
        .join("project")
        .join("post-start");
    let cmd_log = fs::read_dir(&post_start_dir)
        .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .find(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.starts_with("cmd-0"))
        })
        .expect("Should have a cmd-0 log file");

    // Wait for both lines — `&&` sequences two writes (stdout, then stderr),
    // so file size > 0 can hit after only the first landed.
    wait_for_file_lines(&cmd_log, 2);

    let log_contents = fs::read_to_string(&cmd_log).unwrap();

    // Verify both stdout and stderr were captured
    assert_snapshot!(log_contents, @"
    stdout output
    stderr output
    ");
}

#[rstest]
fn test_post_start_invalid_command_handling(repo: TestRepo) {
    // Create command with syntax error (missing quote)
    repo.write_project_config(r#"post-start = "echo 'unclosed quote""#);

    repo.commit("Add invalid command");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'unclosed quote"]
"#,
    );

    // wt should still complete successfully even if background command has errors
    snapshot_switch(
        "post_start_invalid_command",
        &repo,
        &["--create", "feature"],
    );

    // Verify worktree was created despite command error
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    assert!(
        worktree_path.exists(),
        "Worktree should be created even if post-start command fails"
    );
}

#[rstest]
fn test_post_start_multiple_commands_separate_logs(repo: TestRepo) {
    // Create multiple background commands with distinct output
    repo.write_project_config(
        r#"[post-start]
task1 = "echo 'TASK1_OUTPUT'"
task2 = "echo 'TASK2_OUTPUT'"
task3 = "echo 'TASK3_OUTPUT'"
"#,
    );

    repo.commit("Add three background commands");

    // Pre-approve all commands
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo 'TASK1_OUTPUT'",
    "echo 'TASK2_OUTPUT'",
    "echo 'TASK3_OUTPUT'",
]
"#,
    );

    snapshot_switch("post_start_separate_logs", &repo, &["--create", "feature"]);

    // Each command gets its own log file (task1, task2, task3) plus one runner log.
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let git_common_dir = resolve_git_common_dir(&worktree_path);
    let log_dir = git_common_dir.join("wt/logs");
    wait_for_file_count(&log_dir, "log", 4);

    // Verify each task's output is in its own log file. Hook logs live at
    // `{branch}/project/post-start/{task}.log` in the nested layout.
    let post_start_dir = log_dir
        .join(worktrunk::path::sanitize_for_filename("feature"))
        .join("project")
        .join("post-start");
    let log_files: Vec<_> = fs::read_dir(&post_start_dir)
        .unwrap_or_else(|e| panic!("reading {post_start_dir:?}: {e}"))
        .filter_map(|e| e.ok())
        .collect();
    for (task, expected) in [
        ("task1", "TASK1_OUTPUT"),
        ("task2", "TASK2_OUTPUT"),
        ("task3", "TASK3_OUTPUT"),
    ] {
        let log_file = log_files
            .iter()
            .find(|e| e.file_name().to_string_lossy().starts_with(task))
            .unwrap_or_else(|| panic!("should have log file for {task} in {post_start_dir:?}"));

        wait_for_file_content(&log_file.path());
        let contents = fs::read_to_string(log_file.path()).unwrap();
        assert!(
            contents.contains(expected),
            "Log for {task} should contain {expected}, got: {contents}"
        );
    }
}

#[rstest]
fn test_execute_flag_with_post_start_commands(repo: TestRepo) {
    // Create post-start command
    repo.write_project_config(r#"post-start = "echo 'Background task' > background.txt""#);

    repo.commit("Add background command");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'Background task' > background.txt"]
"#,
    );

    // Use --execute flag along with post-start command
    snapshot_switch(
        "execute_with_post_start",
        &repo,
        &[
            "--create",
            "feature",
            "--execute",
            "echo 'Execute flag' > execute.txt",
        ],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // Execute flag file should exist immediately (synchronous)
    assert!(
        worktree_path.join("execute.txt").exists(),
        "Execute command should run synchronously"
    );

    // Wait for background command to complete
    wait_for_file(worktree_path.join("background.txt").as_path());
}

#[rstest]
fn test_post_start_complex_shell_commands(repo: TestRepo) {
    // Create command with pipes and redirects
    repo.write_project_config(
        r#"post-start = "echo 'line1\nline2\nline3' | grep line2 > filtered.txt""#,
    );

    repo.commit("Add complex shell command");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'line1\nline2\nline3' | grep line2 > filtered.txt"]
"#,
    );

    snapshot_switch("post_start_complex_shell", &repo, &["--create", "feature"]);

    // Wait for background command to create the file AND flush content
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let filtered_file = worktree_path.join("filtered.txt");
    wait_for_file_content(filtered_file.as_path());

    let contents = fs::read_to_string(&filtered_file).unwrap();
    assert_snapshot!(contents, @"line2");
}

#[rstest]
fn test_post_start_multiline_commands_with_newlines(repo: TestRepo) {
    // Create command with actual newlines (using TOML triple-quoted string)
    repo.write_project_config(
        r#"post-start = """
echo 'first line' > multiline.txt
echo 'second line' >> multiline.txt
echo 'third line' >> multiline.txt
"""
"#,
    );

    repo.commit("Add multiline command with actual newlines");

    // Pre-approve the command
    let multiline_cmd = "echo 'first line' > multiline.txt
echo 'second line' >> multiline.txt
echo 'third line' >> multiline.txt
";
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["""
{}"""]
"#,
        multiline_cmd
    ));

    snapshot_switch(
        "post_start_multiline_with_newlines",
        &repo,
        &["--create", "feature"],
    );

    // Wait for background command to write all 3 lines (not just the first)
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let output_file = worktree_path.join("multiline.txt");
    wait_for_file_lines(output_file.as_path(), 3);

    let contents = fs::read_to_string(&output_file).unwrap();
    assert_snapshot!(contents, @"
    first line
    second line
    third line
    ");
}

#[rstest]
fn test_post_create_multiline_with_control_structures(repo: TestRepo) {
    // Test multiline command with if-else control structure
    repo.write_project_config(
        r#"post-create = """
if [ ! -f test.txt ]; then
  echo 'File does not exist' > result.txt
else
  echo 'File exists' > result.txt
fi
"""
"#,
    );

    repo.commit("Add multiline control structure");

    // Pre-approve the command
    let multiline_cmd = "if [ ! -f test.txt ]; then
  echo 'File does not exist' > result.txt
else
  echo 'File exists' > result.txt
fi
";
    repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);
    repo.write_test_approvals(&format!(
        r#"[projects."../origin"]
approved-commands = ["""
{}"""]
"#,
        multiline_cmd
    ));

    snapshot_switch(
        "post_create_multiline_control_structure",
        &repo,
        &["--create", "feature"],
    );

    // Verify the command executed correctly
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let result_file = worktree_path.join("result.txt");
    assert!(
        result_file.exists(),
        "Control structure command should create result file"
    );

    let contents = fs::read_to_string(&result_file).unwrap();
    assert_snapshot!(contents, @"File does not exist");
}

// ============================================================================
// Regression Tests
// ============================================================================

///
/// This is a regression test for a bug where post-start commands were running on ALL
/// `wt switch` operations instead of only on `wt switch --create`.
#[rstest]
fn test_post_start_skipped_on_existing_worktree(repo: TestRepo) {
    // Create project config with post-start command
    repo.write_project_config(r#"post-start = "echo 'POST-START-RAN' > post_start_marker.txt""#);

    repo.commit("Add post-start config");

    // Pre-approve the command
    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo 'POST-START-RAN' > post_start_marker.txt"]
"#,
    );

    // First: Create worktree - post-start SHOULD run
    snapshot_switch(
        "post_start_create_with_command",
        &repo,
        &["--create", "feature"],
    );

    // Wait for background post-start command to complete
    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker_file = worktree_path.join("post_start_marker.txt");
    wait_for_file(marker_file.as_path());

    // Remove the marker file to detect if post-start runs again
    fs::remove_file(&marker_file).unwrap();

    // Second: Switch to EXISTING worktree - post-start should NOT run
    snapshot_switch("post_start_skip_existing", &repo, &["feature"]);

    // Wait to ensure no background command starts (testing absence requires fixed wait)
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);

    // Verify post-start did NOT run when switching to existing worktree
    assert!(
        !marker_file.exists(),
        "Post-start should NOT run when switching to existing worktree"
    );
}

// ============================================================================
// Pipeline Tests (project config, list form)
// ============================================================================

#[rstest]
fn test_post_start_project_pipeline(repo: TestRepo) {
    // Project config with pipeline: serial setup, then concurrent tasks
    repo.write_project_config(
        r#"post-start = [
    "echo SETUP > setup_marker.txt",
    { task1 = "cat setup_marker.txt > task1_saw_setup.txt", task2 = "echo TASK2 > task2.txt" }
]
"#,
    );
    repo.commit("Add pipeline config");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo SETUP > setup_marker.txt",
    "cat setup_marker.txt > task1_saw_setup.txt",
    "echo TASK2 > task2.txt",
]
"#,
    );

    snapshot_switch(
        "post_start_project_pipeline",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    // task1 reads the setup marker — verifies serial-before-concurrent ordering
    let task1_file = worktree_path.join("task1_saw_setup.txt");
    wait_for_file_content(&task1_file);

    let content = fs::read_to_string(&task1_file).unwrap();
    assert!(
        content.contains("SETUP"),
        "Concurrent task should see serial step's output, got: {content}"
    );
}

#[rstest]
fn test_post_start_pipeline_with_template_vars(repo: TestRepo) {
    // Pipeline with template variable expansion
    repo.write_project_config(
        r#"post-start = [
    "echo {{ branch }} > branch_marker.txt",
    { check = "cat branch_marker.txt > branch_check.txt" }
]
"#,
    );
    repo.commit("Add pipeline with templates");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo {{ branch }} > branch_marker.txt",
    "cat branch_marker.txt > branch_check.txt",
]
"#,
    );

    snapshot_switch(
        "post_start_pipeline_template_vars",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let check_file = worktree_path.join("branch_check.txt");
    wait_for_file_content(&check_file);

    let content = fs::read_to_string(&check_file).unwrap();
    assert!(
        content.contains("feature"),
        "Template variable should be expanded in pipeline, got: {content}"
    );
}

#[rstest]
fn test_post_start_target_variable_expands_to_branch(repo: TestRepo) {
    // `{{ target }}` in post-start should equal the bare `{{ branch }}` —
    // symmetric with `pre-switch`, which already injects `target`.
    repo.write_project_config(r#"post-start = "echo '{{ target }}' > target_marker.txt""#);
    repo.commit("Add post-start with target var");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo '{{ target }}' > target_marker.txt"]
"#,
    );

    snapshot_switch(
        "post_start_target_variable",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker = worktree_path.join("target_marker.txt");
    wait_for_file_content(&marker);

    let content = fs::read_to_string(&marker).unwrap();
    assert_eq!(
        content.trim(),
        "feature",
        "target should resolve to the newly created branch, got: {content}"
    );
}

#[rstest]
fn test_post_switch_target_variable_on_existing_switch(repo: TestRepo) {
    // `{{ target }}` in post-switch must equal the destination branch for
    // switches to an existing worktree — not just creates.
    repo.write_project_config(r#"post-switch = "echo '{{ target }}' > target_marker.txt""#);
    repo.commit("Add post-switch with target var");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo '{{ target }}' > target_marker.txt"]
"#,
    );

    // Create the destination worktree first, then switch back to main so the
    // next invocation exercises the existing-worktree switch path (not create).
    repo.wt_command()
        .args(["switch", "--create", "feature", "--no-hooks", "--yes"])
        .output()
        .expect("failed to pre-create feature worktree");
    repo.wt_command()
        .args(["switch", "main", "--no-hooks", "--yes"])
        .output()
        .expect("failed to switch back to main");

    snapshot_switch("post_switch_target_variable_existing", &repo, &["feature"]);

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let marker = worktree_path.join("target_marker.txt");
    wait_for_file_content(&marker);

    let content = fs::read_to_string(&marker).unwrap();
    assert_eq!(
        content.trim(),
        "feature",
        "target should resolve to the switched-to branch, got: {content}"
    );
}

#[rstest]
fn test_post_start_mixed_user_pipeline_project_flat(repo: TestRepo) {
    // User has a pipeline, project has flat concurrent commands.
    // Both should execute.
    repo.write_test_config(
        r#"post-start = [
    "echo USER_SETUP > user_pipeline_marker.txt",
    { user_bg = "echo USER_BG > user_bg.txt" }
]
"#,
    );

    repo.write_project_config(
        r#"[post-start]
proj = "echo PROJECT > project_marker.txt"
"#,
    );
    repo.commit("Add project config");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = ["echo PROJECT > project_marker.txt"]
"#,
    );

    snapshot_switch(
        "post_start_mixed_user_pipeline_project_flat",
        &repo,
        &["--create", "feature"],
    );

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");

    // User pipeline should run
    wait_for_file_content(&worktree_path.join("user_bg.txt"));
    let user_bg = fs::read_to_string(worktree_path.join("user_bg.txt")).unwrap();
    assert!(user_bg.contains("USER_BG"));

    // Project flat hook should also run
    wait_for_file_content(&worktree_path.join("project_marker.txt"));
    let project = fs::read_to_string(worktree_path.join("project_marker.txt")).unwrap();
    assert!(project.contains("PROJECT"));
}

/// `WORKTRUNK_TEST_SERIAL_CONCURRENT=1` makes the background pipeline runner's
/// concurrent group run commands one at a time in declaration order. The two
/// commands append to the same file, so a deterministic ordering proves they
/// ran serially (a true concurrent run could interleave the appends). The
/// failing-first-command variant additionally exercises the bail-on-failure
/// path inside the serial branch — second never gets to run.
#[rstest]
fn test_post_start_concurrent_serial_force(repo: TestRepo) {
    repo.write_project_config(
        r#"[post-start]
first = "echo FIRST >> serial_order.txt"
second = "echo SECOND >> serial_order.txt"
"#,
    );
    repo.commit("Add concurrent post-start");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo FIRST >> serial_order.txt",
    "echo SECOND >> serial_order.txt",
]
"#,
    );

    let temp_home = TempDir::new().unwrap();
    let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature"], None);
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    set_temp_home_env(&mut cmd, temp_home.path());
    let _ = cmd.output().unwrap();

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    let order_file = worktree_path.join("serial_order.txt");
    wait_for_file_lines(&order_file, 2);

    let content = fs::read_to_string(&order_file).unwrap();
    assert_eq!(
        content, "FIRST\nSECOND\n",
        "serial run should append in declaration order"
    );
}

#[rstest]
fn test_post_start_concurrent_serial_bails_on_failure(repo: TestRepo) {
    // First command writes a marker then fails; second writes a marker that
    // would always exist if it ran. Serial mode bails after the first failure,
    // so the second marker should be absent.
    repo.write_project_config(
        r#"[post-start]
first = "echo FIRST > first_marker.txt && false"
second = "echo SECOND > second_marker.txt"
"#,
    );
    repo.commit("Add failing post-start");

    repo.write_test_approvals(
        r#"[projects."../origin"]
approved-commands = [
    "echo FIRST > first_marker.txt && false",
    "echo SECOND > second_marker.txt",
]
"#,
    );

    let temp_home = TempDir::new().unwrap();
    let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "feature"], None);
    cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
    set_temp_home_env(&mut cmd, temp_home.path());
    let _ = cmd.output().unwrap();

    let worktree_path = repo.root_path().parent().unwrap().join("repo.feature");
    wait_for_file_content(&worktree_path.join("first_marker.txt"));

    // Wait for any trailing background work, then assert the second never ran.
    thread::sleep(SLEEP_FOR_ABSENCE_CHECK);
    assert!(
        !worktree_path.join("second_marker.txt").exists(),
        "serial mode should bail on first failure — second command must not run"
    );
}