Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Fix fork CI queries, branch tracking remote check, and diverged integration target (#1812)

Maximilian Roos68869761dabd
diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rs
index 94245e1f0..ade710228 100644
--- a/src/commands/list/ci_status/github.rs
+++ b/src/commands/list/ci_status/github.rs
@@ -3,7 +3,7 @@
//! Detects CI status from GitHub PRs and workflow runs using the `gh` CLI.
use serde::Deserialize;
-use worktrunk::git::{GitRemoteUrl, Repository, parse_remote_owner};
+use worktrunk::git::{Repository, parse_owner_repo};
use super::{
CiBranchName, CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error,
@@ -19,8 +19,21 @@ use super::{
/// `url.insteadOf` aliases.
fn github_owner_repo(repo: &Repository) -> Option<(String, String)> {
let (_, url) = repo.find_forge_remote(|parsed| parsed.is_github())?;
- let parsed = GitRemoteUrl::parse(&url)?;
- Some((parsed.owner().to_string(), parsed.repo().to_string()))
+ 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.
@@ -51,16 +64,7 @@ pub(super) fn detect_github(
// 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 = if let Some(remote_name) = &branch.remote {
- // Remote branch - get owner from the remote's effective URL
- repo.effective_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 branch_owner = github_owner_repo_for_branch(repo, branch).map(|(owner, _)| owner);
let Some(branch_owner) = branch_owner else {
log::debug!(
@@ -162,9 +166,14 @@ pub(super) fn detect_github(
/// 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, local_head: &str) -> Option<PrStatus> {
+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(repo)?;
+ let (owner, repo_name) =
+ github_owner_repo_for_branch(repo, branch).or_else(|| github_owner_repo(repo))?;
// Use GitHub's check-runs API to get all checks for this commit
let output = match non_interactive_cmd("gh")
@@ -216,7 +225,7 @@ pub(super) fn detect_github_commit_checks(repo: &Repository, local_head: &str) -
/// GitHub PR info from `gh pr list --json ...`
///
/// Note: We include `headRepositoryOwner` for client-side filtering by source fork.
-/// See [`parse_remote_owner`] for why this is necessary.
+/// 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)]
@@ -229,7 +238,7 @@ pub(super) struct GitHubPrInfo {
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_remote_owner`]).
+ /// Used to filter PRs by source fork (see `parse_owner_repo()`).
#[serde(rename = "headRepositoryOwner")]
pub head_repository_owner: Option<HeadRepositoryOwner>,
}
diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rs
index f8bac536b..c90777a09 100644
--- a/src/commands/list/ci_status/gitlab.rs
+++ b/src/commands/list/ci_status/gitlab.rs
@@ -253,7 +253,7 @@ pub(super) fn detect_gitlab_pipeline(branch: &str, local_head: &str) -> Option<P
/// Use [`fetch_mr_details`] with the `iid` to get complete MR info.
///
/// We include `source_project_id` for client-side filtering by source project.
-/// See [`worktrunk::git::parse_remote_owner`] for why we filter by source, not by author.
+/// See `parse_owner_repo()` for why we filter by source, not by author.
#[derive(Debug, Deserialize)]
struct GitLabMrListEntry {
/// The internal MR ID (used to fetch full details via `glab mr view <iid>`)
diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rs
index 5dea0d5df..759385618 100644
--- a/src/commands/list/ci_status/platform.rs
+++ b/src/commands/list/ci_status/platform.rs
@@ -71,7 +71,7 @@ impl CiPlatform {
local_head: &str,
) -> Option<PrStatus> {
match self {
- Self::GitHub => github::detect_github_commit_checks(repo, local_head),
+ Self::GitHub => github::detect_github_commit_checks(repo, branch, local_head),
// GitLab pipeline uses the bare branch name (not "origin/feature")
Self::GitLab => gitlab::detect_gitlab_pipeline(&branch.name, local_head),
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 9597329fe..754505adb 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -108,11 +108,25 @@ fn resolve_fork_ref(
let ref_type = provider.ref_type();
let repo_root = repo.repo_path()?;
let local_branch = remote_ref::local_branch_name(info);
+ let expected_remote = match ref_type {
+ RefType::Pr => match find_github_remote(repo, info) {
+ Ok(remote) => Some(remote),
+ Err(e) => {
+ log::debug!("Could not resolve GitHub remote for PR: {e:#}");
+ None
+ }
+ },
+ RefType::Mr => None,
+ };
// Check if branch already exists and is tracking this ref
- if let Some(tracks_this) =
- remote_ref::branch_tracks_ref(repo_root, &local_branch, provider, number)
- {
+ if let Some(tracks_this) = remote_ref::branch_tracks_ref(
+ repo_root,
+ &local_branch,
+ provider,
+ number,
+ expected_remote.as_deref(),
+ ) {
if tracks_this {
eprintln!(
"{}",
@@ -132,9 +146,13 @@ fn resolve_fork_ref(
// Branch exists but doesn't track this ref - try prefixed name (GitHub only)
if let Some(prefixed) = info.prefixed_local_branch_name() {
- if let Some(prefixed_tracks) =
- remote_ref::branch_tracks_ref(repo_root, &prefixed, provider, number)
- {
+ if let Some(prefixed_tracks) = remote_ref::branch_tracks_ref(
+ repo_root,
+ &prefixed,
+ provider,
+ number,
+ expected_remote.as_deref(),
+ ) {
if prefixed_tracks {
eprintln!(
"{}",
@@ -189,7 +207,7 @@ fn resolve_fork_ref(
// Resolve remote and URLs based on platform.
let (fork_push_url, remote) = match ref_type {
RefType::Pr => {
- // GitHub: URLs already in info, just find remote
+ // GitHub: URLs already in info, just find remote.
let remote = find_github_remote(repo, info)?;
(info.fork_push_url.clone(), remote)
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index b388e4048..747f03b54 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -269,18 +269,16 @@ use crate::shell_exec::Cmd;
///
/// Used by PR/MR checkout to detect when a branch name collision exists.
///
-/// TODO: This only checks `branch.<name>.merge`, not `branch.<name>.remote`. A branch
-/// could track the right ref but have the wrong remote configured, which matters for
-/// fork PRs/MRs where refs live on the target repo. Consider checking both values.
-///
/// # Arguments
/// * `repo_root` - Path to run git commands from
/// * `branch` - Local branch name to check
/// * `expected_ref` - Full ref path (e.g., `refs/pull/101/head` or `refs/merge-requests/42/head`)
+/// * `expected_remote` - Optional remote name that must also match `branch.<name>.remote`
pub fn branch_tracks_ref(
repo_root: &std::path::Path,
branch: &str,
expected_ref: &str,
+ expected_remote: Option<&str>,
) -> Option<bool> {
let config_key = format!("branch.{}.merge", branch);
let output = Cmd::new("git")
@@ -308,7 +306,29 @@ pub fn branch_tracks_ref(
}
let merge_ref = String::from_utf8_lossy(&output.stdout).trim().to_string();
- Some(merge_ref == expected_ref)
+ if merge_ref != expected_ref {
+ return Some(false);
+ }
+
+ let Some(expected_remote) = expected_remote else {
+ return Some(true);
+ };
+
+ let remote_key = format!("branch.{}.remote", branch);
+ let remote_output = Cmd::new("git")
+ .args(["config", "--get", &remote_key])
+ .current_dir(repo_root)
+ .run()
+ .ok()?;
+
+ if !remote_output.status.success() {
+ return Some(false);
+ }
+
+ let remote = String::from_utf8_lossy(&remote_output.stdout)
+ .trim()
+ .to_string();
+ Some(remote == expected_remote)
}
// Note: HookType and WorktreeInfo are defined in this module and are already public.
@@ -747,9 +767,18 @@ mod tests {
.current_dir(&repo)
.run()
.unwrap();
+ crate::shell_exec::Cmd::new("git")
+ .args(["config", "branch.pr-branch.remote", "origin"])
+ .current_dir(&repo)
+ .run()
+ .unwrap();
assert_eq!(
- branch_tracks_ref(&repo, "pr-branch", "refs/pull/101/head"),
+ branch_tracks_ref(&repo, "pr-branch", "refs/pull/101/head", None),
+ Some(true),
+ );
+ assert_eq!(
+ branch_tracks_ref(&repo, "pr-branch", "refs/pull/101/head", Some("origin")),
Some(true),
);
}
@@ -771,7 +800,33 @@ mod tests {
// Ask about a different ref — should return Some(false)
assert_eq!(
- branch_tracks_ref(&repo, "pr-branch", "refs/pull/999/head"),
+ branch_tracks_ref(&repo, "pr-branch", "refs/pull/999/head", None),
+ Some(false),
+ );
+ }
+
+ #[test]
+ fn test_branch_tracks_ref_wrong_remote() {
+ let (_tmp, repo) = init_test_repo();
+
+ crate::shell_exec::Cmd::new("git")
+ .args(["branch", "pr-branch"])
+ .current_dir(&repo)
+ .run()
+ .unwrap();
+ crate::shell_exec::Cmd::new("git")
+ .args(["config", "branch.pr-branch.merge", "refs/pull/101/head"])
+ .current_dir(&repo)
+ .run()
+ .unwrap();
+ crate::shell_exec::Cmd::new("git")
+ .args(["config", "branch.pr-branch.remote", "fork"])
+ .current_dir(&repo)
+ .run()
+ .unwrap();
+
+ assert_eq!(
+ branch_tracks_ref(&repo, "pr-branch", "refs/pull/101/head", Some("origin")),
Some(false),
);
}
@@ -789,7 +844,7 @@ mod tests {
// Branch exists but has no merge config — Some(false)
assert_eq!(
- branch_tracks_ref(&repo, "local-only", "refs/pull/1/head"),
+ branch_tracks_ref(&repo, "local-only", "refs/pull/1/head", None),
Some(false),
);
}
@@ -800,7 +855,7 @@ mod tests {
// Branch doesn't exist at all — None
assert_eq!(
- branch_tracks_ref(&repo, "no-such-branch", "refs/pull/1/head"),
+ branch_tracks_ref(&repo, "no-such-branch", "refs/pull/1/head", None),
None,
);
}
@@ -810,7 +865,7 @@ mod tests {
// Invalid repo path causes Cmd::run() to fail → .ok()? returns None
let bad_path = std::path::Path::new("/nonexistent/repo/path");
assert_eq!(
- branch_tracks_ref(bad_path, "main", "refs/pull/1/head"),
+ branch_tracks_ref(bad_path, "main", "refs/pull/1/head", None),
None,
);
}
@@ -834,13 +889,23 @@ mod tests {
.current_dir(&repo)
.run()
.unwrap();
+ crate::shell_exec::Cmd::new("git")
+ .args(["config", "branch.mr-branch.remote", "origin"])
+ .current_dir(&repo)
+ .run()
+ .unwrap();
assert_eq!(
- branch_tracks_ref(&repo, "mr-branch", "refs/merge-requests/42/head"),
+ branch_tracks_ref(
+ &repo,
+ "mr-branch",
+ "refs/merge-requests/42/head",
+ Some("origin"),
+ ),
Some(true),
);
assert_eq!(
- branch_tracks_ref(&repo, "mr-branch", "refs/pull/42/head"),
+ branch_tracks_ref(&repo, "mr-branch", "refs/pull/42/head", Some("origin")),
Some(false),
);
}
diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rs
index f617cc9ea..43989eaf3 100644
--- a/src/git/remote_ref/mod.rs
+++ b/src/git/remote_ref/mod.rs
@@ -79,9 +79,10 @@ pub fn branch_tracks_ref(
branch: &str,
provider: &dyn RemoteRefProvider,
number: u32,
+ expected_remote: Option<&str>,
) -> Option<bool> {
let expected_ref = provider.tracking_ref(number);
- crate::git::branch_tracks_ref(repo_root, branch, &expected_ref)
+ crate::git::branch_tracks_ref(repo_root, branch, &expected_ref, expected_remote)
}
/// Generate the local branch name for a remote ref.
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 104355b83..552449557 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -168,10 +168,10 @@ impl Repository {
/// Determine the effective target for integration checks.
///
- /// If the upstream of the local target (e.g., `origin/main`) is strictly ahead of
- /// the local target (i.e., local is an ancestor of upstream but not the same commit),
- /// uses the upstream. This handles the common case where a branch was merged remotely
- /// but the user hasn't pulled yet.
+ /// If the upstream of the local target (e.g., `origin/main`) contains commits that
+ /// the local target does not, uses the upstream. This handles both the common "local
+ /// branch is behind upstream" case and the diverged case where local has extra commits
+ /// but upstream contains a remote merge that local hasn't integrated yet.
///
/// When local and upstream are the same commit, prefers local for clearer messaging.
///
@@ -179,9 +179,6 @@ impl Repository {
///
/// Used by both `wt list` and `wt remove` to ensure consistent integration detection.
///
- /// TODO(future): When local and remote have diverged (neither is ancestor),
- /// check integration against both and delete only if integrated into both.
- /// Current behavior: uses only local in diverged state, may miss remote-merged branches.
pub fn effective_integration_target(&self, local_target: &str) -> String {
// Get the upstream ref for the local target (e.g., origin/main for main)
let upstream = match self.branch(local_target).upstream() {
@@ -194,14 +191,21 @@ impl Repository {
return local_target.to_string();
}
- // Check if local is strictly behind upstream (local is ancestor of upstream)
- // This means upstream has commits that local doesn't have
- // On error, fall back to local target (defensive: don't fail due to git errors)
+ // If upstream contains commits not present in local, prefer upstream so
+ // remotely merged branches still count as integrated after a fetch.
if self.is_ancestor(local_target, &upstream).unwrap_or(false) {
return upstream;
}
- local_target.to_string()
+ // If upstream is strictly behind local, local is more complete.
+ if self.is_ancestor(&upstream, local_target).unwrap_or(false) {
+ return local_target.to_string();
+ }
+
+ // Local and upstream have diverged (neither is ancestor of the other).
+ // Prefer upstream so remote merges are still visible to integration
+ // checks even while local has extra commits.
+ upstream
}
/// Get the cached integration target for this repository.
diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rs
index 040844f01..369c137dc 100644
--- a/tests/integration_tests/ci_status.rs
+++ b/tests/integration_tests/ci_status.rs
@@ -9,9 +9,16 @@
//! reliably locate its JSON data files. Use MOCK_DEBUG=1 to troubleshoot
//! path issues.
-use crate::common::{TestRepo, make_snapshot_cmd, repo, setup_snapshot_settings};
+use crate::common::{
+ TestRepo, make_snapshot_cmd,
+ mock_commands::{MockConfig, MockResponse},
+ repo, setup_snapshot_settings,
+};
+use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
+use std::path::Path;
+use std::process::Command;
/// Get the HEAD commit SHA for a branch
fn branch_sha(repo: &TestRepo, branch: &str) -> String {
@@ -51,6 +58,52 @@ fn run_ci_status_test(repo: &mut TestRepo, snapshot_name: &str, pr_json: &str, r
});
}
+/// Setup mock `gh` with configurable `pr list` and `api repos/.../check-runs`
+/// responses.
+fn setup_mock_gh_with_api_data(
+ repo: &TestRepo,
+ pr_json: &str,
+ api_responses: &[(&str, &str)],
+) -> std::path::PathBuf {
+ let mock_bin = repo.root_path().join("mock-bin");
+ std::fs::create_dir_all(&mock_bin).unwrap();
+
+ let mut gh = MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command("pr list", MockResponse::output(pr_json));
+
+ for (command, response) in api_responses {
+ gh = gh.command(command, MockResponse::output(response));
+ }
+
+ gh.command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+ MockConfig::new("glab")
+ .version("glab version 1.0.0 (mock)")
+ .command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+
+ mock_bin
+}
+
+/// Configure command environment for local gh/glab mocks.
+fn configure_mock_ci_env(cmd: &mut Command, mock_bin: &Path) {
+ cmd.env("MOCK_CONFIG_DIR", mock_bin);
+
+ let (path_var_name, current_path) = std::env::vars_os()
+ .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
+ .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
+ .unwrap_or(("PATH".to_string(), None));
+
+ let mut paths: Vec<std::path::PathBuf> = current_path
+ .as_deref()
+ .map(|p| std::env::split_paths(p).collect())
+ .unwrap_or_default();
+ paths.insert(0, mock_bin.to_path_buf());
+ let new_path = std::env::join_paths(&paths).unwrap();
+ cmd.env(path_var_name, new_path);
+}
+
/// Setup a repo with GitHub remote and feature worktree, returns head SHA
fn setup_github_repo_with_feature(repo: &mut TestRepo) -> String {
// Set origin URL (origin already exists from fixture, just update URL)
@@ -711,6 +764,54 @@ fn test_list_full_with_url_based_pushremote(mut repo: TestRepo) {
run_ci_status_test(&mut repo, "url_based_pushremote", &pr_json, "[]");
}
+/// When a branch has no PR yet, fallback check-runs detection should query the
+/// branch's pushremote repository rather than the first GitHub remote in the
+/// repo.
+#[rstest]
+fn test_list_full_with_branch_fallback_using_fork_pushremote(mut repo: TestRepo) {
+ setup_github_repo_with_feature(&mut repo);
+
+ let feature_a_sha = branch_sha(&repo, "feature-a");
+ repo.run_git(&[
+ "config",
+ "branch.feature-a.pushremote",
+ "https://github.com/fork-owner/test-repo.git",
+ ]);
+
+ let fork_checks = r#"[{"status":"COMPLETED","conclusion":"SUCCESS"}]"#;
+ let mock_bin = setup_mock_gh_with_api_data(
+ &repo,
+ "[]",
+ &[
+ (
+ &format!("api repos/upstream-owner/test-repo/commits/{feature_a_sha}/check-runs"),
+ "[]",
+ ),
+ (
+ &format!("api repos/fork-owner/test-repo/commits/{feature_a_sha}/check-runs"),
+ fork_checks,
+ ),
+ ],
+ );
+
+ let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
+ configure_mock_ci_env(&mut cmd, &mock_bin);
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "wt list should succeed");
+
+ let stdout = String::from_utf8_lossy(&output.stdout)
+ .ansi_strip()
+ .into_owned();
+ let feature_a_line = stdout
+ .lines()
+ .find(|line| line.contains("feature-a"))
+ .expect("expected feature-a line in wt list output");
+ assert!(
+ feature_a_line.contains("●"),
+ "expected feature-a to show passed branch CI from the fork repo fallback\nstdout:\n{stdout}",
+ );
+}
+
// =============================================================================
// GitLab error path tests
// =============================================================================
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 86e6bb604..6142835b0 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -3,6 +3,7 @@ use crate::common::{
make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,
setup_temp_snapshot_settings, wt_command,
};
+use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use path_slash::PathExt as _;
use rstest::rstest;
@@ -1234,6 +1235,112 @@ fn test_remove_squash_merged_on_remote(#[from(repo_with_remote)] repo: TestRepo)
));
}
+/// Like `test_remove_squash_merged_on_remote`, but local `main` also advances
+/// with a local-only commit after the fetch. Integration should still be
+/// detected via `origin/main`.
+#[rstest]
+fn test_remove_squash_merged_on_remote_when_local_main_diverged(
+ #[from(repo_with_remote)] repo: TestRepo,
+) {
+ let remote_path = repo.remote_path().unwrap();
+
+ repo.run_git(&["checkout", "-b", "feature-remote-squash-diverged"]);
+ std::fs::write(repo.root_path().join("feature-diverged.txt"), "initial").unwrap();
+ repo.run_git(&["add", "feature-diverged.txt"]);
+ repo.run_git(&["commit", "-m", "Add diverged feature"]);
+ std::fs::write(
+ repo.root_path().join("feature-diverged.txt"),
+ "final version",
+ )
+ .unwrap();
+ repo.run_git(&["add", "feature-diverged.txt"]);
+ repo.run_git(&["commit", "-m", "Finalize diverged feature"]);
+ repo.run_git(&["push", "-u", "origin", "feature-remote-squash-diverged"]);
+ repo.run_git(&["checkout", "main"]);
+
+ // Simulate a remote squash merge.
+ let github_sim = repo.home_path().join("github-sim-diverged");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-diverged",
+ ],
+ );
+ repo.run_git_in(
+ &github_sim,
+ &["merge", "--squash", "origin/feature-remote-squash-diverged"],
+ );
+ repo.run_git_in(&github_sim, &["commit", "-m", "Add diverged feature (#3)"]);
+ repo.run_git_in(&github_sim, &["push", "origin", "main"]);
+
+ // Fetch the remote squash merge, then create a local-only commit on main so
+ // local and upstream diverge.
+ repo.run_git(&["fetch", "origin"]);
+ std::fs::write(repo.root_path().join("local-only.txt"), "local only").unwrap();
+ repo.run_git(&["add", "local-only.txt"]);
+ repo.run_git(&["commit", "-m", "Local-only main commit"]);
+
+ let local_main = repo.git_output(&["rev-parse", "main"]);
+ let origin_main = repo.git_output(&["rev-parse", "origin/main"]);
+ assert_ne!(
+ local_main, origin_main,
+ "local main should diverge from origin/main"
+ );
+
+ let local_behind_remote = repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "main", "origin/main"])
+ .run()
+ .unwrap();
+ assert!(
+ !local_behind_remote.status.success(),
+ "local main should not be an ancestor of origin/main in diverged state"
+ );
+
+ let remote_behind_local = repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "origin/main", "main"])
+ .run()
+ .unwrap();
+ assert!(
+ !remote_behind_local.status.success(),
+ "origin/main should not be an ancestor of local main in diverged state"
+ );
+
+ let output = make_snapshot_cmd(&repo, "remove", &["feature-remote-squash-diverged"], None)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+
+ assert!(
+ stderr.contains("Removed branch feature-remote-squash-diverged"),
+ "expected branch to be removed once origin/main contains the squash merge\nstderr:\n{stderr}",
+ );
+ assert!(
+ stderr.contains("origin/main"),
+ "expected remove output to mention origin/main as the integration target\nstderr:\n{stderr}",
+ );
+
+ let branch_still_exists = repo
+ .git_command()
+ .args([
+ "rev-parse",
+ "--verify",
+ "--quiet",
+ "refs/heads/feature-remote-squash-diverged",
+ ])
+ .run()
+ .unwrap();
+ assert!(
+ !branch_still_exists.status.success(),
+ "feature branch should be deleted after successful remove"
+ );
+}
+
/// Like `test_remove_squash_merged_on_remote`, but main advances on the
/// remote after the squash merge.
/// Tests that `MergeAddsNothing` detection works through origin/main.
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 0dc1f02b6..ee2598dd8 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -3,6 +3,7 @@ use crate::common::{
make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,
setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wt_command,
};
+use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
@@ -2117,6 +2118,96 @@ fn test_switch_pr_fork_existing_different_pr(#[from(repo_with_remote)] repo: Tes
});
}
+/// Test fork PR where branch already exists with the same PR ref path but the
+/// wrong remote configured.
+///
+/// This branch should not be reused because push/pull would be wired to the
+/// wrong repository.
+#[rstest]
+fn test_switch_pr_fork_existing_same_pr_wrong_remote(#[from(repo_with_remote)] mut repo: TestRepo) {
+ repo.setup_custom_remote("fork", "main");
+
+ // Create a PR ref on the real PR remote.
+ repo.run_git(&["checkout", "-b", "pr-source"]);
+ fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
+ repo.run_git(&["add", "pr-file.txt"]);
+ repo.run_git(&["commit", "-m", "PR commit"]);
+ let commit_sha = repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .run()
+ .unwrap();
+ let sha = String::from_utf8_lossy(&commit_sha.stdout)
+ .trim()
+ .to_string();
+ repo.run_git(&["push", "origin", &format!("{sha}:refs/pull/42/head")]);
+ repo.run_git(&["checkout", "main"]);
+
+ // Create the branch with a stale tracking configuration pointing at a
+ // different remote that happens to use the same PR ref path.
+ let branch_name = "feature-fix";
+ repo.run_git(&["branch", branch_name, "main"]);
+ repo.run_git(&["config", &format!("branch.{branch_name}.remote"), "fork"]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{branch_name}.merge"),
+ "refs/pull/42/head",
+ ]);
+
+ // Set up GitHub URL and redirect (like test_switch_pr_fork).
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .run()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/owner/test-repo.git",
+ ]);
+ repo.run_git(&[
+ "config",
+ &format!("url.{bare_url}.insteadOf"),
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ let gh_response = r#"{
+ "title": "Add feature fix for edge case",
+ "user": {"login": "contributor"},
+ "state": "open",
+ "draft": false,
+ "head": {
+ "ref": "feature-fix",
+ "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
+ },
+ "base": {
+ "ref": "main",
+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}
+ },
+ "html_url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "switch should succeed");
+
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+ assert!(
+ stderr.contains("Using prefixed branch name contributor/feature-fix due to name conflict"),
+ "expected prefixed branch warning when existing branch tracks the PR on the wrong remote\nstderr:\n{stderr}",
+ );
+}
+
/// Test fork PR where branch exists but has no tracking config
/// Uses prefixed branch name `contributor/feature-fix` to avoid conflict
#[rstest]