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
//! Integration tests for `wt step promote`

use crate::common::{TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings, wt_command};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
use worktrunk::git::Repository;
use worktrunk::shell_exec::Cmd;

/// Helper to get the current branch in a directory
fn branch_name(repo: &TestRepo, dir: &std::path::Path) -> String {
    let output = repo
        .git_command()
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(dir)
        .run()
        .unwrap();
    assert!(
        output.status.success(),
        "git rev-parse failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    String::from_utf8_lossy(&output.stdout).trim().to_string()
}

/// Test promoting from another worktree (no argument)
#[rstest]
fn test_promote_from_worktree(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // Run promote from the worktree (no argument needed)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote"],
        Some(&feature_path),
    ));

    // Verify branches were exchanged
    assert_eq!(
        branch_name(&repo, repo.root_path()),
        "feature",
        "main worktree should now have feature"
    );
    assert_eq!(
        branch_name(&repo, &feature_path),
        "main",
        "other worktree should now have main"
    );
}

/// Test promoting by specifying branch name
#[rstest]
fn test_promote_with_branch_argument(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // Run promote from main worktree, specifying the branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));

    // Verify branches were exchanged
    assert_eq!(
        branch_name(&repo, repo.root_path()),
        "feature",
        "main worktree should now have feature"
    );
    assert_eq!(
        branch_name(&repo, &feature_path),
        "main",
        "other worktree should now have main"
    );
}

/// Test restoring canonical state
#[rstest]
fn test_promote_restore(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // First promote: feature to main worktree
    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "first promote failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify first promote worked
    assert_eq!(branch_name(&repo, repo.root_path()), "feature");

    // Restore: promote main back (now 'main' is in the other worktree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "main"],
        Some(repo.root_path()),
    ));

    // Verify canonical state restored
    assert_eq!(
        branch_name(&repo, repo.root_path()),
        "main",
        "main worktree should have main again"
    );
    assert_eq!(
        branch_name(&repo, &feature_path),
        "feature",
        "other worktree should have feature again"
    );
}

/// Test when branch is already in main worktree
#[rstest]
fn test_promote_already_in_main(repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    // 'main' is already in main worktree
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "main"],
        Some(repo.root_path()),
    ));
}

/// Test auto-restore with no argument from main worktree (after prior promote)
#[rstest]
fn test_promote_auto_restore(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // First promote: feature to main worktree (creates mismatch)
    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "first promote failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Verify first promote worked
    assert_eq!(branch_name(&repo, repo.root_path()), "feature");
    assert_eq!(branch_name(&repo, &feature_path), "main");

    // Auto-restore: no argument from main worktree restores default branch
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote"],
        Some(repo.root_path()),
    ));

    // Verify canonical state restored
    assert_eq!(
        branch_name(&repo, repo.root_path()),
        "main",
        "main worktree should have main again"
    );
    assert_eq!(
        branch_name(&repo, &feature_path),
        "feature",
        "other worktree should have feature again"
    );
}

/// Test auto-restore when no argument from main worktree (already canonical)
#[rstest]
fn test_promote_no_arg_from_main(repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    // From main worktree with no arg: restores default branch (already there)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote"],
        Some(repo.root_path()),
    ));
}

/// Test error when branch has no worktree
#[rstest]
fn test_promote_branch_not_in_worktree(repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    // Create a branch but don't make a worktree for it
    repo.run_git(&["branch", "orphan"]);

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "orphan"],
        Some(repo.root_path()),
    ));
}

/// Test error when main worktree is dirty
#[rstest]
fn test_promote_dirty_main(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let _feature_path = repo.add_worktree("feature");

    // Make main worktree dirty
    fs::write(repo.root_path().join("dirty.txt"), "uncommitted").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));
}

/// Test error when target worktree is dirty
#[rstest]
fn test_promote_dirty_target(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // Make target worktree dirty
    fs::write(feature_path.join("dirty.txt"), "uncommitted").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));
}

/// Test that wt list shows mismatch indicator after promote
#[rstest]
fn test_promote_shows_mismatch_in_list(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let _feature_path = repo.add_worktree("feature");

    // Promote
    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "promote failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // List should show mismatch indicators
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "list",
        &[],
        Some(repo.root_path()),
    ));
}

/// Test error when run in a bare repository (no worktrees)
#[test]
fn test_promote_bare_repo_no_worktrees() {
    let test = TestRepo::bare();

    // Try to run promote in the bare repo - fails with "No worktrees found"
    let output = test
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(
        stderr.contains("No worktrees found"),
        "Expected no worktrees error, got: {stderr}"
    );
}

