vibe-workspace 0.0.12

Extremely lightweight CLI for managing multiple git repositories and workspace configurations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! Worktree status tracking and reporting

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
use tokio::process::Command;
use tracing::debug;

use crate::worktree::config::WorktreeMergeDetectionConfig;
use crate::worktree::merge_detection::detect_worktree_merge_status;

/// Comprehensive information about a Git worktree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorktreeInfo {
    /// Path to the worktree directory
    pub path: PathBuf,

    /// Branch name associated with this worktree
    pub branch: String,

    /// Current HEAD commit SHA
    pub head: String,

    /// Task identifier used to create this worktree (if available)
    pub task_id: Option<String>,

    /// Detailed status information
    pub status: WorktreeStatus,

    /// Age of the worktree directory
    pub age: Duration,

    /// Whether this worktree is detached HEAD
    pub is_detached: bool,
}

/// Detailed status information for a worktree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorktreeStatus {
    /// Overall cleanliness of the worktree
    pub is_clean: bool,

    /// Severity level for UI display
    pub severity: StatusSeverity,

    /// List of uncommitted changed files
    pub uncommitted_changes: Vec<String>,

    /// List of untracked files
    pub untracked_files: Vec<String>,

    /// List of unpushed commits
    pub unpushed_commits: Vec<CommitInfo>,

    /// Remote branch tracking status
    pub remote_status: RemoteStatus,

    /// Merge detection information
    pub merge_info: Option<MergeInfo>,

    /// Number of commits ahead of remote
    pub ahead_count: usize,

    /// Number of commits behind remote
    pub behind_count: usize,
}

/// Status severity levels for different types of issues
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatusSeverity {
    /// ✅ No issues - clean worktree with everything synced
    Clean,

    /// ⚠️ Light warning - worktree issues (uncommitted/unsynced)
    LightWarning,

    /// ⚡ Warning - feature branch issues (stale, conflicts, etc.)
    Warning,
}

/// Information about a commit
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommitInfo {
    /// Commit SHA (short form)
    pub id: String,

    /// Commit message (first line)
    pub message: String,

    /// Author name
    pub author: String,

    /// Commit timestamp
    pub timestamp: SystemTime,
}

/// Remote branch tracking status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RemoteStatus {
    /// No remote tracking branch configured
    NoRemote,

    /// Remote branch exists and is up to date
    UpToDate,

    /// Local is ahead of remote
    Ahead(usize),

    /// Local is behind remote
    Behind(usize),

    /// Both ahead and behind (diverged)
    Diverged { ahead: usize, behind: usize },

    /// Remote branch was deleted
    RemoteDeleted,
}

/// Information about merge status detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MergeInfo {
    /// Whether the branch appears to be merged
    pub is_merged: bool,

    /// Method used to detect the merge
    pub detection_method: String,

    /// Additional information about the merge
    pub details: Option<String>,

    /// Confidence level (0.0 to 1.0)
    pub confidence: f32,
}

impl WorktreeStatus {
    /// Create a new empty status
    pub fn new() -> Self {
        Self {
            is_clean: false,
            severity: StatusSeverity::Warning,
            uncommitted_changes: Vec::new(),
            untracked_files: Vec::new(),
            unpushed_commits: Vec::new(),
            remote_status: RemoteStatus::NoRemote,
            merge_info: None,
            ahead_count: 0,
            behind_count: 0,
        }
    }

    /// Check if this worktree is safe to clean up
    pub fn is_safe_to_cleanup(&self) -> bool {
        self.is_clean
            && self.uncommitted_changes.is_empty()
            && self.untracked_files.is_empty()
            && (self.unpushed_commits.is_empty()
                || self
                    .merge_info
                    .as_ref()
                    .map_or(false, |info| info.is_merged))
    }

    /// Get a user-friendly status description
    pub fn status_description(&self) -> String {
        if self.is_clean {
            match &self.merge_info {
                Some(info) if info.is_merged => format!("Clean ({})", info.detection_method),
                _ => "Clean".to_string(),
            }
        } else {
            let mut issues = Vec::new();

            if !self.uncommitted_changes.is_empty() {
                issues.push(format!("{} uncommitted", self.uncommitted_changes.len()));
            }

            if !self.untracked_files.is_empty() {
                issues.push(format!("{} untracked", self.untracked_files.len()));
            }

            if !self.unpushed_commits.is_empty() {
                issues.push(format!("{} unpushed", self.unpushed_commits.len()));
            }

            match &self.remote_status {
                RemoteStatus::NoRemote => issues.push("no remote".to_string()),
                RemoteStatus::Behind(count) => issues.push(format!("{} behind", count)),
                RemoteStatus::Diverged { ahead, behind } => {
                    issues.push(format!("{} ahead, {} behind", ahead, behind));
                }
                RemoteStatus::RemoteDeleted => issues.push("remote deleted".to_string()),
                _ => {}
            }

            if issues.is_empty() {
                "Unknown issue".to_string()
            } else {
                issues.join(", ")
            }
        }
    }

