git-worktree-manager 0.0.39

CLI tool integrating git worktree with AI coding assistants
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
use std::process::Command;

use console::style;

use crate::constants::{
    format_config_key, version_meets_minimum, CONFIG_KEY_BASE_BRANCH, MIN_GIT_VERSION,
    MIN_GIT_VERSION_MAJOR, MIN_GIT_VERSION_MINOR,
};
use crate::error::Result;
use crate::git;
use crate::registry;

use super::display::get_worktree_status;
use super::pr_cache::PrCache;
use super::setup_claude;

/// Worktree info collected during health check.
struct WtInfo {
    branch: String,
    path: std::path::PathBuf,
    status: String,
}

/// Perform health check on all worktrees.
pub fn doctor(session_start: bool, quiet: bool) -> Result<()> {
    if session_start {
        return doctor_session_start(quiet);
    }
    let repo = git::get_repo_root(None)?;
    println!(
        "\n{}\n",
        style("git-worktree-manager Health Check").cyan().bold()
    );

    let mut issues = 0u32;
    let mut warnings = 0u32;

    // 1. Check Git version
    check_git_version(&mut issues);

    // 2. Check worktree accessibility
    let (worktrees, stale_count) = check_worktree_accessibility(&repo, &mut issues)?;

    // 3. Check for uncommitted changes
    check_uncommitted_changes(&worktrees, &mut warnings);

    // 4. Check if worktrees are behind base branch
    let behind = check_behind_base(&worktrees, &repo, &mut warnings);

    // 5. Check for merge conflicts
    let conflicted = check_merge_conflicts(&worktrees, &mut issues);

    // 6. Check Claude Code integration
    check_claude_integration();

    // Summary
    print_summary(issues, warnings);

    // Recommendations
    print_recommendations(stale_count, &behind, &conflicted);

    Ok(())
}

/// Hook-friendly single-line health summary. Always returns Ok(()) so a
/// SessionStart hook never blocks the Claude Code session.
fn doctor_session_start(quiet: bool) -> Result<()> {
    let cwd = std::env::current_dir().ok();
    let cwd_ok = cwd.as_ref().map(|p| p.exists()).unwrap_or(false);
    let cwd_str = cwd
        .as_ref()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "?".into());

    // Branch + base + registration are best-effort: failures here must not
    // abort the line. Each failed lookup contributes "?" to the output.
    let repo_root = git::get_repo_root(None).ok();
    let branch = repo_root
        .as_deref()
        .and_then(|root| git::get_current_branch(Some(root)).ok())
        .unwrap_or_else(|| "?".into());
    let base = if branch != "?" {
        repo_root
            .as_deref()
            .and_then(|root| {
                let key = format_config_key(CONFIG_KEY_BASE_BRANCH, &branch);
                git::get_config(&key, Some(root))
            })
            .unwrap_or_else(|| "?".into())
    } else {
        "?".into()
    };
    let registered = {
        let registry = registry::load_registry();
        cwd.as_ref()
            .map(|p| {
                let key = p
                    .canonicalize()
                    .unwrap_or_else(|_| p.clone())
                    .to_string_lossy()
                    .to_string();
                registry.repositories.contains_key(&key)
            })
            .unwrap_or(false)
    };

    let prefix = if quiet { "gw:" } else { "gw doctor:" };
    println!(
        "{} cwd={} ok={} branch={} base={} registered={}",
        prefix, cwd_str, cwd_ok, branch, base, registered,
    );
    Ok(())
}