/// Test error when run in a bare repository with worktrees
#[test]
fn test_promote_bare_repo_with_worktrees() {
    let temp_dir = tempfile::tempdir().unwrap();
    let bare_repo = temp_dir.path().join("bare.git");
    let worktree_path = temp_dir.path().join("worktree");
    let temp_clone = temp_dir.path().join("temp");

    // Create a bare repository
    Cmd::new("git")
        .args([
            "init",
            "--bare",
            "--initial-branch=main",
            bare_repo.to_str().unwrap(),
        ])
        .run()
        .unwrap();

    // Create a commit via a temporary clone
    Cmd::new("git")
        .args([
            "clone",
            bare_repo.to_str().unwrap(),
            temp_clone.to_str().unwrap(),
        ])
        .run()
        .unwrap();

    let clone_repo = Repository::at(&temp_clone).unwrap();
    clone_repo
        .run_command(&["config", "user.email", "test@test.com"])
        .unwrap();
    clone_repo
        .run_command(&["config", "user.name", "Test"])
        .unwrap();
    clone_repo
        .run_command(&["commit", "--allow-empty", "-m", "init"])
        .unwrap();
    clone_repo.run_command(&["push", "origin", "main"]).unwrap();

    // Add a worktree to the bare repo
    let bare_repo_handle = Repository::at(&bare_repo).unwrap();
    bare_repo_handle
        .run_command(&["worktree", "add", worktree_path.to_str().unwrap(), "main"])
        .unwrap();

    // Try to run promote in the bare repo - should fail with bare repo error
    let output = wt_command()
        .args(["step", "promote", "feature"])
        .current_dir(&bare_repo)
        .output()
        .unwrap();

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success());
    assert!(
        stderr.contains("bare repositories"),
        "Expected bare repo error, got: {stderr}"
    );
}

/// Test error when main worktree has detached HEAD
#[rstest]
fn test_promote_detached_head_main(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let _feature_path = repo.add_worktree("feature");

    // Detach HEAD in main worktree
    let sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .current_dir(repo.root_path())
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&sha.stdout).trim().to_string();

    repo.git_command()
        .args(["checkout", "--detach", &sha])
        .current_dir(repo.root_path())
        .run()
        .unwrap();

    // Promote should fail due to detached HEAD
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));
}

/// Helper: commit a .gitignore in a worktree
fn commit_gitignore(repo: &TestRepo, dir: &std::path::Path, content: &str) {
    fs::write(dir.join(".gitignore"), content).unwrap();
    repo.run_git_in(dir, &["add", ".gitignore"]);
    repo.run_git_in(dir, &["commit", "-m", "add gitignore"]);
}

// ─── Swap tests ───────────────────────────────────────────────────────────

/// Both worktrees have gitignored files — verify complete bidirectional swap
#[rstest]
fn test_promote_swap_bidirectional(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n*.log\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Main: build/main-artifact, app.log
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/main-artifact"), "main build").unwrap();
    fs::write(repo.root_path().join("app.log"), "main log").unwrap();

    // Feature: build/feature-artifact, debug.log
    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/feature-artifact"), "feature build").unwrap();
    fs::write(feature_path.join("debug.log"), "feature log").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));

    // Main worktree (now feature) should have feature's files
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/feature-artifact")).unwrap(),
        "feature build"
    );
    assert_eq!(
        fs::read_to_string(repo.root_path().join("debug.log")).unwrap(),
        "feature log"
    );
    assert!(!repo.root_path().join("build/main-artifact").exists());
    assert!(!repo.root_path().join("app.log").exists());

    // Feature worktree (now main) should have main's files
    assert_eq!(
        fs::read_to_string(feature_path.join("build/main-artifact")).unwrap(),
        "main build"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("app.log")).unwrap(),
        "main log"
    );
    assert!(!feature_path.join("build/feature-artifact").exists());
    assert!(!feature_path.join("debug.log").exists());
}

/// Only main worktree has gitignored files — they should move to the other worktree
#[rstest]
fn test_promote_swap_only_main_has_ignored(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n*.log\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Only main has ignored files
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/artifact"), "main artifact").unwrap();
    fs::write(repo.root_path().join("app.log"), "main log").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Main worktree should be clean (no ignored files)
    assert!(!repo.root_path().join("build").exists());
    assert!(!repo.root_path().join("app.log").exists());

    // Feature worktree should have main's files
    assert_eq!(
        fs::read_to_string(feature_path.join("build/artifact")).unwrap(),
        "main artifact"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("app.log")).unwrap(),
        "main log"
    );
}

