sprit-mutilagent 0.3.2

A robust command-line toolkit for managing multiple AI coding agents in isolated tmux sessions with comprehensive workspace management and health monitoring
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
//! Git utility functions for the Sprite multi-agent workflow toolkit.
//!
//! This module provides functions for managing git repositories, worktrees,
//! branches, and other git operations needed for agent workspace management.

use crate::error::SpriteError;
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Get the current git repository root directory.
#[allow(dead_code)]
pub fn get_git_root() -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .with_context(|| "Failed to execute git command. Is git installed?")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to get git repository root",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let root_str = String::from_utf8_lossy(&output.stdout);
    Ok(PathBuf::from(root_str.trim()))
}

/// Get the current git branch name.
#[allow(dead_code)]
pub fn get_current_branch() -> Result<String> {
    get_current_branch_at(&std::env::current_dir()?)
}

/// Get the current git branch name at a specific path.
pub fn get_current_branch_at(path: &Path) -> Result<String> {
    let output = Command::new("git")
        .current_dir(path)
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .with_context(|| format!("Failed to get current git branch at {}", path.display()))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get current branch at {}", path.display()),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(branch)
}

/// Check if a git branch exists.
pub fn branch_exists(branch: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["rev-parse", "--verify", &format!("refs/heads/{}", branch)])
        .output()
        .with_context(|| "Failed to check if branch exists")?;

    Ok(output.status.success())
}

/// Create a new git branch.
pub fn create_branch(branch: &str) -> Result<()> {
    create_branch_from(branch, "HEAD")
}

/// Create a new git branch from a specific starting point.
pub fn create_branch_from(branch: &str, from: &str) -> Result<()> {
    if branch_exists(branch)? {
        return Err(SpriteError::git(format!("Branch '{}' already exists", branch)).into());
    }

    let output = Command::new("git")
        .args(["checkout", "-b", branch, from])
        .output()
        .with_context(|| format!("Failed to create branch '{}' from '{}'", branch, from))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to create branch '{}' from '{}'", branch, from),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Switch to an existing git branch.
#[allow(dead_code)]
pub fn switch_branch(branch: &str) -> Result<()> {
    switch_branch_at(&std::env::current_dir()?, branch)
}

/// Switch to an existing git branch at a specific path.
pub fn switch_branch_at(path: &Path, branch: &str) -> Result<()> {
    if !branch_exists(branch)? {
        return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
    }

    let output = Command::new("git")
        .current_dir(path)
        .args(["checkout", branch])
        .output()
        .with_context(|| {
            format!(
                "Failed to switch to branch '{}' at {}",
                branch,
                path.display()
            )
        })?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!(
                "Failed to switch to branch '{}' at {}",
                branch,
                path.display()
            ),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Checkout a branch in a specific path.
pub fn checkout_branch(path: &Path, branch: &str) -> Result<()> {
    switch_branch_at(path, branch)
}

/// Create a git worktree for an agent.
pub fn create_worktree(path: &Path, branch: &str) -> Result<()> {
    // Ensure the parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).with_context(|| {
            format!(
                "Failed to create parent directory for worktree: {}",
                parent.display()
            )
        })?;
    }

    // Check if branch exists first
    if !branch_exists(branch)? {
        create_branch(branch)?;
    }

    // Try to create worktree with existing branch first
    let output = Command::new("git")
        .args(["worktree", "add", path.to_string_lossy().as_ref(), branch])
        .output()
        .with_context(|| format!("Failed to create worktree at '{}'", path.display()))?;

    if output.status.success() {
        return Ok(());
    }

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

    // If the worktree creation failed because the branch already exists and has stale references,
    // try to clean up and use force
    if stderr.contains("already exists") || stderr.contains("a branch named") {
        // Clean up any stale references first
        prune_worktrees()?;

        // Try with force flag
        let force_output = Command::new("git")
            .args([
                "worktree",
                "add",
                "--force",
                path.to_string_lossy().as_ref(),
                branch,
            ])
            .output()
            .with_context(|| {
                format!(
                    "Failed to create worktree with force at '{}'",
                    path.display()
                )
            })?;

        if force_output.status.success() {
            return Ok(());
        }
    }

    // If all attempts failed, return the original error
    Err(SpriteError::git_with_source(
        format!("Failed to create worktree at '{}'", path.display()),
        stderr,
    )
    .into())
}

/// Remove a git worktree.
pub fn remove_worktree(path: &Path) -> Result<()> {
    // Check if path exists and is a worktree
    if !path.exists() {
        return Err(
            SpriteError::git(format!("Worktree path does not exist: {}", path.display())).into(),
        );
    }

    let output = Command::new("git")
        .args(["worktree", "remove", path.to_string_lossy().as_ref()])
        .output()
        .with_context(|| format!("Failed to remove worktree at '{}'", path.display()))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to remove worktree at '{}'", path.display()),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    // Try to remove the directory if it still exists
    if path.exists() {
        std::fs::remove_dir_all(path)
            .with_context(|| format!("Failed to remove worktree directory: {}", path.display()))?;
    }

    Ok(())
}