/// Check Git version meets minimum requirement.
fn check_git_version(issues: &mut u32) {
    println!("{}", style("1. Checking Git version...").bold());
    match Command::new("git").arg("--version").output() {
        Ok(output) if output.status.success() => {
            let version_output = String::from_utf8_lossy(&output.stdout);
            let version_str = version_output
                .split_whitespace()
                .nth(2)
                .unwrap_or("unknown");

            let is_ok =
                version_meets_minimum(version_str, MIN_GIT_VERSION_MAJOR, MIN_GIT_VERSION_MINOR);

            if is_ok {
                println!(
                    "   {} Git version {} (minimum: {})",
                    style("*").green(),
                    version_str,
                    MIN_GIT_VERSION,
                );
            } else {
                println!(
                    "   {} Git version {} is too old (minimum: {})",
                    style("x").red(),
                    version_str,
                    MIN_GIT_VERSION,
                );
                *issues += 1;
            }
        }
        _ => {
            println!("   {} Could not detect Git version", style("x").red());
            *issues += 1;
        }
    }
    println!();
}

/// Check that all worktrees are accessible (not stale).
fn check_worktree_accessibility(
    repo: &std::path::Path,
    issues: &mut u32,
) -> Result<(Vec<WtInfo>, u32)> {
    println!("{}", style("2. Checking worktree accessibility...").bold());
    let feature_worktrees = git::get_feature_worktrees(Some(repo))?;
    let mut stale_count = 0u32;
    let mut worktrees: Vec<WtInfo> = Vec::new();

    // doctor needs fresh state; bypass the 60s TTL.
    let pr_cache = PrCache::load_or_fetch(repo, true);

    for (branch_name, path) in &feature_worktrees {
        let status = get_worktree_status(path, repo, Some(branch_name.as_str()), &pr_cache);
        if status == "stale" {
            stale_count += 1;
            println!(
                "   {} {}: Stale (directory missing)",
                style("x").red(),
                branch_name
            );
            *issues += 1;
        }
        worktrees.push(WtInfo {
            branch: branch_name.clone(),
            path: path.clone(),
            status,
        });
    }

    if stale_count == 0 {
        println!(
            "   {} All {} worktrees are accessible",
            style("*").green(),
            worktrees.len()
        );
    }
    println!();

    Ok((worktrees, stale_count))
}

/// Check for uncommitted changes in worktrees.
fn check_uncommitted_changes(worktrees: &[WtInfo], warnings: &mut u32) {
    println!("{}", style("3. Checking for uncommitted changes...").bold());
    let mut dirty: Vec<String> = Vec::new();
    for wt in worktrees {
        if wt.status == "modified" || wt.status == "active" {
            if let Ok(r) = git::git_command(&["status", "--porcelain"], Some(&wt.path), false, true)
            {
                if r.returncode == 0 && !r.stdout.trim().is_empty() {
                    dirty.push(wt.branch.clone());
                }
            }
        }
    }

    if dirty.is_empty() {
        println!("   {} No uncommitted changes", style("*").green());
    } else {
        println!(
            "   {} {} worktree(s) with uncommitted changes:",
            style("!").yellow(),
            dirty.len()
        );
        for b in &dirty {
            println!("      - {}", b);
        }
        *warnings += 1;
    }
    println!();
}

/// Check if worktrees are behind their base branch.
fn check_behind_base(
    worktrees: &[WtInfo],
    repo: &std::path::Path,
    warnings: &mut u32,
) -> Vec<(String, String, String)> {
    println!(
        "{}",
        style("4. Checking if worktrees are behind base branch...").bold()
    );
    let mut behind: Vec<(String, String, String)> = Vec::new();

    for wt in worktrees {
        if wt.status == "stale" {
            continue;
        }
        let key = format_config_key(CONFIG_KEY_BASE_BRANCH, &wt.branch);
        let base = match git::get_config(&key, Some(repo)) {
            Some(b) => b,
            None => continue,
        };

        let origin_base = format!("origin/{}", base);
        if let Ok(r) = git::git_command(
            &[
                "rev-list",
                "--count",
                &format!("{}..{}", wt.branch, origin_base),
            ],
            Some(&wt.path),
            false,
            true,
        ) {
            if r.returncode == 0 {
                let count = r.stdout.trim();
                if count != "0" {
                    behind.push((wt.branch.clone(), base.clone(), count.to_string()));
                }
            }
        }
    }

    if behind.is_empty() {
        println!(
            "   {} All worktrees are up-to-date with base",
            style("*").green()
        );
    } else {
        println!(
            "   {} {} worktree(s) behind base branch:",
            style("!").yellow(),
            behind.len()
        );
        for (b, base, count) in &behind {
            println!("      - {}: {} commit(s) behind {}", b, count, base);
        }
        println!(
            "   {}",
            style("Tip: Use 'gw sync --all' to update all worktrees").dim()
        );
        *warnings += 1;
    }
    println!();

    behind
}