/// Only feature worktree has gitignored files — they should move to the main worktree
#[rstest]
fn test_promote_swap_only_feature_has_ignored(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Only feature has ignored files
    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/artifact"), "feature artifact").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Main worktree should have feature's files
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/artifact")).unwrap(),
        "feature artifact"
    );

    // Feature worktree should be clean
    assert!(!feature_path.join("build").exists());
}

/// Neither worktree has gitignored files — promote should succeed without swap message
#[rstest]
fn test_promote_swap_no_ignored_files(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let _feature_path = repo.add_worktree("feature");

    // No .gitignore, no ignored files — just promote
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        Some(repo.root_path()),
    ));
}

/// Directories with nested structure are swapped correctly (deep nesting)
#[rstest]
fn test_promote_swap_nested_directories(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Main: deep nested structure
    fs::create_dir_all(repo.root_path().join("build/debug/x86/obj")).unwrap();
    fs::write(
        repo.root_path().join("build/debug/x86/obj/main.o"),
        "main object",
    )
    .unwrap();
    fs::write(repo.root_path().join("build/debug/main.bin"), "main binary").unwrap();

    // Feature: different nested structure
    fs::create_dir_all(feature_path.join("build/release/arm64")).unwrap();
    fs::write(
        feature_path.join("build/release/arm64/feature.bin"),
        "feature binary",
    )
    .unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Main worktree should have feature's structure
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/release/arm64/feature.bin")).unwrap(),
        "feature binary"
    );
    assert!(!repo.root_path().join("build/debug").exists());

    // Feature worktree should have main's structure
    assert_eq!(
        fs::read_to_string(feature_path.join("build/debug/x86/obj/main.o")).unwrap(),
        "main object"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("build/debug/main.bin")).unwrap(),
        "main binary"
    );
    assert!(!feature_path.join("build/release").exists());
}

/// Same-named ignored files with different content are swapped (not clobbered)
#[rstest]
fn test_promote_swap_same_filename_different_content(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Both have build/output.bin with different content
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/output.bin"), "main output").unwrap();

    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/output.bin"), "feature output").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Content should be swapped, not lost
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/output.bin")).unwrap(),
        "feature output",
        "main worktree should have feature's content"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("build/output.bin")).unwrap(),
        "main output",
        "feature worktree should have main's content"
    );
}

/// Promote and restore round-trip preserves gitignored files
#[rstest]
fn test_promote_swap_roundtrip(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n*.log\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Create ignored files
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/artifact"), "main build").unwrap();
    fs::write(repo.root_path().join("app.log"), "main log").unwrap();

    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/artifact"), "feature build").unwrap();
    fs::write(feature_path.join("debug.log"), "feature log").unwrap();

    // Promote feature → main
    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Restore: promote main back
    let output = repo
        .wt_command()
        .args(["step", "promote", "main"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // After round-trip: everything should be back to original state
    assert_eq!(branch_name(&repo, repo.root_path()), "main");
    assert_eq!(branch_name(&repo, &feature_path), "feature");

    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/artifact")).unwrap(),
        "main build",
        "main worktree should have its original build artifact back"
    );
    assert_eq!(
        fs::read_to_string(repo.root_path().join("app.log")).unwrap(),
        "main log"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("build/artifact")).unwrap(),
        "feature build",
        "feature worktree should have its original build artifact back"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("debug.log")).unwrap(),
        "feature log"
    );
}

/// .worktreeinclude limits which ignored files are swapped
#[rstest]
fn test_promote_swap_respects_worktreeinclude(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    // .worktreeinclude only includes build/ — .env and *.log should NOT be swapped
    let gitignore = "build/\n*.log\n.env\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Commit .worktreeinclude on both branches (must be tracked for clean worktree)
    fs::write(repo.root_path().join(".worktreeinclude"), "build/\n").unwrap();
    repo.run_git(&["add", ".worktreeinclude"]);
    repo.run_git(&["commit", "-m", "add worktreeinclude"]);

    fs::write(feature_path.join(".worktreeinclude"), "build/\n").unwrap();
    repo.run_git_in(&feature_path, &["add", ".worktreeinclude"]);
    repo.run_git_in(&feature_path, &["commit", "-m", "add worktreeinclude"]);

    // Main: build/ + .env + app.log
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/main-bin"), "main binary").unwrap();
    fs::write(repo.root_path().join(".env"), "MAIN_SECRET=1").unwrap();
    fs::write(repo.root_path().join("app.log"), "main log").unwrap();

    // Feature: build/ + .env + debug.log
    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/feature-bin"), "feature binary").unwrap();
    fs::write(feature_path.join(".env"), "FEATURE_SECRET=1").unwrap();
    fs::write(feature_path.join("debug.log"), "feature log").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // build/ should be swapped (matches .worktreeinclude)
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/feature-bin")).unwrap(),
        "feature binary"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("build/main-bin")).unwrap(),
        "main binary"
    );

    // .env and *.log should NOT be swapped (excluded by .worktreeinclude)
    assert_eq!(
        fs::read_to_string(repo.root_path().join(".env")).unwrap(),
        "MAIN_SECRET=1",
        ".env should stay in place"
    );
    assert_eq!(
        fs::read_to_string(repo.root_path().join("app.log")).unwrap(),
        "main log",
        "app.log should stay in place"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join(".env")).unwrap(),
        "FEATURE_SECRET=1",
        ".env should stay in place"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("debug.log")).unwrap(),
        "feature log",
        "debug.log should stay in place"
    );
}

