worktrunk 0.39.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! GitHub CI status detection.
//!
//! Detects CI status from GitHub PRs and workflow runs using the `gh` CLI.

use serde::Deserialize;
use worktrunk::git::{Repository, parse_owner_repo};

use super::{
    CiBranchName, CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error,
    non_interactive_cmd, parse_json,
};

/// Get the owner and repo name from the primary remote.
///
/// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths.
/// Platform is already known to be GitHub when this runs, so we extract
/// directly from the primary remote's raw URL without checking the hostname.
fn github_owner_repo(repo: &Repository) -> Option<(String, String)> {
    let remote = repo.primary_remote().ok()?;
    let url = repo.remote_url(&remote)?;
    parse_owner_repo(&url)
}

/// Get the owner and repo name for the branch's effective push destination.
fn github_owner_repo_for_branch(
    repo: &Repository,
    branch: &CiBranchName,
) -> Option<(String, String)> {
    let url = if let Some(remote_name) = &branch.remote {
        repo.effective_remote_url(remote_name)
    } else {
        repo.branch(&branch.name).github_push_url()
    }?;

    parse_owner_repo(&url)
}

/// Detect GitHub PR CI status for a branch.
///
/// # Filtering Strategy
///
/// We need to find PRs where the head branch comes from *our* fork, not just
/// PRs we authored. The `--author` flag filters by PR creator, but we want
/// to filter by source repository.
///
/// Since `gh pr list --head` doesn't support `owner:branch` format, we:
/// 1. Fetch all open PRs with matching branch name (up to 20)
/// 2. Include `headRepositoryOwner` in the JSON output
/// 3. Filter client-side by comparing `headRepositoryOwner.login` to the branch's push remote owner
///
/// This correctly handles:
/// - Fork workflows (PRs from your fork to upstream)
/// - Organization repos (PRs from org branches)
/// - Multiple users with same branch name
/// - Remote-only branches (e.g., "origin/feature")
pub(super) fn detect_github(
    repo: &Repository,
    branch: &CiBranchName,
    local_head: &str,
) -> Option<PrStatus> {
    let repo_root = repo.current_worktree().root().ok()?;

    // Get the owner of the branch's push remote for filtering PRs by source repository.
    // For local branches: uses @{push} which resolves through pushRemote → remote.pushDefault → tracking remote.
    // For remote branches: use the remote's effective URL (handles insteadOf aliases).
    let branch_owner = github_owner_repo_for_branch(repo, branch).map(|(owner, _)| owner);

    let Some(branch_owner) = branch_owner else {
        log::debug!(
            "Branch {} has no GitHub push remote; skipping PR-based CI detection",
            branch.full_name
        );
        return None;
    };

    // Use `gh pr list --head` instead of `gh pr view` to handle numeric branch names correctly.
    // When branch name is all digits (e.g., "4315"), `gh pr view` interprets it as a PR number,
    // but `gh pr list --head` correctly treats it as a branch name.
    //
    // IMPORTANT: Use the bare branch name (branch.name), not the full remote ref.
    // `gh pr list --head origin/feature` won't find anything - it needs just "feature".
    //
    // We fetch up to MAX_PRS_TO_FETCH PRs to handle branch name collisions, then filter
    // client-side by headRepositoryOwner to find PRs from our fork.
    let output = match non_interactive_cmd("gh")
        .args([
            "pr",
            "list",
            "--head",
            &branch.name, // Use bare branch name, not "origin/feature"
            "--state",
            "open",
            "--limit",
            &MAX_PRS_TO_FETCH.to_string(),
            "--json",
            "headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner",
        ])
        .current_dir(&repo_root)
        .run()
    {
        Ok(output) => output,
        Err(e) => {
            log::warn!(
                "gh pr list failed to execute for branch {}: {}",
                branch.full_name,
                e
            );
            return None;
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if is_retriable_error(&stderr) {
            return Some(PrStatus::error());
        }
        return None;
    }

    // gh pr list returns an array - find the first PR from our origin
    let pr_list: Vec<GitHubPrInfo> = parse_json(&output.stdout, "gh pr list", &branch.full_name)?;

    // Filter to PRs from our origin (case-insensitive comparison for GitHub usernames).
    // If headRepositoryOwner is missing (older GH CLI, Enterprise, or permissions),
    // treat it as a potential match to avoid false negatives.
    let pr_info = pr_list.iter().find(|pr| {
        pr.head_repository_owner
            .as_ref()
            .map(|h| h.login.eq_ignore_ascii_case(&branch_owner))
            .unwrap_or(true) // Missing owner field = potential match
    });
    if pr_info.is_none() && !pr_list.is_empty() {
        log::debug!(
            "Found {} PRs for branch {} but none from owner {}",
            pr_list.len(),
            branch.full_name,
            branch_owner
        );
    }
    let pr_info = pr_info?;

    // Determine CI status using priority: conflicts > running > failed > passed > no_ci
    let ci_status = if pr_info.merge_state_status.as_deref() == Some("DIRTY") {
        CiStatus::Conflicts
    } else {
        pr_info.ci_status()
    };

    let is_stale = pr_info
        .head_ref_oid
        .as_ref()
        .map(|pr_head| pr_head != local_head)
        .unwrap_or(false);

    Some(PrStatus {
        ci_status,
        source: CiSource::PullRequest,
        is_stale,
        url: pr_info.url.clone(),
    })
}

/// Detect CI status for a commit using GitHub's check-runs API.
///
/// This queries all check runs for the commit SHA, giving us the same data
/// that `statusCheckRollup` provides for PRs. This correctly aggregates
/// status across multiple workflows (e.g., `ci` and `publish-docs`).
pub(super) fn detect_github_commit_checks(
    repo: &Repository,
    branch: &CiBranchName,
    local_head: &str,
) -> Option<PrStatus> {
    let repo_root = repo.current_worktree().root().ok()?;
    let (owner, repo_name) =
        github_owner_repo_for_branch(repo, branch).or_else(|| github_owner_repo(repo))?;

    // Only pass --hostname when explicitly configured (for GHE / self-hosted)
    let hostname = repo
        .load_project_config()
        .ok()
        .flatten()
        .and_then(|c| c.forge_hostname().map(String::from));

    // Use GitHub's check-runs API to get all checks for this commit
    let api_path = format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs");
    let mut args = vec!["api", api_path.as_str()];
    if let Some(h) = &hostname {
        args.extend(["--hostname", h.as_str()]);
    }
    args.extend(["--jq", ".check_runs | map({status, conclusion})"]);

    let output = match non_interactive_cmd("gh")
        .args(args)
        .current_dir(&repo_root)
        .run()
    {
        Ok(output) => output,
        Err(e) => {
            log::warn!(
                "gh api check-runs failed to execute for {}: {}",
                local_head,
                e
            );
            return None;
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if is_retriable_error(&stderr) {
            return Some(PrStatus::error());
        }
        return None;
    }

    let checks: Vec<GitHubCheck> = parse_json(&output.stdout, "gh api check-runs", local_head)?;

    if checks.is_empty() {
        return None;
    }

    // Aggregate status: any failed → Failed, any running → Running, else Passed
    let ci_status = aggregate_github_checks(&checks);

    Some(PrStatus {
        ci_status,
        source: CiSource::Branch,
        is_stale: false, // We're querying by SHA, so always current
        url: None,
    })
}

/// GitHub PR info from `gh pr list --json ...`
///
/// Note: We include `headRepositoryOwner` for client-side filtering by source fork.
/// See `parse_owner_repo()` for why this is necessary.
///
/// Note: We don't include `state` because we already filter with `--state open`.
#[derive(Debug, Deserialize)]
pub(super) struct GitHubPrInfo {
    #[serde(rename = "headRefOid")]
    pub head_ref_oid: Option<String>,
    #[serde(rename = "mergeStateStatus")]
    pub merge_state_status: Option<String>,
    #[serde(rename = "statusCheckRollup")]
    pub status_check_rollup: Option<Vec<GitHubCheck>>,
    pub url: Option<String>,
    /// The owner of the repository the PR's head branch comes from.
    /// Used to filter PRs by source fork (see `parse_owner_repo()`).
    #[serde(rename = "headRepositoryOwner")]
    pub head_repository_owner: Option<HeadRepositoryOwner>,
}

/// Owner info for the head repository of a PR.
#[derive(Debug, Deserialize)]
pub(super) struct HeadRepositoryOwner {
    /// The login (username/org name) of the repository owner.
    pub login: String,
}

/// A single check from `statusCheckRollup`.
///
/// This is a union of two GitHub API types with different field structures:
/// - `CheckRun` (GitHub Actions): has `status` ("COMPLETED", "IN_PROGRESS") and
///   `conclusion` ("SUCCESS", "FAILURE", "CANCELLED", "SKIPPED")
/// - `StatusContext` (external CI like pre-commit.ci): has `state` only
///   ("SUCCESS", "FAILURE", "PENDING", "ERROR")
///
/// We parse all three fields and check whichever is present. An alternative approach would be
/// `gh pr checks <number> --json state` which returns a flat array with unified `state` field,
/// but that requires a separate API call after finding the PR number. Since we also need
/// `gh run list` for branch-based CI (branches without PRs), keeping the single-call approach
/// here is simpler overall.
#[derive(Debug, Deserialize)]
pub(super) struct GitHubCheck {
    /// CheckRun only: "COMPLETED", "IN_PROGRESS", "QUEUED", etc.
    pub status: Option<String>,
    /// CheckRun only: "SUCCESS", "FAILURE", "CANCELLED", "SKIPPED", etc.
    pub conclusion: Option<String>,
    /// StatusContext only: "SUCCESS", "FAILURE", "PENDING", "ERROR"
    pub state: Option<String>,
}

impl GitHubPrInfo {
    pub fn ci_status(&self) -> CiStatus {
        match &self.status_check_rollup {
            None => CiStatus::NoCI,
            Some(checks) if checks.is_empty() => CiStatus::NoCI,
            Some(checks) => aggregate_github_checks(checks),
        }
    }
}

/// Aggregate CI status from multiple GitHub checks (case-insensitive).
///
/// Priority: running > failed > passed > no-ci.
/// Handles both `statusCheckRollup` (uppercase) and check-runs API (lowercase).
/// Skipped/neutral checks don't contribute to pass/fail.
pub(super) fn aggregate_github_checks(checks: &[GitHubCheck]) -> CiStatus {
    let mut has_running = false;
    let mut has_failure = false;
    let mut has_success = false;

    for check in checks {
        // CheckRun: status field indicates in-progress states
        if let Some(status) = &check.status {
            let s = status.to_ascii_lowercase();
            if matches!(
                s.as_str(),
                "in_progress" | "queued" | "pending" | "expected"
            ) {
                has_running = true;
            }
        }

        // StatusContext: state field indicates pending
        if let Some(state) = &check.state {
            let s = state.to_ascii_lowercase();
            if s == "pending" {
                has_running = true;
            } else if matches!(s.as_str(), "failure" | "error") {
                has_failure = true;
            } else if s == "success" {
                has_success = true;
            }
        }

        // CheckRun: conclusion field indicates final result
        if let Some(conclusion) = &check.conclusion {
            let c = conclusion.to_ascii_lowercase();
            match c.as_str() {
                "failure" | "error" | "cancelled" | "timed_out" | "action_required" => {
                    has_failure = true;
                }
                "success" => {
                    has_success = true;
                }
                // "skipped", "neutral" - ignored
                _ => {}
            }
        }
    }

    if has_running {
        CiStatus::Running
    } else if has_failure {
        CiStatus::Failed
    } else if has_success {
        CiStatus::Passed
    } else {
        CiStatus::NoCI
    }
}

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

    #[test]
    fn test_github_pr_info_ci_status() {
        // No checks = NoCI
        let pr = GitHubPrInfo {
            head_ref_oid: None,
            merge_state_status: None,
            status_check_rollup: None,
            url: None,
            head_repository_owner: None,
        };
        assert_eq!(pr.ci_status(), CiStatus::NoCI);

        // Empty checks = NoCI
        let pr = GitHubPrInfo {
            head_ref_oid: None,
            merge_state_status: None,
            status_check_rollup: Some(vec![]),
            url: None,
            head_repository_owner: None,
        };
        assert_eq!(pr.ci_status(), CiStatus::NoCI);

        // CheckRun pending states
        for status in ["IN_PROGRESS", "QUEUED", "PENDING", "EXPECTED"] {
            let pr = GitHubPrInfo {
                head_ref_oid: None,
                merge_state_status: None,
                status_check_rollup: Some(vec![GitHubCheck {
                    status: Some(status.into()),
                    conclusion: None,
                    state: None,
                }]),
                url: None,
                head_repository_owner: None,
            };
            assert_eq!(pr.ci_status(), CiStatus::Running, "status={status}");
        }

        // StatusContext pending
        let pr = GitHubPrInfo {
            head_ref_oid: None,
            merge_state_status: None,
            status_check_rollup: Some(vec![GitHubCheck {
                status: None,
                conclusion: None,
                state: Some("PENDING".into()),
            }]),
            url: None,
            head_repository_owner: None,
        };
        assert_eq!(pr.ci_status(), CiStatus::Running);

        // CheckRun failures
        for conclusion in ["FAILURE", "ERROR", "CANCELLED"] {
            let pr = GitHubPrInfo {
                head_ref_oid: None,
                merge_state_status: None,
                status_check_rollup: Some(vec![GitHubCheck {
                    status: Some("COMPLETED".into()),
                    conclusion: Some(conclusion.into()),
                    state: None,
                }]),
                url: None,
                head_repository_owner: None,
            };
            assert_eq!(pr.ci_status(), CiStatus::Failed, "conclusion={conclusion}");
        }

        // StatusContext failures
        for state in ["FAILURE", "ERROR"] {
            let pr = GitHubPrInfo {
                head_ref_oid: None,
                merge_state_status: None,
                status_check_rollup: Some(vec![GitHubCheck {
                    status: None,
                    conclusion: None,
                    state: Some(state.into()),
                }]),
                url: None,
                head_repository_owner: None,
            };
            assert_eq!(pr.ci_status(), CiStatus::Failed, "state={state}");
        }

        // Success
        let pr = GitHubPrInfo {
            head_ref_oid: None,
            merge_state_status: None,
            status_check_rollup: Some(vec![GitHubCheck {
                status: Some("COMPLETED".into()),
                conclusion: Some("SUCCESS".into()),
                state: None,
            }]),
            url: None,
            head_repository_owner: None,
        };
        assert_eq!(pr.ci_status(), CiStatus::Passed);
    }

    #[test]
    fn test_aggregate_github_checks() {
        // Helper to create a check without state field (like check-runs API)
        fn check(status: &str, conclusion: Option<&str>) -> GitHubCheck {
            GitHubCheck {
                status: Some(status.into()),
                conclusion: conclusion.map(|c| c.into()),
                state: None,
            }
        }

        // Empty checks = NoCI
        assert_eq!(aggregate_github_checks(&[]), CiStatus::NoCI);

        // All skipped = NoCI (skipped doesn't count as success)
        let checks = vec![
            check("completed", Some("skipped")),
            check("completed", Some("neutral")),
        ];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::NoCI);

        // Any running = Running
        for status in ["in_progress", "queued", "pending"] {
            let checks = vec![check("completed", Some("success")), check(status, None)];
            assert_eq!(
                aggregate_github_checks(&checks),
                CiStatus::Running,
                "status={status}"
            );
        }

        // Any failure among completed checks = Failed
        for conclusion in ["failure", "cancelled", "timed_out", "action_required"] {
            let checks = vec![
                check("completed", Some("success")),
                check("completed", Some(conclusion)),
            ];
            assert_eq!(
                aggregate_github_checks(&checks),
                CiStatus::Failed,
                "conclusion={conclusion}"
            );
        }

        // Running takes priority over failure (build might still succeed)
        let checks = vec![
            check("in_progress", None),
            check("completed", Some("failure")),
        ];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);

        // All success = Passed
        let checks = vec![
            check("completed", Some("success")),
            check("completed", Some("success")),
        ];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);

        // Mix of success and skipped = Passed (skipped doesn't block)
        let checks = vec![
            check("completed", Some("success")),
            check("completed", Some("skipped")),
        ];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);

        // Case insensitivity (handles both PR uppercase and API lowercase)
        let checks = vec![check("COMPLETED", Some("FAILURE"))];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);

        // StatusContext via state field (used by external CI like pre-commit.ci)
        let checks = vec![GitHubCheck {
            status: None,
            conclusion: None,
            state: Some("PENDING".into()),
        }];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);

        let checks = vec![GitHubCheck {
            status: None,
            conclusion: None,
            state: Some("failure".into()),
        }];
        assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);
    }
}