    /// Get the appropriate status icon
    pub fn status_icon(&self) -> &'static str {
        match self.severity {
            StatusSeverity::Clean => "",
            StatusSeverity::LightWarning => "⚠️",
            StatusSeverity::Warning => "",
        }
    }
}

impl Default for WorktreeStatus {
    fn default() -> Self {
        Self::new()
    }
}

impl StatusSeverity {
    /// Get numeric priority for sorting (lower is more severe)
    pub fn priority(&self) -> u8 {
        match self {
            StatusSeverity::Warning => 0,
            StatusSeverity::LightWarning => 1,
            StatusSeverity::Clean => 2,
        }
    }
}

impl WorktreeInfo {
    /// Update status information for this worktree
    pub async fn update_status(&mut self) -> Result<()> {
        self.status = check_worktree_status(&self.path).await?;
        self.update_age()?;
        Ok(())
    }

    /// Update the age of this worktree
    fn update_age(&mut self) -> Result<()> {
        if let Ok(metadata) = std::fs::metadata(&self.path) {
            if let Ok(created) = metadata.created() {
                self.age = std::time::SystemTime::now().duration_since(created)?;
            }
        }
        Ok(())
    }
}

/// Repository-level summary statistics for worktree management
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositoryWorktreeSummary {
    /// Total number of worktrees (including main)
    pub total_worktrees: usize,

    /// Number of clean worktrees
    pub clean_worktrees: usize,

    /// Number of worktrees with uncommitted changes
    pub dirty_worktrees: usize,

    /// Number of worktrees with remote tracking
    pub worktrees_with_remote: usize,

    /// Number of worktrees that appear merged
    pub merged_worktrees: usize,

    /// Number of worktrees with unpushed commits
    pub worktrees_with_unpushed: usize,

    /// Overall health score (0.0 to 1.0)
    pub health_score: f32,
}

impl RepositoryWorktreeSummary {
    /// Create summary from a list of worktrees
    pub fn from_worktrees(worktrees: &[WorktreeInfo]) -> Self {
        let total = worktrees.len();
        let clean = worktrees.iter().filter(|w| w.status.is_clean).count();
        let dirty = worktrees.iter().filter(|w| !w.status.is_clean).count();
        let with_remote = worktrees
            .iter()
            .filter(|w| !matches!(w.status.remote_status, RemoteStatus::NoRemote))
            .count();
        let merged = worktrees
            .iter()
            .filter(|w| {
                w.status
                    .merge_info
                    .as_ref()
                    .map_or(false, |info| info.is_merged)
            })
            .count();
        let with_unpushed = worktrees
            .iter()
            .filter(|w| !w.status.unpushed_commits.is_empty())
            .count();

        // Calculate health score based on cleanliness and remote tracking
        let health_score = if total == 0 {
            1.0
        } else {
            let clean_ratio = clean as f32 / total as f32;
            let remote_ratio = with_remote as f32 / total as f32;
            // Weight cleanliness more heavily than remote tracking
            clean_ratio * 0.7 + remote_ratio * 0.3
        };

        Self {
            total_worktrees: total,
            clean_worktrees: clean,
            dirty_worktrees: dirty,
            worktrees_with_remote: with_remote,
            merged_worktrees: merged,
            worktrees_with_unpushed: with_unpushed,
            health_score,
        }
    }

    /// Get a summary description string
    pub fn summary_description(&self) -> String {
        let mut parts = Vec::new();

        parts.push(format!("{} worktrees", self.total_worktrees));

        if self.dirty_worktrees > 0 {
            parts.push(format!("{} dirty", self.dirty_worktrees));
        }

        if self.worktrees_with_unpushed > 0 {
            parts.push(format!("{} unpushed", self.worktrees_with_unpushed));
        }

        if self.merged_worktrees > 0 {
            parts.push(format!("{} merged", self.merged_worktrees));
        }

        let remote_missing = self.total_worktrees - self.worktrees_with_remote;
        if remote_missing > 0 {
            parts.push(format!("{} no remote", remote_missing));
        }

        parts.join(", ")
    }

