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

use crate::common::{TestRepo, make_snapshot_cmd, repo};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;

/// Get the parent directory of the repo (where worktrees are created)
fn worktree_parent(repo: &TestRepo) -> std::path::PathBuf {
    repo.root_path().parent().unwrap().to_path_buf()
}

/// Test with no mismatched worktrees
#[rstest]
fn test_relocate_no_mismatches(mut repo: TestRepo) {
    // Create a worktree at the expected location
    repo.add_worktree("feature");

    // All worktrees should be at expected paths
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
}

/// Test relocating a single mismatched worktree
#[rstest]
fn test_relocate_single_mismatch(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree manually at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Relocate should move it to the expected path
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify the worktree was moved to expected location
    let expected_path = parent.join("repo.feature");
    assert!(
        expected_path.exists(),
        "Worktree should be at expected path: {}",
        expected_path.display()
    );
    assert!(
        !wrong_path.exists(),
        "Old worktree path should no longer exist: {}",
        wrong_path.display()
    );
}

/// Test dry run shows what would be moved
#[rstest]
fn test_relocate_dry_run(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Dry run should show what would be moved without actually moving
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "--dry-run"],
        None
    ));

    // Verify the worktree was NOT moved
    assert!(
        wrong_path.exists(),
        "Worktree should still be at wrong path in dry run: {}",
        wrong_path.display()
    );
}

/// Test that locked worktrees are skipped
#[rstest]
fn test_relocate_locked_worktree(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location and lock it
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);
    repo.run_git(&["worktree", "lock", wrong_path.to_str().unwrap()]);

    // Relocate should skip locked worktree
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify the worktree was NOT moved
    assert!(
        wrong_path.exists(),
        "Locked worktree should not be moved: {}",
        wrong_path.display()
    );
}

/// Test mixed success and skip (covers "Relocated X, skipped Y" output)
#[rstest]
fn test_relocate_mixed_success_and_skip(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create one worktree that can be moved
    let wrong_path1 = parent.join("wrong-location-1");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature1",
        wrong_path1.to_str().unwrap(),
    ]);

    // Create another worktree that is locked (will be skipped)
    let wrong_path2 = parent.join("wrong-location-2");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature2",
        wrong_path2.to_str().unwrap(),
    ]);
    repo.run_git(&["worktree", "lock", wrong_path2.to_str().unwrap()]);

    // Relocate should move feature1 and skip feature2
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify feature1 was moved
    let expected_path1 = parent.join("repo.feature1");
    assert!(
        expected_path1.exists(),
        "feature1 should be at expected path: {}",
        expected_path1.display()
    );

    // Verify feature2 was NOT moved (locked)
    assert!(
        wrong_path2.exists(),
        "Locked feature2 should not be moved: {}",
        wrong_path2.display()
    );
}

/// Test that existing target path causes skip
#[rstest]
fn test_relocate_target_exists(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Create a directory at the expected location
    let expected_path = parent.join("repo.feature");
    fs::create_dir_all(&expected_path).unwrap();
    fs::write(expected_path.join("existing-file.txt"), "existing").unwrap();

    // Relocate should skip because target exists
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify the worktree was NOT moved
    assert!(
        wrong_path.exists(),
        "Worktree should not be moved when target exists: {}",
        wrong_path.display()
    );
}

/// Test that dirty worktrees are skipped without --commit
#[rstest]
fn test_relocate_dirty_without_commit(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Make uncommitted changes
    fs::write(wrong_path.join("dirty.txt"), "uncommitted changes").unwrap();

    // Relocate should skip dirty worktree
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify the worktree was NOT moved
    assert!(
        wrong_path.exists(),
        "Dirty worktree should not be moved: {}",
        wrong_path.display()
    );
}

/// Test that --commit auto-commits dirty worktrees before relocating
#[rstest]
fn test_relocate_dirty_with_commit(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Make uncommitted changes
    fs::write(wrong_path.join("dirty.txt"), "uncommitted changes").unwrap();

    // Configure mock LLM command via config file
    let worktrunk_config = r#"
[commit.generation]
command = "cat >/dev/null && echo 'chore: auto-commit before relocate'"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Relocate with --commit should commit then move
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "--commit"],
        None
    ));

    // Verify the worktree was moved to expected location
    let expected_path = parent.join("repo.feature");
    assert!(
        expected_path.exists(),
        "Worktree should be at expected path after commit: {}",
        expected_path.display()
    );
    assert!(
        !wrong_path.exists(),
        "Old worktree path should no longer exist: {}",
        wrong_path.display()
    );
}

/// Test that --clobber backs up non-worktree paths at target locations
#[rstest]
fn test_relocate_clobber_backs_up(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Create a directory at the expected location (non-worktree blocker)
    let expected_path = parent.join("repo.feature");
    fs::create_dir_all(&expected_path).unwrap();
    fs::write(expected_path.join("existing-file.txt"), "existing content").unwrap();

    // Relocate with --clobber should backup and move
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "--clobber"],
        None
    ));

    // Verify the worktree was moved
    assert!(
        expected_path.exists(),
        "Worktree should be at expected location: {}",
        expected_path.display()
    );
    assert!(
        !wrong_path.exists(),
        "Original path should no longer exist: {}",
        wrong_path.display()
    );

    // Verify backup exists (with timestamp suffix)
    let backup_exists = fs::read_dir(&parent)
        .unwrap()
        .filter_map(|e| e.ok())
        .any(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            name.starts_with("repo.feature.bak-")
        });
    assert!(backup_exists, "Backup directory should exist");
}

