coven 0.1.0

A minimal streaming display and workflow runner for Claude Code's -p mode
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
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use rand::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, thiserror::Error)]
pub enum WorktreeError {
    #[error("not a git repository")]
    NotGitRepo,
    #[error("branch '{0}' already exists")]
    BranchExists(String),
    #[error("worktree has uncommitted changes")]
    DirtyWorkingTree,
    #[error("worktree has untracked files")]
    UntrackedFiles,
    #[error("cannot land from the main worktree")]
    IsMainWorktree,
    #[error("detached HEAD state")]
    DetachedHead,
    #[error("rebase conflict in: {0:?}")]
    RebaseConflict(Vec<String>),
    #[error("fast-forward failed — main has diverged")]
    FastForwardFailed,
    #[error("git command failed: {0}")]
    GitCommand(String),
}

/// Configuration for spawn operations.
pub struct SpawnOptions<'a> {
    /// Path to the git repo (or any worktree of it).
    pub repo_path: &'a Path,
    /// Optional branch name. If None, a random adjective-noun-N name is generated.
    pub branch: Option<&'a str>,
    /// Base directory for worktrees. Worktree will be created at `<base>/<project>/<branch>/`.
    pub base_path: &'a Path,
}

/// Result of a successful spawn operation.
#[derive(Debug, Serialize, Deserialize)]
pub struct SpawnResult {
    pub worktree_path: PathBuf,
    pub branch: String,
}

/// Result of a successful land operation.
#[derive(Debug, Serialize, Deserialize)]
pub struct LandResult {
    pub branch: String,
    pub main_branch: String,
}

// ── Word lists for random branch names ──────────────────────────────────

const ADJECTIVES: &[&str] = &[
    "swift", "quick", "bright", "calm", "clever", "cool", "crisp", "eager", "fast", "fresh",
    "keen", "light", "neat", "prime", "sharp", "silent", "smooth", "steady", "warm", "bold",
    "brave", "clear", "fleet", "golden", "agile", "nimble", "rapid", "blazing", "cosmic",
];

const NOUNS: &[&str] = &[
    "fox", "wolf", "bear", "hawk", "lion", "tiger", "raven", "eagle", "falcon", "otter", "cedar",
    "maple", "oak", "pine", "willow", "river", "stream", "brook", "delta", "canyon", "spark",
    "flame", "ember", "comet", "meteor", "nova", "pulse", "wave", "drift", "glow",
];

// ── Internal helpers ────────────────────────────────────────────────────

fn path_str(path: &Path) -> Result<&str, WorktreeError> {
    path.to_str()
        .ok_or_else(|| WorktreeError::GitCommand("path is not valid UTF-8".into()))
}

/// Run a git command in the given directory and return stdout.
fn git(dir: &Path, args: &[&str]) -> Result<String, WorktreeError> {
    let output = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .map_err(|e| WorktreeError::GitCommand(format!("failed to run git: {e}")))?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(WorktreeError::GitCommand(format!(
            "git {} failed: {}",
            args.join(" "),
            stderr.trim()
        )))
    }
}

/// Run a git command and return whether it exited successfully (ignoring output).
fn git_status(dir: &Path, args: &[&str]) -> Result<bool, WorktreeError> {
    let status = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map_err(|e| WorktreeError::GitCommand(format!("failed to run git: {e}")))?;
    Ok(status.success())
}

/// Parse `git worktree list --porcelain` to find the main worktree path and branch.
fn find_main_worktree(repo: &Path) -> Result<(PathBuf, String), WorktreeError> {
    let output = git(repo, &["worktree", "list", "--porcelain"])?;

    let mut path = None;
    let mut branch = None;

    for line in output.lines() {
        if path.is_none()
            && let Some(p) = line.strip_prefix("worktree ")
        {
            path = Some(PathBuf::from(p));
        }
        if branch.is_none()
            && let Some(b) = line.strip_prefix("branch refs/heads/")
        {
            branch = Some(b.to_string());
        }
        if line.is_empty() {
            break; // Only parse the first worktree entry
        }
    }

    match (path, branch) {
        (Some(p), Some(b)) => Ok((p, b)),
        _ => Err(WorktreeError::GitCommand(
            "could not parse worktree list output".into(),
        )),
    }
}