    /// Get health status icon
    pub fn health_icon(&self) -> &'static str {
        if self.health_score >= 0.8 {
            "🟢"
        } else if self.health_score >= 0.5 {
            "🟡"
        } else {
            "🔴"
        }
    }

    /// Get health description
    pub fn health_description(&self) -> String {
        if self.health_score >= 0.8 {
            "Healthy".to_string()
        } else if self.health_score >= 0.5 {
            "Needs attention".to_string()
        } else {
            "Unhealthy".to_string()
        }
    }
}

/// Check comprehensive status for a worktree
pub async fn check_worktree_status(worktree_path: &Path) -> Result<WorktreeStatus> {
    check_worktree_status_with_config(worktree_path, None).await
}

/// Check comprehensive status for a worktree with optional merge detection config
pub async fn check_worktree_status_with_config(
    worktree_path: &Path,
    merge_config: Option<&WorktreeMergeDetectionConfig>,
) -> Result<WorktreeStatus> {
    let mut status = WorktreeStatus::new();

    // Get basic git status (staged, unstaged, untracked files)
    let git_status = get_git_porcelain_status(worktree_path).await?;
    status.uncommitted_changes = git_status.changed_files;
    status.untracked_files = git_status.untracked_files;

    // Get remote status and commit information
    let remote_info = get_remote_status(worktree_path).await?;
    status.remote_status = remote_info.status;
    status.ahead_count = remote_info.ahead;
    status.behind_count = remote_info.behind;

    // Get unpushed commits
    if status.ahead_count > 0 {
        status.unpushed_commits = get_unpushed_commits(worktree_path).await?;
    }

    // Add merge detection if config is provided
    if let Some(config) = merge_config {
        if let Ok(current_branch) = get_current_branch(worktree_path).await {
            match detect_worktree_merge_status(worktree_path, &current_branch, config).await {
                Ok(merge_info) => {
                    status.merge_info = Some(merge_info);
                }
                Err(e) => {
                    debug!(
                        "Merge detection failed for branch '{}': {}",
                        current_branch, e
                    );
                    // Continue without merge info rather than failing
                }
            }
        }
    }

    // Determine overall cleanliness
    status.is_clean = status.uncommitted_changes.is_empty()
        && status.untracked_files.is_empty()
        && (status.ahead_count == 0 || matches!(status.remote_status, RemoteStatus::NoRemote));

    // Classify severity (now considering merge status)
    status.severity = classify_status_severity(&status);

    Ok(status)
}

/// Get git status in porcelain format for parsing
async fn get_git_porcelain_status(worktree_path: &Path) -> Result<GitStatusInfo> {
    let output = Command::new("git")
        .args(&["status", "--porcelain=v1", "-z"])
        .current_dir(worktree_path)
        .output()
        .await
        .with_context(|| format!("Failed to get git status for: {}", worktree_path.display()))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow::anyhow!("Git status failed: {}", stderr));
    }

    parse_porcelain_status(&output.stdout)
}

/// Parse git status porcelain output
fn parse_porcelain_status(output: &[u8]) -> Result<GitStatusInfo> {
    let output_str = String::from_utf8_lossy(output);
    let mut changed_files = Vec::new();
    let mut untracked_files = Vec::new();

    for line in output_str.split('\0') {
        if line.is_empty() {
            continue;
        }

        if line.len() < 3 {
            continue;
        }

        let status_code = &line[0..2];
        let file_path = &line[3..];

        match status_code {
            "??" => {
                untracked_files.push(file_path.to_string());
            }
            _ => {
                let status_desc = match status_code {
                    "M " => "modified (unstaged)",
                    " M" => "modified (staged)",
                    "MM" => "modified (both staged and unstaged)",
                    "A " => "added (staged)",
                    " A" => "added (unstaged)",
                    "D " => "deleted (staged)",
                    " D" => "deleted (unstaged)",
                    "R " => "renamed (staged)",
                    " R" => "renamed (unstaged)",
                    "C " => "copied (staged)",
                    " C" => "copied (unstaged)",
                    "U " | " U" | "UU" => "unmerged",
                    _ => "unknown",
                };

                changed_files.push(format!("{}: {}", status_desc, file_path));
            }
        }
    }

    Ok(GitStatusInfo {
        changed_files,
        untracked_files,
    })
}