/// No stale staging directory left after successful promote
#[rstest]
fn test_promote_swap_no_staging_leftover(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/artifact"), "data").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // The staging directory should be cleaned up
    let git_dir = repo.root_path().join(".git");
    assert!(
        !git_dir.join("wt/staging/promote").exists(),
        "staging directory should be cleaned up after promote"
    );
}

/// Tracked files are not affected by the swap
#[rstest]
fn test_promote_swap_does_not_touch_tracked_files(mut repo: TestRepo) {
    let feature_path = repo.add_worktree("feature");

    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);

    // Create a tracked file on main (committed, not ignored)
    fs::write(repo.root_path().join("src.txt"), "main source").unwrap();
    repo.run_git(&["add", "src.txt"]);
    repo.run_git(&["commit", "-m", "add source"]);

    // Create a tracked file on feature
    fs::write(feature_path.join("feat.txt"), "feature source").unwrap();
    repo.run_git_in(&feature_path, &["add", "feat.txt"]);
    repo.run_git_in(&feature_path, &["commit", "-m", "add feat source"]);

    // Create ignored files
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/main.o"), "main obj").unwrap();
    fs::create_dir_all(feature_path.join("build")).unwrap();
    fs::write(feature_path.join("build/feat.o"), "feat obj").unwrap();

    let output = repo
        .wt_command()
        .args(["step", "promote", "feature"])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Tracked files should follow their branches (via git switch, not our swap)
    // Main worktree (now on feature) should have feat.txt from git switch
    assert_eq!(
        fs::read_to_string(repo.root_path().join("feat.txt")).unwrap(),
        "feature source"
    );
    // Feature worktree (now on main) should have src.txt from git switch
    assert_eq!(
        fs::read_to_string(feature_path.join("src.txt")).unwrap(),
        "main source"
    );

    // Ignored files should be swapped by our code
    assert_eq!(
        fs::read_to_string(repo.root_path().join("build/feat.o")).unwrap(),
        "feat obj"
    );
    assert_eq!(
        fs::read_to_string(feature_path.join("build/main.o")).unwrap(),
        "main obj"
    );
}

/// Test that promote bails with guidance when stale staging directory exists
#[rstest]
fn test_promote_stale_staging_blocks_with_guidance(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // Need gitignored files so stage_ignored is actually called
    let gitignore = "build/\n";
    commit_gitignore(&repo, repo.root_path(), gitignore);
    commit_gitignore(&repo, &feature_path, gitignore);
    fs::create_dir_all(repo.root_path().join("build")).unwrap();
    fs::write(repo.root_path().join("build/artifact"), "main build").unwrap();

    // Create a fake leftover staging directory (as if previous promote was interrupted)
    let git_dir = repo.root_path().join(".git");
    let staging_dir = git_dir.join("wt/staging/promote");
    fs::create_dir_all(staging_dir.join("a")).unwrap();
    fs::write(staging_dir.join("a/leftover"), "leftover data").unwrap();

    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote", "feature"],
        None
    ));

    // Staging dir should still exist (not destroyed)
    assert!(staging_dir.exists(), "staging dir should be preserved");
    assert_eq!(
        fs::read_to_string(staging_dir.join("a/leftover")).unwrap(),
        "leftover data"
    );
}

/// Test error when linked worktree has detached HEAD (no-arg promote)
#[rstest]
fn test_promote_detached_head_linked(mut repo: TestRepo) {
    let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();
    let feature_path = repo.add_worktree("feature");

    // Detach HEAD in the linked worktree
    let sha = repo
        .git_command()
        .args(["rev-parse", "HEAD"])
        .current_dir(&feature_path)
        .run()
        .unwrap();
    let sha = String::from_utf8_lossy(&sha.stdout).trim().to_string();

    repo.git_command()
        .args(["checkout", "--detach", &sha])
        .current_dir(&feature_path)
        .run()
        .unwrap();

    // No-arg promote from linked worktree should fail due to detached HEAD
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["promote"],
        Some(&feature_path),
    ));
}