/// Test that --clobber refuses to clobber an existing worktree
#[rstest]
fn test_relocate_clobber_refuses_worktree(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create worktree alpha at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "alpha",
        wrong_path.to_str().unwrap(),
    ]);

    // Create another worktree beta at alpha's expected location
    let expected_path = parent.join("repo.alpha");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "beta",
        expected_path.to_str().unwrap(),
    ]);

    // Relocate with --clobber should still skip (can't clobber a worktree)
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "--clobber", "alpha"],
        None
    ));

    // Verify alpha was NOT moved (beta still occupies the target)
    assert!(
        wrong_path.exists(),
        "alpha should still be at wrong location: {}",
        wrong_path.display()
    );
}

/// Test relocating specific worktrees by branch name
#[rstest]
fn test_relocate_specific_branch(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create two worktrees at non-standard locations
    let wrong_path1 = parent.join("wrong-location-1");
    let wrong_path2 = parent.join("wrong-location-2");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature1",
        wrong_path1.to_str().unwrap(),
    ]);
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature2",
        wrong_path2.to_str().unwrap(),
    ]);

    // Relocate only feature1
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "feature1"],
        None
    ));

    // Verify only feature1 was moved
    let expected_path1 = parent.join("repo.feature1");
    assert!(
        expected_path1.exists(),
        "feature1 should be at expected path: {}",
        expected_path1.display()
    );
    assert!(
        wrong_path2.exists(),
        "feature2 should still be at wrong path: {}",
        wrong_path2.display()
    );
}

/// Test relocating main worktree with non-default branch (create + switch)
#[rstest]
fn test_relocate_main_worktree(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Switch main worktree to a feature branch
    repo.run_git(&["checkout", "-b", "feature"]);

    // Relocate should create worktree for feature and switch main to default branch
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify new worktree was created
    let expected_path = parent.join("repo.feature");
    assert!(
        expected_path.exists(),
        "Feature worktree should be created at: {}",
        expected_path.display()
    );

    // Verify main worktree is now on default branch
    let output = repo
        .git_command()
        .args(["branch", "--show-current"])
        .run()
        .unwrap();
    let current_branch = String::from_utf8_lossy(&output.stdout);
    assert_eq!(
        current_branch.trim(),
        "main",
        "Main worktree should be on default branch"
    );
}

/// Test swap scenario: two worktrees at each other's expected locations
///
/// When alpha is at repo.beta and beta is at repo.alpha, relocate
/// automatically handles the swap via a temporary location.
#[rstest]
fn test_relocate_swap(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create worktrees at each other's expected locations
    // alpha at repo.beta (where beta should go)
    // beta at repo.alpha (where alpha should go)
    let path_for_beta = parent.join("repo.beta");
    let path_for_alpha = parent.join("repo.alpha");

    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "alpha",
        path_for_beta.to_str().unwrap(), // alpha at beta's expected location
    ]);
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "beta",
        path_for_alpha.to_str().unwrap(), // beta at alpha's expected location
    ]);

    // Relocate resolves the swap via temp location
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify both are now at their expected locations
    assert!(path_for_alpha.exists(), "alpha should be at repo.alpha");
    assert!(path_for_beta.exists(), "beta should be at repo.beta");
}

/// Test relocating multiple worktrees shows compact output
#[rstest]
fn test_relocate_multiple(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create 5 worktrees at non-standard locations
    for i in 1..=5 {
        let wrong_path = parent.join(format!("wrong-{i}"));
        repo.run_git(&[
            "worktree",
            "add",
            "-b",
            &format!("feature-{i}"),
            wrong_path.to_str().unwrap(),
        ]);
    }

    // Relocate all
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));

    // Verify all were moved
    for i in 1..=5 {
        let expected_path = parent.join(format!("repo.feature-{i}"));
        assert!(
            expected_path.exists(),
            "feature-{i} should be at expected path: {}",
            expected_path.display()
        );
    }
}

/// Test that two worktrees targeting the same path doesn't panic
///
/// Before the fix, this would panic with "existing target must be a tracked worktree"
/// because after the first worktree moved, the second would find an occupied target
/// that wasn't in the tracking map.
#[rstest]
fn test_relocate_same_target_no_panic(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create two worktrees at non-standard locations
    let wrong_path1 = parent.join("wrong-location-1");
    let wrong_path2 = parent.join("wrong-location-2");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "alpha",
        wrong_path1.to_str().unwrap(),
    ]);
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "beta",
        wrong_path2.to_str().unwrap(),
    ]);

    // Configure a template that maps BOTH branches to the same path
    // This creates the "same target" scenario
    let worktrunk_config = r#"