/// Get remote branch status and ahead/behind counts
async fn get_remote_status(worktree_path: &Path) -> Result<RemoteInfo> {
    // First, check if there's a remote tracking branch
    let upstream_result = Command::new("git")
        .args(&["rev-parse", "--abbrev-ref", "@{u}"])
        .current_dir(worktree_path)
        .output()
        .await;

    let upstream_branch = match upstream_result {
        Ok(output) if output.status.success() => {
            Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
        }
        _ => None,
    };

    if upstream_branch.is_none() {
        return Ok(RemoteInfo {
            status: RemoteStatus::NoRemote,
            ahead: 0,
            behind: 0,
        });
    }

    // Get ahead/behind counts
    let count_output = Command::new("git")
        .args(&["rev-list", "--count", "--left-right", "@{u}...HEAD"])
        .current_dir(worktree_path)
        .output()
        .await?;

    if !count_output.status.success() {
        // Remote branch might be deleted
        return Ok(RemoteInfo {
            status: RemoteStatus::RemoteDeleted,
            ahead: 0,
            behind: 0,
        });
    }

    let count_str = String::from_utf8_lossy(&count_output.stdout);
    let counts: Vec<&str> = count_str.trim().split_whitespace().collect();

    let (behind, ahead) = if counts.len() >= 2 {
        let behind = counts[0].parse::<usize>().unwrap_or(0);
        let ahead = counts[1].parse::<usize>().unwrap_or(0);
        (behind, ahead)
    } else {
        (0, 0)
    };

    let status = match (ahead, behind) {
        (0, 0) => RemoteStatus::UpToDate,
        (a, 0) if a > 0 => RemoteStatus::Ahead(a),
        (0, b) if b > 0 => RemoteStatus::Behind(b),
        (a, b) if a > 0 && b > 0 => RemoteStatus::Diverged {
            ahead: a,
            behind: b,
        },
        _ => RemoteStatus::UpToDate,
    };

    Ok(RemoteInfo {
        status,
        ahead,
        behind,
    })
}

/// Get list of unpushed commits with details
async fn get_unpushed_commits(worktree_path: &Path) -> Result<Vec<CommitInfo>> {
    let output = Command::new("git")
        .args(&["log", "--oneline", "--format=%H|%s|%an|%ct", "@{u}..HEAD"])
        .current_dir(worktree_path)
        .output()
        .await?;

    if !output.status.success() {
        return Ok(Vec::new());
    }

    let output_str = String::from_utf8_lossy(&output.stdout);
    let mut commits = Vec::new();

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

        let parts: Vec<&str> = line.split('|').collect();
        if parts.len() >= 4 {
            let full_sha = parts[0];
            let short_sha = if full_sha.len() >= 7 {
                &full_sha[..7]
            } else {
                full_sha
            };

            let timestamp_secs = parts[3].parse::<u64>().unwrap_or(0);
            let timestamp = std::time::UNIX_EPOCH + std::time::Duration::from_secs(timestamp_secs);

            commits.push(CommitInfo {
                id: short_sha.to_string(),
                message: parts[1].to_string(),
                author: parts[2].to_string(),
                timestamp,
            });
        }
    }

    Ok(commits)
}