fn generate_branch_name() -> String {
    let mut rng = rand::rng();
    let adj = ADJECTIVES.choose(&mut rng).copied().unwrap_or("swift");
    let noun = NOUNS.choose(&mut rng).copied().unwrap_or("fox");
    let num: u32 = rng.random_range(0..100);
    format!("{adj}-{noun}-{num}")
}

// ── Public API ──────────────────────────────────────────────────────────

/// A git worktree entry from `git worktree list --porcelain`.
pub struct WorktreeEntry {
    pub path: PathBuf,
    /// Branch name (without refs/heads/ prefix). None for detached HEAD.
    pub branch: Option<String>,
    /// Whether this is the main worktree (first entry in the list).
    pub is_main: bool,
}

/// List all worktrees in the repository.
pub fn list_worktrees(repo_path: &Path) -> Result<Vec<WorktreeEntry>, WorktreeError> {
    let output = git(repo_path, &["worktree", "list", "--porcelain"])?;

    let mut entries = Vec::new();
    let mut current_path = None;
    let mut current_branch = None;

    for line in output.lines() {
        if let Some(p) = line.strip_prefix("worktree ") {
            current_path = Some(PathBuf::from(p));
        } else if let Some(b) = line.strip_prefix("branch refs/heads/") {
            current_branch = Some(b.to_string());
        } else if line.is_empty() {
            if let Some(path) = current_path.take() {
                let is_main = entries.is_empty();
                entries.push(WorktreeEntry {
                    path,
                    branch: current_branch.take(),
                    is_main,
                });
            }
            current_branch = None;
        }
    }
    // Handle last entry (porcelain output may not have trailing blank line)
    if let Some(path) = current_path {
        let is_main = entries.is_empty();
        entries.push(WorktreeEntry {
            path,
            branch: current_branch,
            is_main,
        });
    }

    Ok(entries)
}

/// Spawn a new worktree with a random branch name (or caller-provided name).
///
/// - Validates we're in a git repo
/// - Generates a random adjective-noun-N branch name if none provided
/// - Runs `git worktree add -b <branch> <path>`
/// - Rsyncs gitignored files from main repo to worktree
/// - Worktree location: `<base_path>/<project>/<branch>/`
pub fn spawn(options: &SpawnOptions<'_>) -> Result<SpawnResult, WorktreeError> {
    // Validate git repo
    if !git_status(options.repo_path, &["rev-parse", "--git-dir"])? {
        return Err(WorktreeError::NotGitRepo);
    }

    let branch = match options.branch {
        Some(b) => b.to_string(),
        None => generate_branch_name(),
    };

    // Check branch doesn't already exist
    if git_status(
        options.repo_path,
        &[
            "show-ref",
            "--verify",
            "--quiet",
            &format!("refs/heads/{branch}"),
        ],
    )? {
        return Err(WorktreeError::BranchExists(branch));
    }

    // Find main worktree to get project name
    let (main_path, _) = find_main_worktree(options.repo_path)?;
    let project = main_path
        .file_name()
        .and_then(|n| n.to_str())
        .ok_or_else(|| WorktreeError::GitCommand("could not determine project name".into()))?;

    let worktree_path = options.base_path.join(project).join(&branch);

    // Create parent directory
    std::fs::create_dir_all(options.base_path.join(project))
        .map_err(|e| WorktreeError::GitCommand(format!("failed to create directory: {e}")))?;

    // Create worktree with new branch (from the main repo)
    let wt_str = path_str(&worktree_path)?;
    git(&main_path, &["worktree", "add", "-b", &branch, wt_str])?;

    // Copy gitignored files via rsync
    rsync_ignored(&main_path, &worktree_path)?;

    Ok(SpawnResult {
        worktree_path,
        branch,
    })
}