/// List all git worktrees in the repository.
pub fn list_worktrees() -> Result<Vec<WorktreeInfo>> {
    let output = Command::new("git")
        .args(["worktree", "list"])
        .output()
        .with_context(|| "Failed to list worktrees")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to list worktrees",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let worktrees_str = String::from_utf8_lossy(&output.stdout);
    parse_worktree_list(&worktrees_str)
}

/// Information about a git worktree.
#[derive(Debug, Clone)]
pub struct WorktreeInfo {
    /// Path to the worktree
    pub path: PathBuf,
    /// Branch name
    #[allow(dead_code)]
    pub branch: String,
    /// Whether the worktree is bare
    #[allow(dead_code)]
    pub bare: bool,
    /// Worktree ID (for detached HEAD worktrees)
    #[allow(dead_code)]
    pub id: Option<String>,
}

/// Parse the output of `git worktree list`.
fn parse_worktree_list(output: &str) -> Result<Vec<WorktreeInfo>> {
    let mut worktrees = Vec::new();

    for line in output.lines() {
        if line.trim().is_empty() {
            continue;
        }

        // Parse worktree list format
        // Format: <path> [<branch> (<id>)]
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }

        let path = PathBuf::from(parts[0]);
        let (branch, id, bare) = if parts.len() > 1 {
            // Check if this is a bare worktree
            if parts.len() == 2 && parts[1].starts_with('(') && parts[1].ends_with(')') {
                (String::new(), None, true)
            } else if parts.len() >= 3 {
                // Format: path branch id or path branch (something)
                if parts[2].starts_with('(') {
                    // This is a special marker like (bare), not an ID
                    (parts[1].to_string(), None, parts[2].contains("bare"))
                } else {
                    // Format: path branch id
                    (parts[1].to_string(), Some(parts[2].to_string()), false)
                }
            } else {
                // Format: path branch or path branch [id]
                let branch_part = parts[1];
                let (branch, id_part) = branch_part.split_once(' ').unwrap_or((branch_part, ""));

                let id = if !id_part.is_empty() {
                    Some(id_part.to_string())
                } else {
                    None
                };

                (branch.trim().to_string(), id, false)
            }
        } else {
            (String::new(), None, false)
        };

        worktrees.push(WorktreeInfo {
            path,
            branch,
            bare,
            id,
        });
    }

    Ok(worktrees)
}

/// Check if the current directory is a git repository.
pub fn is_git_repository() -> Result<bool> {
    is_git_repository_at(&std::env::current_dir()?)
}

/// Check if a specific path is a git repository.
pub fn is_git_repository_at(path: &Path) -> Result<bool> {
    let output = Command::new("git")
        .current_dir(path)
        .args(["rev-parse", "--git-dir"])
        .output()
        .with_context(|| format!("Failed to execute git command at {}", path.display()))?;

    Ok(output.status.success())
}

/// Validate that we're in a git repository.
pub fn validate_git_repository() -> Result<()> {
    if !is_git_repository()? {
        return Err(SpriteError::config(
            "Not a git repository. Sprite must be run from within a git repository.",
        )
        .into());
    }
    Ok(())
}

/// Get the git repository status.
#[allow(dead_code)]
pub fn get_status() -> Result<GitStatus> {
    get_status_at(&std::env::current_dir()?)
}

/// Get the git repository status as a string.
#[allow(dead_code)]
pub fn get_status_string() -> Result<String> {
    get_status_string_at(&std::env::current_dir()?)
}

/// Get the git repository status at a specific path.
#[allow(dead_code)]
pub fn get_status_at(path: &Path) -> Result<GitStatus> {
    let output = Command::new("git")
        .current_dir(path)
        .args(["status", "--porcelain"])
        .output()
        .with_context(|| format!("Failed to get git status at {}", path.display()))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get git status at {}", path.display()),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let status_str = String::from_utf8_lossy(&output.stdout);
    parse_git_status(&status_str)
}

/// Get the git repository status as a string at a specific path.
pub fn get_status_string_at(path: &Path) -> Result<String> {
    let output = Command::new("git")
        .current_dir(path)
        .args(["status", "--porcelain"])
        .output()
        .with_context(|| format!("Failed to get git status string at {}", path.display()))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get git status string at {}", path.display()),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let status_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(status_str)
}

/// Git repository status information.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GitStatus {
    /// Number of modified files
    pub modified: usize,
    /// Number of added files
    pub added: usize,
    /// Number of deleted files
    pub deleted: usize,
    /// Number of untracked files
    pub untracked: usize,
    /// Whether there are any changes
    pub has_changes: bool,
}