/// Get the current branch name
async fn get_current_branch(worktree_path: &Path) -> Result<String> {
    let output = Command::new("git")
        .args(&["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(worktree_path)
        .output()
        .await?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        Err(anyhow::anyhow!("Failed to get current branch"))
    }
}

/// Classify the overall severity of a worktree's status
fn classify_status_severity(status: &WorktreeStatus) -> StatusSeverity {
    // If branch is merged with high confidence, it's safer to clean
    if let Some(merge_info) = &status.merge_info {
        if merge_info.is_merged && merge_info.confidence > 0.8 {
            // Even with uncommitted changes, merged branches are less concerning
            if status.is_clean {
                return StatusSeverity::Clean;
            } else {
                return StatusSeverity::LightWarning;
            }
        }
    }

    // Clean status: everything is up to date
    if status.is_clean && status.ahead_count == 0 && status.behind_count == 0 {
        return StatusSeverity::Clean;
    }

    // Warning (⚡) - serious issues with the branch itself
    if matches!(status.remote_status, RemoteStatus::RemoteDeleted) {
        return StatusSeverity::Warning;
    }

    if status.behind_count > 10 {
        return StatusSeverity::Warning;
    }

    if let RemoteStatus::Diverged { ahead, behind } = status.remote_status {
        if behind > 5 || ahead > 20 {
            return StatusSeverity::Warning;
        }
    }

    // Light warning (⚠️) - typical worktree development issues
    if !status.uncommitted_changes.is_empty()
        || !status.untracked_files.is_empty()
        || status.ahead_count > 0
        || status.behind_count > 0
        || matches!(status.remote_status, RemoteStatus::NoRemote)
    {
        return StatusSeverity::LightWarning;
    }

    StatusSeverity::Clean
}

/// Check if a worktree has any activity in the last N days
pub async fn check_worktree_activity(worktree_path: &Path, days: u64) -> Result<bool> {
    let since = format!("--since={} days ago", days);

    let output = Command::new("git")
        .args(&["log", "--oneline", &since, "HEAD"])
        .current_dir(worktree_path)
        .output()
        .await?;

    Ok(output.status.success() && !output.stdout.is_empty())
}

/// Get detailed file-level diff for conflicts or changes
pub async fn get_worktree_diff(worktree_path: &Path, compact: bool) -> Result<String> {
    let mut args = vec!["diff"];

    if compact {
        args.extend(&["--name-status"]);
    } else {
        args.extend(&["--stat", "--color=never"]);
    }

    let output = Command::new("git")
        .args(&args)
        .current_dir(worktree_path)
        .output()
        .await?;

    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        Ok(String::new())
    }
}

