Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: CI status detection for remote-only branches (#817)
Maximilian Roos9d0e1cbc1acf
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex 291efc29c..1a158eefd 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -219,7 +219,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {let repo = Repository::current()?;let project_config = repo.load_project_config().ok().flatten();let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());- let platform = get_platform_for_repo(&repo, platform_override);+ let platform = get_platform_for_repo(&repo, platform_override, None);match platform {Some(CiPlatform::GitHub) => {diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 3ca06ccdc..7b2413101 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -16,7 +16,7 @@ use worktrunk::styling::{};use worktrunk::utils::get_now;-use super::super::list::ci_status::CachedCiStatus;+use super::super::list::ci_status::{CachedCiStatus, CiBranchName};use crate::display::format_relative_time_short;use crate::help_pager::show_help_in_pager;@@ -198,6 +198,17 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>None => repo.require_current_branch("get ci-status for current branch")?,};+ // Determine if this is a remote ref by checking git refs directly.+ // This is authoritative - we check actual refs, not guessing from name.+ let is_remote = repo+ .run_command(&[+ "show-ref",+ "--verify",+ "--quiet",+ &format!("refs/remotes/{}", branch_name),+ ])+ .is_ok();+// Get the HEAD commit for this branchlet head = repo.run_command(&["rev-parse", &branch_name])@@ -212,13 +223,8 @@ pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()>.into());}- let has_upstream = repo- .branch(&branch_name)- .upstream()- .ok()- .flatten()- .is_some();- let ci_status = PrStatus::detect(&repo, &branch_name, &head, has_upstream)+ let ci_branch = CiBranchName::from_branch_ref(&branch_name, is_remote, &repo);+ let ci_status = PrStatus::detect(&repo, &ci_branch, &head).map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {s.ci_status});diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex ab852fcf3..cdf8110da 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -6,8 +6,8 @@ use serde::Deserialize;use worktrunk::git::{GitRemoteUrl, Repository, parse_remote_owner};use super::{- CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error, non_interactive_cmd,- parse_json,+ CiBranchName, CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error,+ non_interactive_cmd, parse_json,};/// Get the owner and repo name from any GitHub remote.@@ -42,27 +42,43 @@ fn get_github_owner_repo(repo: &Repository) -> Option<(String, String)> {/// - Fork workflows (PRs from your fork to upstream)/// - Organization repos (PRs from org branches)/// - Multiple users with same branch name-pub(super) fn detect_github(repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+/// - 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.- // Uses @{push} which resolves through pushRemote → remote.pushDefault → tracking remote.- let branch_owner = repo- .branch(branch)- .github_push_url()- .and_then(|url| parse_remote_owner(&url));- if branch_owner.is_none() {+ // For local branches: uses @{push} which resolves through pushRemote → remote.pushDefault → tracking remote.+ // For remote branches: use the remote's URL directly (the branch IS on that remote).+ let branch_owner = if let Some(remote_name) = &branch.remote {+ // Remote branch - get owner from the remote's URL+ repo.remote_url(remote_name)+ .and_then(|url| parse_remote_owner(&url))+ } else {+ // Local branch - use existing push remote resolution+ repo.branch(&branch.name)+ .github_push_url()+ .and_then(|url| parse_remote_owner(&url))+ };++ let Some(branch_owner) = branch_owner else {log::debug!("Branch {} has no GitHub push remote; skipping PR-based CI detection",- branch+ 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")@@ -70,7 +86,7 @@ pub(super) fn detect_github(repo: &Repository, branch: &str, local_head: &str) -"pr","list","--head",- branch,+ &branch.name, // Use bare branch name, not "origin/feature""--state","open","--limit",@@ -83,7 +99,11 @@ pub(super) fn detect_github(repo: &Repository, branch: &str, local_head: &str) -{Ok(output) => output,Err(e) => {- log::warn!("gh pr list failed to execute for branch {}: {}", branch, e);+ log::warn!(+ "gh pr list failed to execute for branch {}: {}",+ branch.full_name,+ e+ );return None;}};@@ -97,24 +117,23 @@ pub(super) fn detect_github(repo: &Repository, branch: &str, local_head: &str) -}// 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)?;+ 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 owner = branch_owner.as_ref().unwrap(); // Safe: returned early if Nonelet pr_info = pr_list.iter().find(|pr| {pr.head_repository_owner.as_ref()- .map(|h| h.login.eq_ignore_ascii_case(owner))+ .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,- owner+ branch.full_name,+ branch_owner);}let pr_info = pr_info?;diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rsindex 781354044..81b4f2b1b 100644--- a/src/commands/list/ci_status/gitlab.rs+++ b/src/commands/list/ci_status/gitlab.rs@@ -19,8 +19,8 @@ use std::path::Path;use worktrunk::git::Repository;use super::{- CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error, non_interactive_cmd,- parse_json,+ CiBranchName, CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error,+ non_interactive_cmd, parse_json,};/// Get the GitLab project ID for a repository.@@ -68,7 +68,11 @@ fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {/// 1. Get the current project ID via `glab repo view`/// 2. Fetch all open MRs with matching branch name (up to 20)/// 3. Filter client-side by comparing `source_project_id` to our project ID-pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+pub(super) fn detect_gitlab(+ repo: &Repository,+ branch: &CiBranchName,+ local_head: &str,+) -> Option<PrStatus> {let repo_root = repo.current_worktree().root().ok()?;// Get current project ID for filtering@@ -78,6 +82,8 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -}// Fetch MRs with matching source branch.+ // IMPORTANT: Use the bare branch name (branch.name), not the full remote ref.+ // `glab mr list --source-branch origin/feature` won't find anything - it needs just "feature".// Note: glab mr list returns open MRs by default, no --state flag needed.// We filter client-side by source_project_id (numeric project ID comparison).let output = match non_interactive_cmd("glab")@@ -85,7 +91,7 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -"mr","list","--source-branch",- branch,+ &branch.name, // Use bare branch name, not "origin/feature"&format!("--per-page={}", MAX_PRS_TO_FETCH),"--output","json",@@ -97,7 +103,7 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -Err(e) => {log::warn!("glab mr list failed to execute for branch {}: {}",- branch,+ branch.full_name,e);return None;@@ -116,7 +122,8 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -// Step 1: Parse mr list output to find matching MR.// Note: glab mr list does NOT return head_pipeline/pipeline fields.- let mr_list: Vec<GitLabMrListEntry> = parse_json(&output.stdout, "glab mr list", branch)?;+ let mr_list: Vec<GitLabMrListEntry> =+ parse_json(&output.stdout, "glab mr list", &branch.full_name)?;// Filter to MRs from our project (numeric project ID comparison)let mr_entry = if let Some(proj_id) = project_id {@@ -127,7 +134,7 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -log::debug!("Found {} MRs for branch {} but none from project ID {}",mr_list.len(),- branch,+ branch.full_name,proj_id);}@@ -137,7 +144,7 @@ pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -log::debug!("No project ID for {}, using first MR for branch {}",repo_root.display(),- branch+ branch.full_name);mr_list.first()}?;diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsindex 5b3d02a07..7fe446bd6 100644--- a/src/commands/list/ci_status/mod.rs+++ b/src/commands/list/ci_status/mod.rs@@ -14,6 +14,89 @@ use worktrunk::git::Repository;use worktrunk::shell_exec::Cmd;use worktrunk::utils::get_now;+/// A parsed branch name for CI status detection.+///+/// CI tools like `gh` and `glab` expect bare branch names (e.g., `"feature"`),+/// not remote-prefixed refs (e.g., `"origin/feature"`). This type holds+/// parsed branch components:+/// 1. `name` - bare branch name for CI tool API calls+/// 2. `remote` - remote name for URL lookups (if remote branch)+/// 3. `full_name` - original name for cache keys+#[derive(Debug, Clone)]+pub struct CiBranchName {+ /// The original full name (e.g., "origin/feature" or "feature")+ pub full_name: String,+ /// For remote branches: the remote name (e.g., "origin")+ pub remote: Option<String>,+ /// The bare branch name (e.g., "feature")+ pub name: String,+}++impl CiBranchName {+ /// Create from a branch name with authoritative `is_remote` flag.+ ///+ /// For remote branches (e.g., "origin/feature"), extracts the remote name+ /// and bare branch name by finding the matching remote prefix.+ /// For local branches, the name is already bare.+ ///+ /// The `is_remote` flag should come from an authoritative source:+ /// - `BranchRef::is_remote` (from collection phase)+ /// - `git show-ref --verify refs/remotes/<branch>` (for CLI input)+ pub fn from_branch_ref(branch: &str, is_remote: bool, repo: &Repository) -> Self {+ if is_remote {+ // Remote branch - find the remote prefix to extract bare name+ for (remote_name, _) in repo.all_remote_urls() {+ let prefix = format!("{}/", remote_name);+ if let Some(name) = branch.strip_prefix(&prefix) {+ log::debug!(+ "Remote branch {} -> remote={}, name={}",+ branch,+ remote_name,+ name+ );+ return Self {+ full_name: branch.to_string(),+ remote: Some(remote_name),+ name: name.to_string(),+ };+ }+ }+ // Fallback: couldn't find matching remote, use first segment as remote+ if let Some((remote, name)) = branch.split_once('/') {+ log::warn!(+ "Remote branch {} has unknown remote '{}', using as-is",+ branch,+ remote+ );+ return Self {+ full_name: branch.to_string(),+ remote: Some(remote.to_string()),+ name: name.to_string(),+ };+ }+ }+ // Local branch - name is already bare+ Self {+ full_name: branch.to_string(),+ remote: None,+ name: branch.to_string(),+ }+ }++ /// Returns true if this is a remote branch reference.+ pub fn is_remote(&self) -> bool {+ self.remote.is_some()+ }++ /// Check if this branch has upstream (remote tracking) configured.+ ///+ /// Remote branches inherently "have upstream" since they ARE the upstream.+ /// Local branches need tracking config to have upstream.+ pub fn has_upstream(&self, repo: &Repository) -> bool {+ self.is_remote() || repo.branch(&self.name).upstream().ok().flatten().is_some()+ }+}+// Re-export public typespub(crate) use cache::CachedCiStatus;pub use platform::{CiPlatform, get_platform_for_repo};@@ -255,24 +338,21 @@ impl PrStatus {/// repos are properly detected.////// # Arguments- /// * `has_upstream` - Whether the branch has upstream tracking configured.- /// PR/MR detection always runs. Workflow/pipeline fallback only runs if true.- pub fn detect(- repo: &Repository,- branch: &str,- local_head: &str,- has_upstream: bool,- ) -> Option<Self> {+ /// * `branch` - The parsed branch name (may be local or remote).+ /// * `local_head` - The commit SHA to check CI status for.+ pub fn detect(repo: &Repository, branch: &CiBranchName, local_head: &str) -> Option<Self> {+ let has_upstream = branch.has_upstream(repo);let repo_path = repo.current_worktree().root().ok()?;// Check cache first to avoid hitting API rate limits+ // Use full_name as cache key to distinguish local "feature" from remote "origin/feature"let now_secs = get_now();- if let Some(cached) = CachedCiStatus::read(repo, branch) {+ if let Some(cached) = CachedCiStatus::read(repo, &branch.full_name) {if cached.is_valid(local_head, now_secs, &repo_path) {log::debug!("Using cached CI status for {} (age={}s, ttl={}s, status={:?})",- branch,+ branch.full_name,now_secs - cached.checked_at,CachedCiStatus::ttl_for_repo(&repo_path),cached.status.as_ref().map(|s| &s.ci_status)@@ -281,7 +361,7 @@ impl PrStatus {}log::debug!("Cache expired for {} (age={}s, ttl={}s, head_match={})",- branch,+ branch.full_name,now_secs - cached.checked_at,CachedCiStatus::ttl_for_repo(&repo_path),cached.head == local_head@@ -297,7 +377,7 @@ impl PrStatus {checked_at: now_secs,head: local_head.to_string(),};- cached.write(repo, branch);+ cached.write(repo, &branch.full_name);status}@@ -310,7 +390,7 @@ impl PrStatus {/// PR/MR detection always runs. Workflow/pipeline fallback only runs if `has_upstream`.fn detect_uncached(repo: &Repository,- branch: &str,+ branch: &CiBranchName,local_head: &str,has_upstream: bool,) -> Option<Self> {@@ -318,8 +398,9 @@ impl PrStatus {let project_config = repo.load_project_config().ok().flatten();let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());- // Determine platform (config override or URL detection)- let platform = get_platform_for_repo(repo, platform_override);+ // Determine platform (config override, branch's remote, or any remote URL)+ // For remote branches, use their specific remote to get the correct platform+ let platform = get_platform_for_repo(repo, platform_override, branch.remote.as_deref());match platform {Some(p) => p.detect_ci(repo, branch, local_head, has_upstream),diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rsindex 892be5116..9810aede9 100644--- a/src/commands/list/ci_status/platform.rs+++ b/src/commands/list/ci_status/platform.rs@@ -5,7 +5,7 @@use worktrunk::git::{GitRemoteUrl, Repository};-use super::{PrStatus, github, gitlab, tool_available};+use super::{CiBranchName, PrStatus, github, gitlab, tool_available};/// CI platform detected from project config override or remote URL.///@@ -29,7 +29,12 @@ impl CiPlatform {}/// Detect CI status from PR/MR.- fn detect_pr_mr(self, repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+ fn detect_pr_mr(+ self,+ repo: &Repository,+ branch: &CiBranchName,+ local_head: &str,+ ) -> Option<PrStatus> {match self {Self::GitHub => github::detect_github(repo, branch, local_head),Self::GitLab => gitlab::detect_gitlab(repo, branch, local_head),@@ -37,10 +42,16 @@ impl CiPlatform {}/// Detect CI status from branch workflow/pipeline (fallback when no PR/MR).- fn detect_branch(self, repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+ fn detect_branch(+ self,+ repo: &Repository,+ branch: &CiBranchName,+ local_head: &str,+ ) -> Option<PrStatus> {match self {Self::GitHub => github::detect_github_commit_checks(repo, local_head),- Self::GitLab => gitlab::detect_gitlab_pipeline(branch, local_head),+ // GitLab pipeline uses the bare branch name (not "origin/feature")+ Self::GitLab => gitlab::detect_gitlab_pipeline(&branch.name, local_head),}}@@ -50,7 +61,7 @@ impl CiPlatform {pub(super) fn detect_ci(self,repo: &Repository,- branch: &str,+ branch: &CiBranchName,local_head: &str,has_upstream: bool,) -> Option<PrStatus> {@@ -81,14 +92,19 @@ pub fn detect_platform_from_url(url: &str) -> Option<CiPlatform> {}}-/// Get the CI platform for a repository.+/// Get the CI platform for a repository, optionally prioritizing a specific remote.+///+/// Priority order:+/// 1. Project config `ci.platform` override (if provided)+/// 2. The specific remote's URL (if `remote_hint` is provided)+/// 3. Any remote URL that matches a known platform///-/// If `platform_override` is provided (from project config `ci.platform`),-/// uses that value directly. Otherwise, searches all remote URLs for a-/// supported platform (GitHub or GitLab).+/// For remote branches, pass the branch's remote as `remote_hint` to ensure+/// the correct platform is detected in mixed-remote repos (e.g., GitHub + GitLab).pub fn get_platform_for_repo(repo: &Repository,platform_override: Option<&str>,+ remote_hint: Option<&str>,) -> Option<CiPlatform> {// Config override takes precedenceif let Some(platform_str) = platform_override {@@ -102,6 +118,19 @@ pub fn get_platform_for_repo();}+ // If we have a specific remote hint (e.g., from a remote branch), use that first+ if let Some(remote_name) = remote_hint+ && let Some(url) = repo.remote_url(remote_name)+ && let Some(platform) = detect_platform_from_url(&url)+ {+ log::debug!(+ "Detected CI platform {} from remote '{}' (hint)",+ platform,+ remote_name+ );+ return Some(platform);+ }+// Search all remotes for a supported platformfor (remote_name, url) in repo.all_remote_urls() {if let Some(platform) = detect_platform_from_url(&url) {diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex fd7a55df5..630d64e38 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -235,19 +235,28 @@ pub fn work_items_for_worktree(/// branch. Branches have fewer tasks than worktrees (no working tree operations).////// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.+/// The `is_remote` flag indicates whether this is a remote-tracking branch (e.g., "origin/feature")+/// vs a local branch. This is known definitively at collection time and avoids guessing later.pub fn work_items_for_branch(repo: &Repository,branch_name: &str,commit_sha: &str,item_idx: usize,+ is_remote: bool,options: &CollectOptions,expected_results: &Arc<ExpectedResults>,) -> Vec<WorkItem> {let skip = &options.skip_tasks;+ let branch_ref = if is_remote {+ BranchRef::remote_branch(branch_name, commit_sha)+ } else {+ BranchRef::local_branch(branch_name, commit_sha)+ };+let ctx = TaskContext {repo: repo.clone(),- branch_ref: BranchRef::branch_only(branch_name, commit_sha),+ branch_ref,item_idx,item_url: None, // Branches without worktrees don't have URLs};diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 200ce52ee..4dfde3dea 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -620,28 +620,24 @@ pub fn collect(let repo_clone = repo.clone();// Prepare branch data if needed (before moving into closure)- let branch_data: Vec<(usize, String, String)> = if show_branches || show_remotes {- let mut all_branches = Vec::new();- if show_branches {- all_branches.extend(- branches_without_worktrees- .iter()- .enumerate()- .map(|(idx, (name, sha))| (branch_start_idx + idx, name.clone(), sha.clone())),- );- }- if show_remotes {- all_branches.extend(- remote_branches- .iter()- .enumerate()- .map(|(idx, (name, sha))| (remote_start_idx + idx, name.clone(), sha.clone())),- );- }- all_branches- } else {- Vec::new()- };+ // Tuple: (item_idx, branch_name, commit_sha, is_remote)+ let branch_data: Vec<(usize, String, String, bool)> =+ if show_branches || show_remotes {+ let mut all_branches = Vec::new();+ if show_branches {+ all_branches.extend(branches_without_worktrees.iter().enumerate().map(+ |(idx, (name, sha))| (branch_start_idx + idx, name.clone(), sha.clone(), false),+ ));+ }+ if show_remotes {+ all_branches.extend(remote_branches.iter().enumerate().map(+ |(idx, (name, sha))| (remote_start_idx + idx, name.clone(), sha.clone(), true),+ ));+ }+ all_branches+ } else {+ Vec::new()+ };worktrunk::shell_exec::trace_instant("Spawning worker thread");std::thread::spawn(move || {@@ -662,12 +658,13 @@ pub fn collect(}// Branch work items (local + remote)- for (item_idx, branch_name, commit_sha) in &branch_data {+ for (item_idx, branch_name, commit_sha, is_remote) in &branch_data {all_work_items.extend(work_items_for_branch(&repo_clone,branch_name,commit_sha,*item_idx,+ *is_remote,&options,&expected_results_clone,));diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex b52c04107..403a5df35 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -8,7 +8,7 @@ use std::time::Duration;use worktrunk::git::{LineDiff, Repository};-use super::super::ci_status::PrStatus;+use super::super::ci_status::{CiBranchName, PrStatus};use super::super::model::{ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, UpstreamStatus,WorkingTreeStatus,@@ -589,6 +589,10 @@ impl Task for UpstreamTask {/// Always checks for open PRs/MRs regardless of upstream tracking./// For branch workflow/pipeline fallback (no PR), requires upstream tracking/// to prevent false matches from similarly-named branches on the remote.+///+/// Remote branches (e.g., "origin/feature") are treated as having upstream+/// by definition - they ARE the upstream. This enables workflow/pipeline+/// fallback for remote-only branches shown via `wt list --remotes`.pub struct CiStatusTask;impl Task for CiStatusTask {@@ -597,8 +601,10 @@ impl Task for CiStatusTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let repo = &ctx.repo;let pr_status = ctx.branch_ref.branch.as_deref().and_then(|branch| {- let has_upstream = repo.branch(branch).upstream().ok().flatten().is_some();- PrStatus::detect(repo, branch, &ctx.branch_ref.commit_sha, has_upstream)+ // Use from_branch_ref with the authoritative is_remote flag+ // rather than guessing from the branch name+ let ci_branch = CiBranchName::from_branch_ref(branch, ctx.branch_ref.is_remote, repo);+ PrStatus::detect(repo, &ci_branch, &ctx.branch_ref.commit_sha)});Ok(TaskResult::CiStatus {diff --git a/src/commands/process.rs b/src/commands/process.rsindex b772984fc..958e8ff8b 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -272,49 +272,50 @@ mod tests {#[test]fn test_sanitize_for_filename() {- // Path separators- assert_eq!(sanitize_for_filename("feature/branch"), "feature-branch");- assert_eq!(sanitize_for_filename("feature\\branch"), "feature-branch");+ // Path separators (hash suffix appended)+ assert!(sanitize_for_filename("feature/branch").starts_with("feature-branch-"));+ assert!(sanitize_for_filename("feature\\branch").starts_with("feature-branch-"));// Windows-illegal characters- assert_eq!(sanitize_for_filename("bug:123"), "bug-123");- assert_eq!(sanitize_for_filename("fix<angle>"), "fix-angle-");- assert_eq!(sanitize_for_filename("fix|pipe"), "fix-pipe");- assert_eq!(sanitize_for_filename("fix?question"), "fix-question");- assert_eq!(sanitize_for_filename("fix*wildcard"), "fix-wildcard");- assert_eq!(sanitize_for_filename("fix\"quotes\""), "fix-quotes-");+ assert!(sanitize_for_filename("bug:123").starts_with("bug-123-"));+ assert!(sanitize_for_filename("fix<angle>").starts_with("fix-angle-"));+ assert!(sanitize_for_filename("fix|pipe").starts_with("fix-pipe-"));+ assert!(sanitize_for_filename("fix?question").starts_with("fix-question-"));+ assert!(sanitize_for_filename("fix*wildcard").starts_with("fix-wildcard-"));+ assert!(sanitize_for_filename("fix\"quotes\"").starts_with("fix-quotes-"));// Multiple special characters- assert_eq!(- sanitize_for_filename("a/b\\c<d>e:f\"g|h?i*j"),- "a-b-c-d-e-f-g-h-i-j"- );+ assert!(sanitize_for_filename("a/b\\c<d>e:f\"g|h?i*j").starts_with("a-b-c-d-e-f-g-h-i-j-"));- // Already safe- assert_eq!(sanitize_for_filename("normal-branch"), "normal-branch");- assert_eq!(- sanitize_for_filename("branch_with_underscore"),- "branch_with_underscore"+ // Already safe (still gets hash suffix)+ assert!(sanitize_for_filename("normal-branch").starts_with("normal-branch-"));+ assert!(+ sanitize_for_filename("branch_with_underscore").starts_with("branch_with_underscore-"));// Windows reserved device names (must be prefixed to avoid conflicts)- assert_eq!(sanitize_for_filename("CON"), "_CON");- assert_eq!(sanitize_for_filename("con"), "_con");- assert_eq!(sanitize_for_filename("PRN"), "_PRN");- assert_eq!(sanitize_for_filename("AUX"), "_AUX");- assert_eq!(sanitize_for_filename("NUL"), "_NUL");- assert_eq!(sanitize_for_filename("COM1"), "_COM1");- assert_eq!(sanitize_for_filename("com9"), "_com9");- assert_eq!(sanitize_for_filename("LPT1"), "_LPT1");- assert_eq!(sanitize_for_filename("lpt9"), "_lpt9");+ assert!(sanitize_for_filename("CON").starts_with("_CON-"));+ assert!(sanitize_for_filename("con").starts_with("_con-"));+ assert!(sanitize_for_filename("PRN").starts_with("_PRN-"));+ assert!(sanitize_for_filename("AUX").starts_with("_AUX-"));+ assert!(sanitize_for_filename("NUL").starts_with("_NUL-"));+ assert!(sanitize_for_filename("COM1").starts_with("_COM1-"));+ assert!(sanitize_for_filename("com9").starts_with("_com9-"));+ assert!(sanitize_for_filename("LPT1").starts_with("_LPT1-"));+ assert!(sanitize_for_filename("lpt9").starts_with("_lpt9-"));// COM0/LPT0 are NOT reserved (only 1-9 are)- assert_eq!(sanitize_for_filename("COM0"), "COM0");- assert_eq!(sanitize_for_filename("LPT0"), "LPT0");+ assert!(sanitize_for_filename("COM0").starts_with("COM0-"));+ assert!(sanitize_for_filename("LPT0").starts_with("LPT0-"));// Longer names are fine- assert_eq!(sanitize_for_filename("CONSOLE"), "CONSOLE");- assert_eq!(sanitize_for_filename("COM10"), "COM10");+ assert!(sanitize_for_filename("CONSOLE").starts_with("CONSOLE-"));+ assert!(sanitize_for_filename("COM10").starts_with("COM10-"));++ // Collision avoidance: different inputs produce different outputs+ let a = sanitize_for_filename("feature/x");+ let b = sanitize_for_filename("feature-x");+ assert_ne!(a, b, "should not collide: {a} vs {b}");}#[test]diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex dbd6b3f76..61cbc8471 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -159,7 +159,8 @@ pub fn sanitize_db(s: &str) -> String {/// Generate a 3-character hash suffix from a string.////// Uses base36 (0-9, a-z) for a compact representation with 46,656 unique values.-fn short_hash(s: &str) -> String {+/// Used by `sanitize_db` and `sanitize_for_filename` to avoid collisions.+pub fn short_hash(s: &str) -> String {let mut h = std::collections::hash_map::DefaultHasher::new();s.hash(&mut h);let hash = h.finish();diff --git a/src/config/mod.rs b/src/config/mod.rsindex 4292eb999..5097c09f6 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -83,7 +83,7 @@ pub use deprecation::normalize_template_vars;pub use deprecation::{key_belongs_in, warn_unknown_fields};pub use expansion::{DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, expand_template, redact_credentials,- sanitize_branch_name, sanitize_db,+ sanitize_branch_name, sanitize_db, short_hash,};pub use hooks::HooksConfig;pub use project::{diff --git a/src/git/mod.rs b/src/git/mod.rsindex 9cb580e85..786368a36 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -340,7 +340,8 @@ pub enum HookType {/// # Construction////// - From a worktree: `BranchRef::from(&worktree_info)`-/// - For a branch-only item: `BranchRef::branch_only("feature", "abc123")`+/// - For a local branch: `BranchRef::local_branch("feature", "abc123")`+/// - For a remote branch: `BranchRef::remote_branch("origin/feature", "abc123")`////// # Working Tree Access///@@ -348,7 +349,7 @@ pub enum HookType {/// which returns `Some(WorkingTree)` only when this ref has a worktree path.#[derive(Debug, Clone)]pub struct BranchRef {- /// Branch name (e.g., "main", "feature/auth").+ /// Branch name (e.g., "main", "feature/auth", "origin/feature")./// None for detached HEAD.pub branch: Option<String>,/// Commit SHA this branch/worktree points to.@@ -356,17 +357,35 @@ pub struct BranchRef {/// Path to worktree, if this branch has one./// None for branch-only items (remote branches, local branches without worktrees).pub worktree_path: Option<PathBuf>,+ /// True if this is a remote-tracking ref (e.g., "origin/feature").+ /// Remote branches inherently exist on the remote and don't need push config.+ // TODO(full-refs): Consider refactoring to store full refs (e.g., "refs/remotes/origin/feature"+ // or "refs/heads/feature") instead of short names + is_remote flag. Full refs are self-describing+ // and unambiguous, but would require changes throughout the codebase and user input resolution.+ pub is_remote: bool,}impl BranchRef {- /// Create a BranchRef for a branch without a worktree.+ /// Create a BranchRef for a local branch without a worktree.+ pub fn local_branch(branch: &str, commit_sha: &str) -> Self {+ Self {+ branch: Some(branch.to_string()),+ commit_sha: commit_sha.to_string(),+ worktree_path: None,+ is_remote: false,+ }+ }++ /// Create a BranchRef for a remote-tracking branch.///- /// Used for remote-only branches or local branches that don't have a worktree.- pub fn branch_only(branch: &str, commit_sha: &str) -> Self {+ /// Remote branches (e.g., "origin/feature") are refs under refs/remotes/.+ /// They inherently exist on the remote and don't need upstream tracking config.+ pub fn remote_branch(branch: &str, commit_sha: &str) -> Self {Self {branch: Some(branch.to_string()),commit_sha: commit_sha.to_string(),worktree_path: None,+ is_remote: true,}}@@ -392,6 +411,7 @@ impl From<&WorktreeInfo> for BranchRef {branch: wt.branch.clone(),commit_sha: wt.head.clone(),worktree_path: Some(wt.path.clone()),+ is_remote: false, // Worktrees are always local}}}@@ -637,16 +657,29 @@ mod tests {Some(PathBuf::from("/repo.feature")));assert!(branch_ref.has_worktree());+ assert!(!branch_ref.is_remote); // Worktrees are always local}#[test]- fn test_branch_ref_branch_only() {- let branch_ref = BranchRef::branch_only("feature", "abc123");+ fn test_branch_ref_local_branch() {+ let branch_ref = BranchRef::local_branch("feature", "abc123");assert_eq!(branch_ref.branch, Some("feature".to_string()));assert_eq!(branch_ref.commit_sha, "abc123");assert_eq!(branch_ref.worktree_path, None);assert!(!branch_ref.has_worktree());+ assert!(!branch_ref.is_remote);+ }++ #[test]+ fn test_branch_ref_remote_branch() {+ let branch_ref = BranchRef::remote_branch("origin/feature", "abc123");++ assert_eq!(branch_ref.branch, Some("origin/feature".to_string()));+ assert_eq!(branch_ref.commit_sha, "abc123");+ assert_eq!(branch_ref.worktree_path, None);+ assert!(!branch_ref.has_worktree());+ assert!(branch_ref.is_remote);}#[test]diff --git a/src/path.rs b/src/path.rsindex e65696775..e154699ca 100644--- a/src/path.rs+++ b/src/path.rs@@ -1,5 +1,6 @@use std::path::{Path, PathBuf};+use crate::config::short_hash;#[cfg(windows)]use crate::shell_exec::{Cmd, ShellConfig};@@ -103,7 +104,12 @@ pub fn format_path_for_display(path: &Path) -> String {/// Sanitize a string for use as a filename on all platforms.////// Replaces invalid characters and control characters with `-`, trims trailing-/// dots/spaces (Windows), and prefixes reserved device names with `_`.+/// dots/spaces (Windows), prefixes reserved device names with `_`, and appends+/// a 3-character hash suffix for collision avoidance.+///+/// The hash ensures unique outputs for inputs that would otherwise collide+/// (e.g., `origin/feature` and `origin-feature` both sanitize to `origin-feature`+/// but get different hash suffixes).pub fn sanitize_for_filename(value: &str) -> String {let mut result: String = value.chars()@@ -130,12 +136,17 @@ pub fn sanitize_for_filename(value: &str) -> String {&& upper.chars().nth(3).is_some_and(|c| matches!(c, '1'..='9')));if is_reserved {- format!("_{result}")+ result = format!("_{result}");} else if result.is_empty() {- "_empty".to_string()- } else {- result+ result = "_empty".to_string();+ }++ // Append hash suffix for collision avoidance (computed from original input)+ if !result.ends_with('-') {+ result.push('-');}+ result.push_str(&short_hash(value));+ result}#[cfg(test)]@@ -249,24 +260,35 @@ mod tests {#[test]fn test_sanitize_for_filename_replaces_invalid_chars() {- assert_eq!(sanitize_for_filename("foo/bar"), "foo-bar");- assert_eq!(sanitize_for_filename("name:with?chars"), "name-with-chars");+ assert!(sanitize_for_filename("foo/bar").starts_with("foo-bar-"));+ assert!(sanitize_for_filename("name:with?chars").starts_with("name-with-chars-"));}#[test]fn test_sanitize_for_filename_trims_trailing_dots_and_spaces() {- assert_eq!(sanitize_for_filename("file. "), "file");- assert_eq!(sanitize_for_filename("file..."), "file");+ assert!(sanitize_for_filename("file. ").starts_with("file-"));+ assert!(sanitize_for_filename("file...").starts_with("file-"));}#[test]fn test_sanitize_for_filename_prefixes_reserved_names() {- assert_eq!(sanitize_for_filename("CON"), "_CON");- assert_eq!(sanitize_for_filename("com1"), "_com1");+ assert!(sanitize_for_filename("CON").starts_with("_CON-"));+ assert!(sanitize_for_filename("com1").starts_with("_com1-"));}#[test]fn test_sanitize_for_filename_handles_empty() {- assert_eq!(sanitize_for_filename(""), "_empty");+ assert!(sanitize_for_filename("").starts_with("_empty-"));+ }++ #[test]+ fn test_sanitize_for_filename_avoids_collisions() {+ // These would collide without the hash suffix+ let a = sanitize_for_filename("origin/feature");+ let b = sanitize_for_filename("origin-feature");++ assert_ne!(a, b, "collision: {a} == {b}");+ assert!(a.starts_with("origin-feature-"));+ assert!(b.starts_with("origin-feature-"));}}diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex d9a3ea6a3..8fbcdea92 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -1,6 +1,6 @@use crate::common::{BareRepoTest, TestRepo, TestRepoBase, canonicalize, configure_directive_file, directive_file,- repo, setup_temp_snapshot_settings, wait_for, wait_for_file, wt_command,+ repo, setup_temp_snapshot_settings, wait_for, wait_for_file_count, wt_command,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -416,13 +416,34 @@ fn test_bare_repo_background_logs_location() {// Wait for background process to create log file (poll instead of fixed sleep)// The key test is that the path is correct, not that content was written (background processes are flaky in tests)- let log_path = test.bare_repo_path().join("wt-logs/feature-remove.log");- wait_for_file(&log_path);+ // Log filename has hash suffix: feature-<hash>-remove-<hash>.log+ let log_dir = test.bare_repo_path().join("wt-logs");+ wait_for_file_count(&log_dir, "log", 1);++ // Verify the log file matches expected pattern (feature-*-remove-*.log)+ let log_files: Vec<_> = std::fs::read_dir(&log_dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| {+ let name = e.file_name().to_string_lossy().to_string();+ name.starts_with("feature-") && name.contains("-remove-") && name.ends_with(".log")+ })+ .collect();+ assert_eq!(+ log_files.len(),+ 1,+ "Expected exactly one feature-*-remove-*.log file, found: {:?}",+ log_files+ );// Verify it's NOT in the worktree's .git directory (which doesn't exist for linked worktrees)- let wrong_path = main_worktree.join(".git/wt-logs/feature-remove.log");+ let wrong_dir = main_worktree.join(".git/wt-logs");assert!(- !wrong_path.exists(),+ !wrong_dir.exists()+ || std::fs::read_dir(&wrong_dir)+ .map(|d| d.count())+ .unwrap_or(0)+ == 0,"Log should NOT be in worktree's .git directory");}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 7956b3a29..b78c95592 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -398,6 +398,83 @@ fn test_list_with_remotes_filters_tracked_branches(#[from(repo_with_remote)] rep});}+#[rstest]+fn test_list_with_remotes_and_full(#[from(repo_with_remote)] repo: TestRepo) {+ // Create remote-only branches (no local tracking)+ repo.create_branch("feature-remote");+ repo.push_branch("feature-remote");+ repo.run_git(&["branch", "-D", "feature-remote"]);++ // Set a GitHub-style URL AFTER pushing so platform detection works+ // This exercises the remote_hint path in get_platform_for_repo+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);++ // Run with --full to trigger CiBranchName::from_branch_ref for remote branches+ // This exercises the is_remote=true code path even without gh/glab auth+ // (CI detection will return None, but the branch parsing is still covered)+ assert_cmd_snapshot!({+ let mut cmd = list_snapshots::command(&repo, repo.root_path());+ cmd.args(["--remotes", "--full"]);+ cmd+ });+}++#[rstest]+fn test_list_with_orphaned_remote_ref(#[from(repo_with_remote)] repo: TestRepo) {+ // Create a remote-tracking ref for a non-existent remote to exercise the+ // fallback path in CiBranchName::from_branch_ref (lines 64-75)+ // This simulates a ref that remains after a remote is deleted+ let head_sha = repo+ .git_command()+ .args(["rev-parse", "HEAD"])+ .output()+ .unwrap()+ .stdout;+ let head_sha = String::from_utf8_lossy(&head_sha);+ let head_sha = head_sha.trim();+ repo.run_git(&[+ "update-ref",+ "refs/remotes/deleted-remote/orphaned-branch",+ head_sha,+ ]);++ // Verify the ref exists but the remote doesn't+ let remotes = repo.git_command().args(["remote"]).output().unwrap().stdout;+ let remotes = String::from_utf8_lossy(&remotes);+ assert!(+ !remotes.contains("deleted-remote"),+ "deleted-remote should not exist"+ );++ // Run with --remotes --full to trigger the fallback path+ // The orphaned ref should be parsed using split_once('/') as fallback+ // Note: We don't use snapshot testing here because the spinner character+ // in stderr is non-deterministic (timing-dependent)+ let output = repo+ .wt_command()+ .args(["list", "--remotes", "--full"])+ .output()+ .unwrap();+ assert!(output.status.success(), "command should succeed");++ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(+ stdout.contains("deleted-remote/orphaned-branch"),+ "should show orphaned remote branch in output: {stdout}"+ );++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("unknown remote 'deleted-remote'"),+ "should warn about unknown remote: {stderr}"+ );+}+#[rstest]fn test_list_json_with_display_fields(mut repo: TestRepo) {repo.commit("Initial commit on main");@@ -1539,11 +1616,8 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_let cache_dir = git_path.join("wt-cache").join("ci-status");std::fs::create_dir_all(&cache_dir).unwrap();- // Sanitize branch name for filename (replace / and \ with -)- let safe_branch: String = branch- .chars()- .map(|c| if c == '/' || c == '\\' { '-' } else { c })- .collect();+ // Use the same sanitization as production code for cache filenames+ let safe_branch = worktrunk::path::sanitize_for_filename(branch);let cache_file = cache_dir.join(format!("{safe_branch}.json"));std::fs::write(&cache_file, &cache_json).unwrap();}diff --git a/tests/snapshots/integration__integration_tests__list__list_with_remotes_and_full.snap b/tests/snapshots/integration__integration_tests__list__list_with_remotes_and_full.snapnew file mode 100644index 000000000..71e27a468--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__list_with_remotes_and_full.snap@@ -0,0 +1,46 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ - "--remotes"+ - "--full"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "-1"+ WT_TEST_EPOCH: "1735776000"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mmain…±[0m [1mPath[0m [1mRemote⇅[0m [1mCI[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [2m^[22m[2m|[22m . [2m|[0m [2m05a4a45d[0m [2m16h[0m [2mInitial commit++ feature-a [2m↑[22m [32m↑1[0m [32m+1[0m ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file++ feature-b [2m↑[22m [32m↑1[0m [32m+1[0m ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file++ feature-c [2m↑[22m [32m↑1[0m [32m+1[0m ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file+ [2morigin/feature-remote[0m [2m/[22m[2m_[22m [2m05a4a45d[0m [2m16h[0m [2mInitial commit++[2m○[22m [2mShowing 4 worktrees, 1 remote branches, 3 ahead++----- stderr -----