/// Check for merge conflicts in worktrees.
fn check_merge_conflicts(worktrees: &[WtInfo], issues: &mut u32) -> Vec<(String, usize)> {
    println!("{}", style("5. Checking for merge conflicts...").bold());
    let mut conflicted: Vec<(String, usize)> = Vec::new();

    for wt in worktrees {
        if wt.status == "stale" {
            continue;
        }
        if let Ok(r) = git::git_command(
            &["diff", "--name-only", "--diff-filter=U"],
            Some(&wt.path),
            false,
            true,
        ) {
            if r.returncode == 0 && !r.stdout.trim().is_empty() {
                let count = r.stdout.trim().lines().count();
                conflicted.push((wt.branch.clone(), count));
            }
        }
    }

    if conflicted.is_empty() {
        println!("   {} No merge conflicts detected", style("*").green());
    } else {
        println!(
            "   {} {} worktree(s) with merge conflicts:",
            style("x").red(),
            conflicted.len()
        );
        for (b, count) in &conflicted {
            println!("      - {}: {} conflicted file(s)", b, count);
        }
        *issues += 1;
    }
    println!();

    conflicted
}

/// Check Claude Code installation and skill integration.
fn check_claude_integration() {
    println!("{}", style("6. Checking Claude Code integration...").bold());

    let has_claude = Command::new("which")
        .arg("claude")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !has_claude {
        println!(
            "   {} Claude Code not detected (optional)",
            style("-").dim()
        );
    } else if setup_claude::is_plugin_installed() {
        println!("   {} gw plugin installed", style("*").green());
    } else if setup_claude::is_skill_installed() {
        // Legacy skill-only install. Suggest the upgrade.
        println!(
            "   {} Legacy gw skill installed (pre-plugin layout)",
            style("!").yellow()
        );
        println!(
            "   {}",
            style("Tip: Re-run 'gw setup-claude' to upgrade from skill to plugin").dim()
        );
    } else {
        println!(
            "   {} Claude Code detected but gw plugin not installed",
            style("!").yellow()
        );
        println!(
            "   {}",
            style("Tip: Run 'gw setup-claude' to install the gw plugin for Claude Code").dim()
        );
    }
    println!();
}

/// Print health check summary.
fn print_summary(issues: u32, warnings: u32) {
    println!("{}", style("Summary:").cyan().bold());
    if issues == 0 && warnings == 0 {
        println!("{}\n", style("* Everything looks healthy!").green().bold());
    } else {
        if issues > 0 {
            println!(
                "{}",
                style(format!("x {} issue(s) found", issues)).red().bold()
            );
        }
        if warnings > 0 {
            println!(
                "{}",
                style(format!("! {} warning(s) found", warnings))
                    .yellow()
                    .bold()
            );
        }
        println!();
    }
}

/// Print remediation recommendations.
fn print_recommendations(
    stale_count: u32,
    behind: &[(String, String, String)],
    conflicted: &[(String, usize)],
) {
    let has_recommendations = stale_count > 0 || !behind.is_empty() || !conflicted.is_empty();
    if has_recommendations {
        println!("{}", style("Recommendations:").bold());
        if stale_count > 0 {
            println!(
                "  - Run {} to clean up stale worktrees",
                style("gw prune").cyan()
            );
        }
        if !behind.is_empty() {
            println!(
                "  - Run {} to update all worktrees",
                style("gw sync --all").cyan()
            );
        }
        if !conflicted.is_empty() {
            println!("  - Resolve conflicts in conflicted worktrees");
        }
        println!();
    }
}