/// Get branch creation time and first commit
pub async fn get_branch_info(worktree_path: &Path) -> Result<BranchInfo> {
    // Get current branch name
    let branch_output = Command::new("git")
        .args(&["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(worktree_path)
        .output()
        .await?;

    let branch_name = String::from_utf8_lossy(&branch_output.stdout)
        .trim()
        .to_string();

    // Get first commit on this branch (if it's not the default branch)
    // First, try to find the default branch
    let default_branch_result = Command::new("git")
        .args(&["symbolic-ref", "refs/remotes/origin/HEAD"])
        .current_dir(worktree_path)
        .output()
        .await;

    // If current branch is a common default branch, assume it's the main branch
    if branch_name == "main" || branch_name == "master" {
        return Ok(BranchInfo {
            name: branch_name,
            first_commit: None,
            commit_count: 0,
        });
    }

    let default_branch = match default_branch_result {
        Ok(output) if output.status.success() => {
            let full_ref = String::from_utf8_lossy(&output.stdout);
            let trimmed = full_ref.trim();
            trimmed
                .strip_prefix("refs/remotes/origin/")
                .unwrap_or("main")
                .to_string()
        }
        _ => {
            // Fallback: try common default branch names
            let mut found_default = None;
            for default in &["main", "master"] {
                let check_output = Command::new("git")
                    .args(&["show-ref", "--verify", &format!("refs/heads/{}", default)])
                    .current_dir(worktree_path)
                    .output()
                    .await;

                if let Ok(output) = check_output {
                    if output.status.success() {
                        found_default = Some(default.to_string());
                        break;
                    }
                }
            }

            found_default.unwrap_or_else(|| "main".to_string())
        }
    };

    // Don't compare branch to itself
    if branch_name == default_branch {
        return Ok(BranchInfo {
            name: branch_name,
            first_commit: None,
            commit_count: 0,
        });
    }

    let first_commit_output = Command::new("git")
        .args(&[
            "log",
            "--reverse",
            "--oneline",
            &format!("{}..HEAD", default_branch),
        ])
        .current_dir(worktree_path)
        .output()
        .await?;

    let first_commit =
        if first_commit_output.status.success() && !first_commit_output.stdout.is_empty() {
            String::from_utf8_lossy(&first_commit_output.stdout)
                .lines()
                .next()
                .map(|line| line.to_string())
        } else {
            None
        };

    // Get total commits on this branch
    let commit_count_output = Command::new("git")
        .args(&["rev-list", "--count", &format!("{}..HEAD", default_branch)])
        .current_dir(worktree_path)
        .output()
        .await?;

    let commit_count = if commit_count_output.status.success() {
        String::from_utf8_lossy(&commit_count_output.stdout)
            .trim()
            .parse::<usize>()
            .unwrap_or(0)
    } else {
        0
    };

    Ok(BranchInfo {
        name: branch_name,
        first_commit,
        commit_count,
    })
}

/// Update an existing WorktreeInfo with fresh status
pub async fn update_worktree_info(mut worktree: WorktreeInfo) -> Result<WorktreeInfo> {
    worktree.update_status().await?;

    // Refresh HEAD
    let head_output = Command::new("git")
        .args(&["rev-parse", "HEAD"])
        .current_dir(&worktree.path)
        .output()
        .await?;

    if head_output.status.success() {
        worktree.head = String::from_utf8_lossy(&head_output.stdout)
            .trim()
            .to_string();
    }

    Ok(worktree)
}

/// Batch update multiple worktrees for efficiency
pub async fn batch_update_worktree_status(
    worktrees: Vec<WorktreeInfo>,
) -> Result<Vec<WorktreeInfo>> {
    let mut updated = Vec::new();

    // Update in parallel for better performance
    let futures = worktrees
        .into_iter()
        .map(|worktree| async move { update_worktree_info(worktree).await });

    let results = futures_util::future::try_join_all(futures).await?;
    updated.extend(results);

    Ok(updated)
}

// Supporting types
#[derive(Debug)]
struct GitStatusInfo {
    changed_files: Vec<String>,
    untracked_files: Vec<String>,
}

#[derive(Debug)]
struct RemoteInfo {
    status: RemoteStatus,
    ahead: usize,
    behind: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BranchInfo {
    pub name: String,
    pub first_commit: Option<String>,
    pub commit_count: usize,
}

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

    async fn setup_test_worktree() -> Result<(TempDir, PathBuf)> {
        let temp_dir = TempDir::new()?;
        let path = temp_dir.path().to_path_buf();

        // Initialize git repo
        let init_output = Command::new("git")
            .args(&["init"])
            .current_dir(&path)
            .output()
            .await?;

        if !init_output.status.success() {
            anyhow::bail!("Failed to initialize git repo");
        }

        // Configure git user
        Command::new("git")
            .args(&["config", "user.name", "Test User"])
            .current_dir(&path)
            .output()
            .await?;

        Command::new("git")
            .args(&["config", "user.email", "test@example.com"])
            .current_dir(&path)
            .output()
            .await?;

        // Create initial commit
        std::fs::write(path.join("README.md"), "# Test Repository")?;

        Command::new("git")
            .args(&["add", "README.md"])
            .current_dir(&path)
            .output()
            .await?;

        Command::new("git")
            .args(&["commit", "-m", "Initial commit"])
            .current_dir(&path)
            .output()
            .await?;

        Ok((temp_dir, path))
    }

    #[tokio::test]
    async fn test_clean_worktree_status() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        let status = check_worktree_status(&path).await?;

        assert!(status.is_clean);
        assert_eq!(status.severity, StatusSeverity::Clean);
        assert!(status.uncommitted_changes.is_empty());
        assert!(status.untracked_files.is_empty());
        assert_eq!(status.ahead_count, 0);
        assert_eq!(status.behind_count, 0);

        Ok(())
    }

    #[tokio::test]
    async fn test_uncommitted_changes_detection() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        // Create a modified file
        std::fs::write(path.join("README.md"), "# Modified Test Repository")?;

        let status = check_worktree_status(&path).await?;

        assert!(!status.is_clean);
        assert_eq!(status.severity, StatusSeverity::LightWarning);
        assert!(!status.uncommitted_changes.is_empty());

        // Should contain information about the modified file
        let change_desc = &status.uncommitted_changes[0];
        assert!(change_desc.contains("README.md"));
        assert!(change_desc.contains("modified"));

        Ok(())
    }

    #[tokio::test]
    async fn test_untracked_files_detection() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        // Create an untracked file
        std::fs::write(path.join("untracked.txt"), "Untracked content")?;

        let status = check_worktree_status(&path).await?;

        assert!(!status.is_clean);
        assert_eq!(status.severity, StatusSeverity::LightWarning);
        assert!(!status.untracked_files.is_empty());
        assert!(status
            .untracked_files
            .contains(&"untracked.txt".to_string()));

        Ok(())
    }

    #[tokio::test]
    async fn test_severity_classification() -> Result<()> {
        // Test clean status
        let mut status = WorktreeStatus::new();
        status.is_clean = true;
        status.ahead_count = 0;
        status.behind_count = 0;
        status.uncommitted_changes.clear();
        status.untracked_files.clear();
        status.remote_status = RemoteStatus::UpToDate;

        assert_eq!(classify_status_severity(&status), StatusSeverity::Clean);

        // Test light warning - uncommitted changes
        status.uncommitted_changes.push("file.txt".to_string());
        status.is_clean = false;
        assert_eq!(
            classify_status_severity(&status),
            StatusSeverity::LightWarning
        );

        // Test warning - many commits behind
        status.behind_count = 15;
        status.remote_status = RemoteStatus::Behind(15);
        assert_eq!(classify_status_severity(&status), StatusSeverity::Warning);

        // Test warning - remote deleted
        status.behind_count = 0;
        status.remote_status = RemoteStatus::RemoteDeleted;
        assert_eq!(classify_status_severity(&status), StatusSeverity::Warning);

        // Test warning - diverged significantly
        status.remote_status = RemoteStatus::Diverged {
            ahead: 25,
            behind: 8,
        };
        assert_eq!(classify_status_severity(&status), StatusSeverity::Warning);

        Ok(())
    }

    #[test]
    fn test_porcelain_status_parsing() {
        let sample_output = b"M  modified.txt\0?? untracked.txt\0A  added.txt\0D  deleted.txt\0";
        let status = parse_porcelain_status(sample_output).unwrap();

        assert_eq!(status.changed_files.len(), 3); // M, A, D
        assert_eq!(status.untracked_files.len(), 1); // ??
        assert!(status
            .untracked_files
            .contains(&"untracked.txt".to_string()));

        // Check that status descriptions are included
        assert!(status
            .changed_files
            .iter()
            .any(|f| f.contains("modified.txt") && f.contains("modified")));
        assert!(status
            .changed_files
            .iter()
            .any(|f| f.contains("added.txt") && f.contains("added")));
        assert!(status
            .changed_files
            .iter()
            .any(|f| f.contains("deleted.txt") && f.contains("deleted")));
    }

    #[test]
    fn test_empty_porcelain_status() {
        let empty_output = b"";
        let status = parse_porcelain_status(empty_output).unwrap();

        assert!(status.changed_files.is_empty());
        assert!(status.untracked_files.is_empty());
    }

    #[test]
    fn test_status_severity_priority() {
        assert!(StatusSeverity::Warning.priority() < StatusSeverity::LightWarning.priority());
        assert!(StatusSeverity::LightWarning.priority() < StatusSeverity::Clean.priority());
    }

    #[tokio::test]
    async fn test_worktree_info_update_status() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        let mut worktree_info = WorktreeInfo {
            path: path.clone(),
            branch: "main".to_string(),
            head: "".to_string(),
            task_id: None,
            status: WorktreeStatus::new(),
            age: Duration::from_secs(0),
            is_detached: false,
        };

        // Update status should work without errors
        worktree_info.update_status().await?;

        // Should have a clean status for the fresh repo
        assert!(worktree_info.status.is_clean);
        assert_eq!(worktree_info.status.severity, StatusSeverity::Clean);

        Ok(())
    }

    #[tokio::test]
    async fn test_batch_update_worktree_status() -> Result<()> {
        let (_temp1, path1) = setup_test_worktree().await?;
        let (_temp2, path2) = setup_test_worktree().await?;

        let worktrees = vec![
            WorktreeInfo {
                path: path1,
                branch: "main".to_string(),
                head: "abc123".to_string(),
                task_id: None,
                status: WorktreeStatus::new(),
                age: Duration::from_secs(0),
                is_detached: false,
            },
            WorktreeInfo {
                path: path2,
                branch: "feature".to_string(),
                head: "def456".to_string(),
                task_id: Some("feature".to_string()),
                status: WorktreeStatus::new(),
                age: Duration::from_secs(0),
                is_detached: false,
            },
        ];

        let updated_worktrees = batch_update_worktree_status(worktrees).await?;

        assert_eq!(updated_worktrees.len(), 2);

        // Both should be clean since they're fresh repos
        for worktree in &updated_worktrees {
            assert!(worktree.status.is_clean);
            assert_eq!(worktree.status.severity, StatusSeverity::Clean);
        }

        Ok(())
    }

    #[tokio::test]
    async fn test_check_worktree_activity() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        // Should have recent activity (the initial commit)
        let has_recent_activity = check_worktree_activity(&path, 1).await?;
        assert!(has_recent_activity);

        // Check for activity in the distant past (should be false)
        // Note: This might be flaky depending on system clock
        let _has_old_activity = check_worktree_activity(&path, 0).await?;
        // We can't reliably test this because it depends on timing

        Ok(())
    }

    #[tokio::test]
    async fn test_get_worktree_diff_compact() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        // Clean repo should have empty diff
        let diff = get_worktree_diff(&path, true).await?;
        assert!(diff.is_empty() || diff.trim().is_empty());

        // Modify a file and check diff
        std::fs::write(path.join("README.md"), "# Modified Test Repository")?;

        let diff = get_worktree_diff(&path, true).await?;
        // Should contain information about the modified file
        assert!(diff.contains("README.md") || diff.trim().is_empty()); // Git might not show diff until staged

        Ok(())
    }

    #[tokio::test]
    async fn test_get_branch_info() -> Result<()> {
        let (_temp, path) = setup_test_worktree().await?;

        let branch_info = get_branch_info(&path).await?;

        // Default branch name can be either "main" or "master" depending on git configuration
        assert!(branch_info.name == "main" || branch_info.name == "master");
        // For a new repo, there shouldn't be commits ahead of main/master
        assert_eq!(branch_info.commit_count, 0);
        assert!(branch_info.first_commit.is_none());

        Ok(())
    }

    #[test]
    fn test_status_description() {
        let mut status = WorktreeStatus::new();
        status.is_clean = true;

        // Clean status
        assert_eq!(status.status_description(), "Clean");

        // Status with issues
        status.is_clean = false;
        status.uncommitted_changes.push("file1.rs".to_string());
        status.untracked_files.push("file2.rs".to_string());
        status.unpushed_commits.push(CommitInfo {
            id: "abc123".to_string(),
            message: "Test commit".to_string(),
            author: "Test Author".to_string(),
            timestamp: SystemTime::now(),
        });

        let description = status.status_description();
        assert!(description.contains("1 uncommitted"));
        assert!(description.contains("1 untracked"));
        assert!(description.contains("1 unpushed"));
    }

    #[test]
    fn test_status_icon() {
        let mut status = WorktreeStatus::new();

        status.severity = StatusSeverity::Clean;
        assert_eq!(status.status_icon(), "");

        status.severity = StatusSeverity::LightWarning;
        assert_eq!(status.status_icon(), "⚠️");

        status.severity = StatusSeverity::Warning;
        assert_eq!(status.status_icon(), "");
    }

    #[test]
    fn test_cleanup_safety_detection() {
        let mut status = WorktreeStatus::new();

        // Not safe initially
        assert!(!status.is_safe_to_cleanup());

        // Make it clean
        status.is_clean = true;
        status.uncommitted_changes.clear();
        status.untracked_files.clear();
        status.unpushed_commits.clear();
        assert!(status.is_safe_to_cleanup());

        // Test with unpushed commits but merged branch
        status.unpushed_commits.push(CommitInfo {
            id: "abc123".to_string(),
            message: "Test commit".to_string(),
            author: "Test Author".to_string(),
            timestamp: SystemTime::now(),
        });
        assert!(!status.is_safe_to_cleanup());

        status.merge_info = Some(MergeInfo {
            is_merged: true,
            detection_method: "standard".to_string(),
            details: None,
            confidence: 0.9,
        });
        assert!(status.is_safe_to_cleanup());
    }

    #[test]
    fn test_remote_status_display() {
        // Test the different remote status variants would be covered
        // in integration tests with the CLI display functions
        let status_no_remote = RemoteStatus::NoRemote;
        let status_up_to_date = RemoteStatus::UpToDate;
        let status_ahead = RemoteStatus::Ahead(3);
        let status_behind = RemoteStatus::Behind(2);
        let status_diverged = RemoteStatus::Diverged {
            ahead: 3,
            behind: 2,
        };
        let status_deleted = RemoteStatus::RemoteDeleted;

        // These would be tested in the display functions
        // Here we just verify the enum variants exist and can be constructed
        assert!(matches!(status_no_remote, RemoteStatus::NoRemote));
        assert!(matches!(status_up_to_date, RemoteStatus::UpToDate));
        assert!(matches!(status_ahead, RemoteStatus::Ahead(3)));
        assert!(matches!(status_behind, RemoteStatus::Behind(2)));
        assert!(matches!(
            status_diverged,
            RemoteStatus::Diverged {
                ahead: 3,
                behind: 2
            }
        ));
        assert!(matches!(status_deleted, RemoteStatus::RemoteDeleted));
    }
}