worktree-path = "{{ repo }}.shared"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Relocate only alpha and beta (exclude any other branches from prior tests)
    // Previously this would panic
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "alpha", "beta"],
        None
    ));

    // Verify first worktree moved to shared location
    // Note: {{ repo }} in template uses repo NAME, so path is inside repo root
    let shared_path = repo.root_path().join("repo.shared");
    assert!(
        shared_path.exists(),
        "First worktree should be at shared path: {}",
        shared_path.display()
    );

    // Second worktree should still be at its original location (skipped)
    // It was skipped because the target was occupied after first moved there
    assert!(
        wrong_path1.exists() || wrong_path2.exists(),
        "One worktree should remain at original location (skipped)"
    );
}

/// Test that template expansion errors are reported gracefully
#[rstest]
fn test_relocate_template_error(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);

    // Configure an invalid template with a non-existent variable
    let worktrunk_config = r#"
worktree-path = "{{ nonexistent_variable }}"
"#;
    fs::write(repo.test_config_path(), worktrunk_config).unwrap();

    // Relocate should warn about template error and skip
    // Filter to just "feature" to avoid noise from other worktrees
    assert_cmd_snapshot!(make_snapshot_cmd(
        &repo,
        "step",
        &["relocate", "feature"],
        None
    ));

    // Verify the worktree was NOT moved (skipped due to template error)
    assert!(
        wrong_path.exists(),
        "Worktree should not be moved when template fails: {}",
        wrong_path.display()
    );
}

/// Regression test: main worktree relocation must surface a failed
/// `git checkout <default_branch>` rather than silently claiming success.
///
/// Setup engineers a state where `worktrunk.default-branch` is set to a
/// branch that does not exist locally. `Repository::default_branch()`
/// trusts the persisted value (validation happens downstream), so
/// `wt step relocate` proceeds into `move_main_worktree`, which tries
/// `git checkout <nonexistent-branch>`. Before the fix, `Cmd::run()`
/// returned `Ok(Output { status: non-zero, .. })` and the `?` operator
/// didn't propagate it, so relocate printed "Relocated main ..." even
/// though nothing happened.
///
/// After the fix: non-zero exit bails with the git stderr, exit code is
/// non-zero, and the main worktree stays at its original path.
#[rstest]
fn test_relocate_main_worktree_checkout_failure_surfaces(repo: TestRepo) {
    let parent = worktree_parent(&repo);
    let repo_path = repo.root_path().to_path_buf();

    // Switch main worktree to a non-default branch so it becomes a
    // relocation candidate (expected path = repo.feature, not repo).
    repo.run_git(&["checkout", "-b", "feature"]);

    // Point worktrunk's default-branch cache at a branch that doesn't
    // resolve locally. `default_branch()` now returns this value without
    // validating it, so relocate's preflight does NOT bail and the main
    // worktree code path runs `git checkout nonexistent-branch-xyz`.
    repo.run_git(&[
        "config",
        "worktrunk.default-branch",
        "nonexistent-branch-xyz",
    ]);

    let output = repo
        .wt_command()
        .args(["step", "relocate"])
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        !output.status.success(),
        "relocate must fail when checkout of default branch fails; \
         stdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        !stderr.contains("Relocated"),
        "relocate must not claim success after a failed checkout; \
         stdout: {stdout}\nstderr: {stderr}"
    );

    // Main worktree is untouched - still at repo_path, still on feature.
    assert!(
        repo_path.exists(),
        "main worktree path should still exist: {}",
        repo_path.display()
    );
    let expected_path = parent.join("repo.feature");
    assert!(
        !expected_path.exists(),
        "relocate must not create the new worktree path after checkout \
         failure: {}",
        expected_path.display()
    );

    let branch_output = repo
        .git_command()
        .args(["branch", "--show-current"])
        .run()
        .unwrap();
    assert_eq!(
        String::from_utf8_lossy(&branch_output.stdout).trim(),
        "feature",
        "main worktree branch should be unchanged after failed checkout"
    );
}

/// Test that empty default branch is detected early with actionable error.
///
/// Engineers a state where detection genuinely fails (no remote, no
/// standard branch names, no init.defaultBranch) so `default_branch()`
/// returns None — relocate's preflight bails with a clear setup hint.
#[rstest]
fn test_relocate_empty_default_branch(repo: TestRepo) {
    let parent = worktree_parent(&repo);

    // Create a worktree at a non-standard location on a branch with a
    // non-standard name, then rename `main` to another non-standard name
    // and remove the remote. With no remote, no main/master/develop/trunk,
    // and no init.defaultBranch, detection has nothing to go on.
    let wrong_path = parent.join("wrong-location");
    repo.run_git(&[
        "worktree",
        "add",
        "-b",
        "feature",
        wrong_path.to_str().unwrap(),
    ]);
    repo.run_git(&["branch", "-m", "main", "trunk-a"]);
    repo.run_git(&["remote", "remove", "origin"]);

    // Relocate should fail early with helpful error
    assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &["relocate"], None));
}