/// Land the worktree's branch onto the main branch.
///
/// - Validates we're in a secondary worktree with clean working tree
/// - Rebases current branch onto main
/// - Fast-forward merges main to current branch tip
///
/// Does NOT remove the worktree — the worktree persists for continued use.
/// Returns an error with conflict details if rebase fails.
pub fn land(worktree_path: &Path) -> Result<LandResult, WorktreeError> {
    let (main_path, main_branch) = find_main_worktree(worktree_path)?;

    // Check we're not in the main worktree
    let toplevel = git(worktree_path, &["rev-parse", "--show-toplevel"])?;
    if main_path == Path::new(toplevel.trim()) {
        return Err(WorktreeError::IsMainWorktree);
    }

    // Check for detached HEAD
    let current_branch = git(worktree_path, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let current_branch = current_branch.trim().to_string();
    if current_branch == "HEAD" {
        return Err(WorktreeError::DetachedHead);
    }

    // Check for uncommitted changes (staged or unstaged)
    if !git_status(worktree_path, &["diff", "--quiet"])? {
        return Err(WorktreeError::DirtyWorkingTree);
    }
    if !git_status(worktree_path, &["diff", "--cached", "--quiet"])? {
        return Err(WorktreeError::DirtyWorkingTree);
    }

    // Check for untracked files
    let untracked = git(
        worktree_path,
        &["ls-files", "--others", "--exclude-standard"],
    )?;
    if !untracked.trim().is_empty() {
        return Err(WorktreeError::UntrackedFiles);
    }

    // Rebase onto main
    let rebase_output = Command::new("git")
        .arg("-C")
        .arg(worktree_path)
        .args(["rebase", &main_branch])
        .output()
        .map_err(|e| WorktreeError::GitCommand(format!("failed to run git: {e}")))?;

    if !rebase_output.status.success() {
        let conflicts =
            git(worktree_path, &["diff", "--name-only", "--diff-filter=U"]).unwrap_or_default();
        let conflict_files: Vec<String> = conflicts
            .lines()
            .filter(|l| !l.is_empty())
            .map(String::from)
            .collect();

        if conflict_files.is_empty() {
            let stderr = String::from_utf8_lossy(&rebase_output.stderr);
            return Err(WorktreeError::GitCommand(format!(
                "rebase failed: {}",
                stderr.trim()
            )));
        }

        return Err(WorktreeError::RebaseConflict(conflict_files));
    }

    // Fast-forward merge main to current branch tip
    if !git_status(&main_path, &["merge", "--ff-only", &current_branch])? {
        return Err(WorktreeError::FastForwardFailed);
    }

    Ok(LandResult {
        branch: current_branch,
        main_branch,
    })
}

/// Remove a worktree and delete its branch.
///
/// - Runs `git worktree remove <path>`
/// - Deletes the branch
///
/// Intended for worker shutdown, not after every land.
pub fn remove(worktree_path: &Path) -> Result<(), WorktreeError> {
    let branch = git(worktree_path, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let branch = branch.trim().to_string();

    let (main_path, _) = find_main_worktree(worktree_path)?;

    let wt_str = path_str(worktree_path)?;
    git(&main_path, &["worktree", "remove", wt_str])?;

    // Delete the branch (ignore errors — branch may already be gone)
    let _ = git(&main_path, &["branch", "-d", &branch]);

    Ok(())
}

/// Update the worktree branch to include the latest commits from main.
///
/// If the worktree has no unique commits (normal state after landing),
/// this is a fast-forward. If the worktree has unique commits, they
/// are rebased onto main.
///
/// Call this before dispatch so the agent sees the latest issue files.
pub fn sync_to_main(worktree_path: &Path) -> Result<(), WorktreeError> {
    let (_, main_branch) = find_main_worktree(worktree_path)?;
    git(worktree_path, &["rebase", &main_branch])?;
    Ok(())
}

/// Reset the worktree branch to main's tip, discarding any local commits.
///
/// Used after a failed land to put the worktree back in a clean state
/// so the next dispatch can start fresh.
pub fn reset_to_main(worktree_path: &Path) -> Result<(), WorktreeError> {
    let (_, main_branch) = find_main_worktree(worktree_path)?;
    git(worktree_path, &["reset", "--hard", &main_branch])?;
    Ok(())
}

/// Abort a failed rebase in the given worktree.
pub fn abort_rebase(worktree_path: &Path) -> Result<(), WorktreeError> {
    git(worktree_path, &["rebase", "--abort"])?;
    Ok(())
}

/// Remove untracked, non-ignored files and directories from the worktree.
///
/// Runs `git clean -fd`. Gitignored files (build artifacts, etc.) are preserved.
/// Used during land failure recovery to prevent stray files from blocking
/// future land attempts.
pub fn clean(worktree_path: &Path) -> Result<(), WorktreeError> {
    git(worktree_path, &["clean", "-fd"])?;
    Ok(())
}

/// Check whether the worktree branch has any commits ahead of main.
pub fn has_unique_commits(worktree_path: &Path) -> Result<bool, WorktreeError> {
    let (_, main_branch) = find_main_worktree(worktree_path)?;
    let output = git(
        worktree_path,
        &["rev-list", "--count", &format!("{main_branch}..HEAD")],
    )?;
    let count: u64 = output
        .trim()
        .parse()
        .map_err(|e| WorktreeError::GitCommand(format!("failed to parse rev-list count: {e}")))?;
    Ok(count > 0)
}

/// Check if a rebase is currently in progress in the worktree.
pub fn is_rebase_in_progress(worktree_path: &Path) -> Result<bool, WorktreeError> {
    let git_dir_output = git(worktree_path, &["rev-parse", "--git-dir"])?;
    let git_dir = PathBuf::from(git_dir_output.trim());
    Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())
}

/// Fast-forward merge main to the worktree branch tip.
///
/// Use after resolving rebase conflicts externally (e.g., via a resumed Claude
/// session) to complete the landing process. Only the ff-merge step — assumes
/// the rebase is already complete.
pub fn ff_merge_main(worktree_path: &Path) -> Result<LandResult, WorktreeError> {
    let (main_path, main_branch) = find_main_worktree(worktree_path)?;

    let current_branch = git(worktree_path, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    let current_branch = current_branch.trim().to_string();

    if !git_status(&main_path, &["merge", "--ff-only", &current_branch])? {
        return Err(WorktreeError::FastForwardFailed);
    }

    Ok(LandResult {
        branch: current_branch,
        main_branch,
    })
}

// ── Private helpers ─────────────────────────────────────────────────────

fn rsync_ignored(main_path: &Path, worktree_path: &Path) -> Result<(), WorktreeError> {
    let ignored = git(
        main_path,
        &[
            "ls-files",
            "--others",
            "--ignored",
            "--exclude-standard",
            "--directory",
        ],
    )?;

    if ignored.trim().is_empty() {
        return Ok(());
    }

    let mut child = Command::new("rsync")
        .arg("-a")
        .arg("--files-from=-")
        .arg(format!("{}/", main_path.display()))
        .arg(format!("{}/", worktree_path.display()))
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| WorktreeError::GitCommand(format!("failed to run rsync: {e}")))?;

    if let Some(mut stdin) = child.stdin.take() {
        // Write and drop to signal EOF; ignore broken pipe (some files may not exist)
        let _ = stdin.write_all(ignored.as_bytes());
    }

    // Non-fatal: rsync may warn about missing gitignored files
    let _ = child.wait();

    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Initialize a git repo with an initial commit.
    fn init_repo(dir: &Path) {
        git(dir, &["init"]).unwrap();
        git(dir, &["config", "user.email", "test@test.com"]).unwrap();
        git(dir, &["config", "user.name", "Test"]).unwrap();
        fs::write(dir.join("README.md"), "# test repo\n").unwrap();
        git(dir, &["add", "."]).unwrap();
        git(dir, &["commit", "-m", "initial commit"]).unwrap();
    }

    /// Create a file, add, and commit.
    fn commit_file(dir: &Path, name: &str, content: &str, message: &str) {
        let file_path = dir.join(name);
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent).unwrap();
        }
        fs::write(&file_path, content).unwrap();
        git(dir, &["add", name]).unwrap();
        git(dir, &["commit", "-m", message]).unwrap();
    }

    fn spawn_opts<'a>(repo: &'a Path, base: &'a Path, branch: Option<&'a str>) -> SpawnOptions<'a> {
        SpawnOptions {
            repo_path: repo,
            branch,
            base_path: base,
        }
    }

    #[test]
    fn spawn_creates_worktree() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let result = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("test-branch"),
        ));
        let result = result.unwrap();

        assert_eq!(result.branch, "test-branch");
        assert!(result.worktree_path.exists());
        assert!(result.worktree_path.join("README.md").exists());
    }

    #[test]
    fn spawn_copies_gitignored_files() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        // Create a .gitignore and an ignored file
        fs::write(repo_dir.path().join(".gitignore"), "build/\n").unwrap();
        git(repo_dir.path(), &["add", ".gitignore"]).unwrap();
        git(repo_dir.path(), &["commit", "-m", "add gitignore"]).unwrap();

        fs::create_dir_all(repo_dir.path().join("build")).unwrap();
        fs::write(repo_dir.path().join("build/output.txt"), "compiled stuff\n").unwrap();

        let result = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("wt-ignored"),
        ));
        let result = result.unwrap();

        assert!(result.worktree_path.join("build/output.txt").exists());
    }

    #[test]
    fn spawn_custom_branch_name() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let result = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("my-feature"),
        ));
        let result = result.unwrap();

        assert_eq!(result.branch, "my-feature");
        assert!(result.worktree_path.ends_with("my-feature"));
    }

    #[test]
    fn spawn_duplicate_branch_errors() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        // Create a branch
        git(repo_dir.path(), &["branch", "existing-branch"]).unwrap();

        let result = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("existing-branch"),
        ));

        assert!(
            matches!(result, Err(WorktreeError::BranchExists(ref b)) if b == "existing-branch")
        );
    }

    #[test]
    fn land_clean_rebase() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("feature"),
        ));
        let spawned = spawned.unwrap();

        // Commit in the worktree
        commit_file(&spawned.worktree_path, "new.txt", "hello\n", "add new file");

        // Land
        let landed = land(&spawned.worktree_path).unwrap();
        assert_eq!(landed.branch, "feature");

        // Verify main has the commit
        let log = git(repo_dir.path(), &["log", "--oneline"]).unwrap();
        assert!(log.contains("add new file"));

        // Verify worktree still exists
        assert!(spawned.worktree_path.exists());
    }

    #[test]
    fn land_with_conflict() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("conflict-branch"),
        ));
        let spawned = spawned.unwrap();

        // Commit conflicting change on main
        commit_file(repo_dir.path(), "file.txt", "main content\n", "main change");

        // Commit conflicting change in worktree
        commit_file(
            &spawned.worktree_path,
            "file.txt",
            "worktree content\n",
            "worktree change",
        );

        let result = land(&spawned.worktree_path);
        assert!(
            matches!(result, Err(WorktreeError::RebaseConflict(ref files)) if files.contains(&"file.txt".to_string()))
        );

        // Clean up the rebase state
        abort_rebase(&spawned.worktree_path).unwrap();
    }

    #[test]
    fn land_dirty_worktree_errors() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("dirty-branch"),
        ));
        let spawned = spawned.unwrap();

        // Modify a file without committing
        fs::write(spawned.worktree_path.join("README.md"), "modified\n").unwrap();

        let result = land(&spawned.worktree_path);
        assert!(matches!(result, Err(WorktreeError::DirtyWorkingTree)));
    }

    #[test]
    fn abort_rebase_restores_clean_state() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("abort-branch"),
        ));
        let spawned = spawned.unwrap();

        // Create a conflict
        commit_file(repo_dir.path(), "conflict.txt", "main\n", "main side");
        commit_file(
            &spawned.worktree_path,
            "conflict.txt",
            "worktree\n",
            "wt side",
        );

        let result = land(&spawned.worktree_path);
        assert!(matches!(result, Err(WorktreeError::RebaseConflict(_))));

        // Abort the rebase
        abort_rebase(&spawned.worktree_path).unwrap();

        // Verify clean state — diff should be quiet
        assert!(git_status(&spawned.worktree_path, &["diff", "--quiet"]).unwrap());
    }

    #[test]
    fn sync_to_main_picks_up_new_commits() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("sync-branch"),
        ))
        .unwrap();

        // Commit on main after the worktree was spawned
        commit_file(
            repo_dir.path(),
            "new-on-main.txt",
            "from main\n",
            "main commit",
        );

        // Worktree doesn't have the file yet
        assert!(!spawned.worktree_path.join("new-on-main.txt").exists());

        // Sync picks it up
        sync_to_main(&spawned.worktree_path).unwrap();
        assert!(spawned.worktree_path.join("new-on-main.txt").exists());
    }

    #[test]
    fn sync_to_main_noop_when_up_to_date() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("sync-noop"),
        ))
        .unwrap();

        // Sync when already up to date should succeed
        sync_to_main(&spawned.worktree_path).unwrap();
    }

    #[test]
    fn reset_to_main_discards_local_commits() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("reset-branch"),
        ))
        .unwrap();

        // Make a commit in the worktree
        commit_file(
            &spawned.worktree_path,
            "local.txt",
            "local\n",
            "local commit",
        );
        assert!(spawned.worktree_path.join("local.txt").exists());

        // Reset to main
        reset_to_main(&spawned.worktree_path).unwrap();

        // Local file should be gone
        assert!(!spawned.worktree_path.join("local.txt").exists());
    }

    #[test]
    fn reset_to_main_after_conflict_abort() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("reset-conflict"),
        ))
        .unwrap();

        // Create a conflict
        commit_file(repo_dir.path(), "file.txt", "main\n", "main side");
        commit_file(&spawned.worktree_path, "file.txt", "worktree\n", "wt side");

        // Land fails with conflict
        let result = land(&spawned.worktree_path);
        assert!(matches!(result, Err(WorktreeError::RebaseConflict(_))));

        // Abort rebase, then reset to main
        abort_rebase(&spawned.worktree_path).unwrap();
        reset_to_main(&spawned.worktree_path).unwrap();

        // Worktree should now have main's version
        let content = fs::read_to_string(spawned.worktree_path.join("file.txt")).unwrap();
        assert_eq!(content, "main\n");
    }

    #[test]
    fn clean_removes_untracked_files() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("clean-branch"),
        ))
        .unwrap();

        // Create untracked files
        fs::write(spawned.worktree_path.join("stray.txt"), "leftover\n").unwrap();
        fs::create_dir_all(spawned.worktree_path.join("stray-dir")).unwrap();
        fs::write(
            spawned.worktree_path.join("stray-dir/nested.txt"),
            "nested\n",
        )
        .unwrap();

        assert!(spawned.worktree_path.join("stray.txt").exists());
        assert!(spawned.worktree_path.join("stray-dir/nested.txt").exists());

        clean(&spawned.worktree_path).unwrap();

        assert!(!spawned.worktree_path.join("stray.txt").exists());
        assert!(!spawned.worktree_path.join("stray-dir").exists());
        // Tracked files should still be there
        assert!(spawned.worktree_path.join("README.md").exists());
    }

    #[test]
    fn clean_preserves_gitignored_files() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        // Add a .gitignore
        fs::write(repo_dir.path().join(".gitignore"), "build/\n").unwrap();
        git(repo_dir.path(), &["add", ".gitignore"]).unwrap();
        git(repo_dir.path(), &["commit", "-m", "add gitignore"]).unwrap();

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("clean-ignore"),
        ))
        .unwrap();

        // Create an ignored directory and an untracked file
        fs::create_dir_all(spawned.worktree_path.join("build")).unwrap();
        fs::write(spawned.worktree_path.join("build/output.bin"), "binary\n").unwrap();
        fs::write(spawned.worktree_path.join("stray.txt"), "leftover\n").unwrap();

        clean(&spawned.worktree_path).unwrap();

        // Untracked file should be removed
        assert!(!spawned.worktree_path.join("stray.txt").exists());
        // Gitignored file should be preserved
        assert!(spawned.worktree_path.join("build/output.bin").exists());
    }

    #[test]
    fn ff_merge_after_manual_conflict_resolution() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("ff-resolve"),
        ))
        .unwrap();

        // Create a conflict
        commit_file(repo_dir.path(), "file.txt", "main\n", "main side");
        commit_file(&spawned.worktree_path, "file.txt", "worktree\n", "wt side");

        // Land fails with conflict (rebase in progress)
        let result = land(&spawned.worktree_path);
        assert!(matches!(result, Err(WorktreeError::RebaseConflict(_))));
        assert!(is_rebase_in_progress(&spawned.worktree_path).unwrap());

        // Simulate conflict resolution: pick worktree's version
        fs::write(spawned.worktree_path.join("file.txt"), "resolved\n").unwrap();
        git(&spawned.worktree_path, &["add", "file.txt"]).unwrap();
        git(&spawned.worktree_path, &["rebase", "--continue"]).unwrap();

        // Rebase should be complete
        assert!(!is_rebase_in_progress(&spawned.worktree_path).unwrap());

        // Now ff-merge should succeed
        let landed = ff_merge_main(&spawned.worktree_path).unwrap();
        assert_eq!(landed.branch, "ff-resolve");

        // Main should have the resolved content
        let content = fs::read_to_string(repo_dir.path().join("file.txt")).unwrap();
        assert_eq!(content, "resolved\n");
    }

    #[test]
    fn is_rebase_in_progress_false_normally() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("no-rebase"),
        ))
        .unwrap();

        assert!(!is_rebase_in_progress(&spawned.worktree_path).unwrap());
    }

    #[test]
    fn has_unique_commits_true_when_ahead() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("unique-commits"),
        ))
        .unwrap();

        // No unique commits initially
        assert!(!has_unique_commits(&spawned.worktree_path).unwrap());

        // Make a commit in the worktree
        commit_file(&spawned.worktree_path, "new.txt", "hello\n", "add file");

        // Now has unique commits
        assert!(has_unique_commits(&spawned.worktree_path).unwrap());
    }

    #[test]
    fn has_unique_commits_false_after_land() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("unique-land"),
        ))
        .unwrap();

        commit_file(&spawned.worktree_path, "new.txt", "hello\n", "add file");
        assert!(has_unique_commits(&spawned.worktree_path).unwrap());

        land(&spawned.worktree_path).unwrap();

        // After landing, worktree branch and main are at the same tip
        assert!(!has_unique_commits(&spawned.worktree_path).unwrap());
    }

    #[test]
    fn remove_worktree() {
        let repo_dir = TempDir::new().unwrap();
        let base_dir = TempDir::new().unwrap();
        init_repo(repo_dir.path());

        let spawned = spawn(&spawn_opts(
            repo_dir.path(),
            base_dir.path(),
            Some("rm-branch"),
        ));
        let spawned = spawned.unwrap();

        assert!(spawned.worktree_path.exists());

        remove(&spawned.worktree_path).unwrap();

        // Directory should be gone
        assert!(!spawned.worktree_path.exists());

        // Branch should be gone
        let branch_check = git_status(
            repo_dir.path(),
            &["show-ref", "--verify", "--quiet", "refs/heads/rm-branch"],
        )
        .unwrap();
        assert!(!branch_check);
    }
}