/// Parse the output of `git status --porcelain`.
#[allow(dead_code)]
fn parse_git_status(output: &str) -> Result<GitStatus> {
    let mut status = GitStatus {
        modified: 0,
        added: 0,
        deleted: 0,
        untracked: 0,
        has_changes: false,
    };

    for line in output.lines() {
        if line.trim().is_empty() {
            continue;
        }

        let first_char = line.chars().next().unwrap_or(' ');
        let second_char = line.chars().nth(1).unwrap_or(' ');

        match (first_char, second_char) {
            // Modified files (staged or unstaged)
            ('M', _) | ('A', 'M') | ('R', 'M') => status.modified += 1,
            (' ', 'M') => status.modified += 1, // Unstaged modifications
            // Added files
            ('A', _) | ('R', 'A') | ('C', 'A') => status.added += 1,
            // Deleted files
            ('D', _) | ('C', 'D') => status.deleted += 1,
            (' ', 'D') => status.deleted += 1, // Unstaged deletions
            // Untracked files
            ('?', _) => status.untracked += 1,
            _ => {}
        }
    }

    status.has_changes = status.modified + status.added + status.deleted + status.untracked > 0;

    Ok(status)
}

/// Pull changes from the remote repository.
#[allow(dead_code)]
pub fn pull() -> Result<()> {
    let output = Command::new("git")
        .args(["pull"])
        .output()
        .with_context(|| "Failed to pull changes")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to pull changes",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Push changes to the remote repository.
#[allow(dead_code)]
pub fn push(branch: Option<&str>) -> Result<()> {
    let mut args = vec!["push"];
    if let Some(b) = branch {
        args.extend(&["origin", b]);
    }

    let output = Command::new("git")
        .args(&args)
        .output()
        .with_context(|| "Failed to push changes")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to push changes",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Commit changes with a message.
#[allow(dead_code)]
pub fn commit(message: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["commit", "-m", message])
        .output()
        .with_context(|| "Failed to commit changes")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to commit changes",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Add files to git staging area.
#[allow(dead_code)]
pub fn add(files: &[&Path]) -> Result<()> {
    let mut args: Vec<String> = vec!["add".to_string()];
    for file in files {
        args.push(file.to_string_lossy().into_owned());
    }

    let output = Command::new("git")
        .args(&args)
        .output()
        .with_context(|| "Failed to add files to git")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to add files to git",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Check if a file has uncommitted changes.
#[allow(dead_code)]
pub fn has_uncommitted_changes(path: &Path) -> Result<bool> {
    let output = Command::new("git")
        .args([
            "diff",
            "--quiet",
            "--exit-code",
            path.to_string_lossy().as_ref(),
        ])
        .output()
        .with_context(|| "Failed to check for uncommitted changes")?;

    // Exit code 1 means there are changes, 0 means no changes
    Ok(output.status.code() == Some(1))
}

/// Get the current git commit hash.
#[allow(dead_code)]
pub fn get_current_commit() -> Result<String> {
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .with_context(|| "Failed to get current commit hash")?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            "Failed to get current commit hash",
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(commit)
}

/// Get the git remote URL.
#[allow(dead_code)]
pub fn get_remote_url(remote: Option<&str>) -> Result<String> {
    let remote_name = remote.unwrap_or("origin");

    let output = Command::new("git")
        .args(["remote", "get-url", remote_name])
        .output()
        .with_context(|| format!("Failed to get remote URL for '{}'", remote_name))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get remote URL for '{}'", remote_name),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(url)
}

/// Delete a git branch.
pub fn delete_branch(branch: &str, force: bool) -> Result<()> {
    if !branch_exists(branch)? {
        return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
    }

    let mut args = vec!["branch", "-d"];
    if force {
        args.push("-D");
    }
    args.push(branch);

    let output = Command::new("git")
        .args(&args)
        .output()
        .with_context(|| format!("Failed to delete branch '{}'", branch))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to delete branch '{}'", branch),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Check if a branch has been merged into the current branch.
pub fn is_branch_merged(branch: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["merge-base", "--is-ancestor", branch, "HEAD"])
        .output()
        .with_context(|| format!("Failed to check if branch '{}' is merged", branch))?;

    Ok(output.status.success())
}

/// Get a list of all branches that contain the given commit.
#[allow(dead_code)]
pub fn get_branches_containing_commit(commit: &str) -> Result<Vec<String>> {
    let output = Command::new("git")
        .args(["branch", "--contains", commit])
        .output()
        .with_context(|| format!("Failed to get branches containing commit '{}'", commit))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get branches containing commit '{}'", commit),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let branches_str = String::from_utf8_lossy(&output.stdout);
    let branches: Vec<String> = branches_str
        .lines()
        .map(|line| line.trim().trim_start_matches("* ").to_string())
        .filter(|s| !s.is_empty())
        .collect();

    Ok(branches)
}

/// Force remove a git branch, even if it has unmerged changes.
#[allow(dead_code)]
pub fn force_delete_branch(branch: &str) -> Result<()> {
    delete_branch(branch, true)
}

/// Safely remove a git branch, checking if it's merged first.
#[allow(dead_code)]
pub fn safe_delete_branch(branch: &str) -> Result<()> {
    if !is_branch_merged(branch)? {
        return Err(SpriteError::git(format!(
            "Branch '{}' has unmerged changes. Use --force to delete anyway.",
            branch
        ))
        .into());
    }

    delete_branch(branch, false)
}

/// Get the current commit hash of a branch.
#[allow(dead_code)]
pub fn get_branch_commit(branch: &str) -> Result<String> {
    let output = Command::new("git")
        .args(["rev-parse", &format!("refs/heads/{}", branch)])
        .output()
        .with_context(|| format!("Failed to get commit hash for branch '{}'", branch))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to get commit hash for branch '{}'", branch),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(commit)
}

/// Merge a branch into the current branch.
pub fn merge_branch(branch: &str) -> Result<()> {
    if !branch_exists(branch)? {
        return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
    }

    let output = Command::new("git")
        .args(["merge", "--no-ff", branch])
        .output()
        .with_context(|| format!("Failed to merge branch '{}'", branch))?;

    if !output.status.success() {
        return Err(SpriteError::git_with_source(
            format!("Failed to merge branch '{}'", branch),
            String::from_utf8_lossy(&output.stderr),
        )
        .into());
    }

    Ok(())
}

/// Check if there are merge conflicts after a merge operation.
pub fn has_merge_conflicts() -> Result<bool> {
    let output = Command::new("git")
        .args(["diff", "--name-only", "--diff-filter=U"])
        .output()
        .with_context(|| "Failed to check for merge conflicts")?;

    let conflicts_str = String::from_utf8_lossy(&output.stdout);
    Ok(!conflicts_str.trim().is_empty())
}

/// Prune stale worktree references.
pub fn prune_worktrees() -> Result<()> {
    let output = Command::new("git")
        .args(["worktree", "prune"])
        .output()
        .with_context(|| "Failed to prune worktrees")?;

    if !output.status.success() {
        // Don't fail on prune errors, just log them
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("⚠️  Warning: Failed to prune worktrees: {}", stderr);
    }

    Ok(())
}

/// Remove a worktree reference without removing the directory.
pub fn remove_worktree_reference(path: &Path) -> Result<()> {
    let output = Command::new("git")
        .args([
            "worktree",
            "remove",
            "--force",
            path.to_string_lossy().as_ref(),
        ])
        .output()
        .with_context(|| {
            format!(
                "Failed to remove worktree reference at '{}'",
                path.display()
            )
        })?;

    if !output.status.success() {
        // If remove fails, try prune instead
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!(
            "⚠️  Warning: Failed to remove worktree reference: {}. Trying prune...",
            stderr
        );
        prune_worktrees()?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_worktree_list() {
        let input = r#"
/path/to/worktree feature/branch
/path/to/another main abc123
/path/to/bare (bare)
"#;

        let worktrees = parse_worktree_list(input).unwrap();
        assert_eq!(worktrees.len(), 3);

        assert_eq!(worktrees[0].path, PathBuf::from("/path/to/worktree"));
        assert_eq!(worktrees[0].branch, "feature/branch");
        assert!(!worktrees[0].bare);
        assert_eq!(worktrees[0].id, None);

        assert_eq!(worktrees[1].path, PathBuf::from("/path/to/another"));
        assert_eq!(worktrees[1].branch, "main");
        assert!(!worktrees[1].bare);
        assert_eq!(worktrees[1].id, Some("abc123".to_string()));

        assert_eq!(worktrees[2].path, PathBuf::from("/path/to/bare"));
        assert!(worktrees[2].bare);
    }

    #[test]
    fn test_parse_git_status() {
        let input = r#"
 M src/main.rs
A src/new_file.rs
 D src/old_file.rs
?? untracked.txt
"#;

        let status = parse_git_status(input).unwrap();
        assert_eq!(status.modified, 1);
        assert_eq!(status.added, 1);
        assert_eq!(status.deleted, 1);
        assert_eq!(status.untracked, 1);
        assert!(status.has_changes);
    }

    #[test]
    fn test_validate_git_repository() {
        // This test depends on being run in a git repository
        // In actual usage, this would be tested in a proper git repository
        let _result = is_git_repository();
        // We don't assert the result since it depends on the test environment
    }
}